avatarCaleb

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

7269

Abstract

(where your custom JavaScript code is located).</li></ul><p id="b492">In essence, this HTML file is setting up a full-screen map by linking to the necessary Leaflet files, creating a container for the map, and linking to a custom JavaScript file (<code>app.js</code>) for additional functionality.</p><h1 id="fa60">Adding Leaflets and Presenting Openstreetmap</h1><p id="88b4">In <code>app.js</code>, initialize the map using <code>L.map</code> and set the view to a global view.</p><div id="cf44"><pre><span class="hljs-keyword">const</span> <span class="hljs-keyword">map</span> = L.<span class="hljs-keyword">map</span>(<span class="hljs-string">'map'</span>).setView([<span class="hljs-number">20</span>, <span class="hljs-number">0</span>], <span class="hljs-number">3</span>);</pre></div><p id="3d9e"><code>[20, 0]</code>: These are the latitude and longitude coordinates for the initial center point of the map. <code>20</code> is the latitude and <code>0</code> is the longitude. It will center the map roughly around Northern Africa.</p><p id="892a"><code>3</code>: This is the initial zoom level of the map. The zoom level controls how far in or out the map is zoomed, with higher numbers being zoomed in further. A zoom level of <code>3</code> is a moderately zoomed out view, showing a large portion of the world map.</p><p id="26a6">Then, add the OpenStreetMap tile layer to your map with <code>L.tileLayer</code> and add it to your map with <code>.addTo(map)</code>.</p><div id="a602"><pre>L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '<span class="hljs-symbol">&copy;</span> <span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.openstreetmap.org/copyright"</span>></span>OpenStreetMap<span class="hljs-tag"></<span class="hljs-name">a</span>></span> contributors' }).addTo(map);</pre></div><p id="7150">This step lays the foundation for your map and connects it to the open-source map from OpenStreetMap.</p><h1 id="e0fc">Adding geo.json for Borders</h1><p id="375e">For setting up the country borders on your map, you will need a geo.json file. Follow these steps to generate and add a geo.json file to your project:</p><ol><li>Visit <a href="https://geojson-maps.ash.ms/">https://geojson-maps.ash.ms/</a>.</li><li>On this website, you can generate a geo.json file containing the border data for all countries. Select the countries or areas you want to include and download the generated geo.json file.</li><li>Place the downloaded geo.json file in the root directory of your project and rename it to <code>custom.geo.json</code>.</li></ol><p id="1578">In <code>app.js</code>, fetch this <code>custom.geo.json</code> file, which contains the border data for the countries:</p><div id="af49"><pre><span class="hljs-title function_">fetch</span>(<span class="hljs-string">'custom.geo.json'</span>) .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">response</span>) =></span> response.<span class="hljs-title function_">json</span>()) .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {...});</pre></div><p id="b0dd">This file will be used to display the borders of the selected countries on the map. The countries’ borders will be visible, giving a clear distinction between each country on the map</p><p id="912a">If you’re not comfortable with fetch, please read this article:</p><div id="2ecc" class="link-block"> <a href="https://blog.devgenius.io/api-calls-in-javascript-fetch-the-universe-with-nasas-api-dc375f32b924"> <div> <div> <h2>API Calls in Javascript: Fetch() the Universe with NASA’s API</h2> <div><h3>Hello there, fellow code enthusiasts! Today, we’re about to embark on an exciting journey into the cosmos using…</h3></div> <div><p>blog.devgenius.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*TIasH93FWj2VQj_Cgwbg-A.jpeg)"></div> </div> </div> </a> </div><h1 id="6db1">Building the Logic for Highlighting Visited Countries</h1><p id="e8b2">The logic for highlighting visited countries involves checking if the country name from the GeoJSON data is included in the <code>visitedCountries</code> array.</p><p id="1550">If it is, style the country with a different color and opacity.</p><div id="3ee0"><pre><span class="hljs-selector-tag">L</span><span class="hljs-selector-class">.geoJSON</span>(data, { style: (feature) => { if (visitedCountries.includes(feature.properties.name)) { return { <span class="hljs-attribute">color</span>: <span class="hljs-string">'#03DAC6'</span>, <span class="hljs-attribute">fillColor</span>: <span class="hljs-string">'#03DAC6'</span>, <span class="hljs-attribute">fillOpacity</span>: <span class="hljs-number">0.3</span> }; } return { <span class="hljs-attribute">color</span>: <span class="hljs-string">'#E0E0E0'</span>, <span class="hljs-attribute">fillColor</span>: <span class="hljs-string">'#fff'</span>, <span class="hljs-attribute">fillOpacity</span>: <span class="hljs-number">0.1</span> }; } })<span class="hljs-selector-class">.addTo</span>(map);</pre></div><p id="d1ae">This will visually distinguish the visited countries from the others on the map.</p><p id="05c2">At the end, your <code>app.js</code> should look like this:</p><div id="e19f"><pre><span class="hljs-keyword">const</span> map = L.<span class="hljs-title function_">map</span>(<span class="hljs-string">'map'</span>).<span class="hljs-title function_">setView</span>([<span class="hljs-number">20</span>, <span class="hljs-number">0</span>], <span class="hljs-number">3</span>);

L.<span class="hljs-title function_">tileLayer</span>(<span class="hljs-string">'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'</span>, { <span class="hljs-attr">attribution</span>: <span class="hljs-string">'&copy; <a href="https://www.openstreetmap.org/copyright"&gt;OpenStreetMap&lt;/a> contributors'</span> }).<span class="hljs-title function_">addTo</span>(map);

<span class="hljs-title function_">fetch</span>(<span class="hljs-string">'custom.geo.json'</span>) .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">response</span>) =></span> response.<span class="hljs-title function_">json</span>()) .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> { L.<span class="hljs-title function_">geoJSON</span>(data, { <span class="hljs-attr">style</span>: <span class="hljs-function">(<span class="hljs-params">feature</span>) =></span> { <span class="hljs-keyword">if</span> (visitedCountries.<span class="hljs-title function_">includes</span>(feature.<span class="hljs-property">properties</span>.<span class="hljs-property">name</span>)) { <span class="hljs-keywor

Options

d">return</span> { <span class="hljs-attr">color</span>: <span class="hljs-string">'#03DAC6'</span>, <span class="hljs-attr">fillColor</span>: <span class="hljs-string">'#03DAC6'</span>, <span class="hljs-attr">fillOpacity</span>: <span class="hljs-number">0.3</span> }; } <span class="hljs-keyword">return</span> { <span class="hljs-attr">color</span>: <span class="hljs-string">'#E0E0E0'</span>, <span class="hljs-attr">fillColor</span>: <span class="hljs-string">'#fff'</span>, <span class="hljs-attr">fillOpacity</span>: <span class="hljs-number">0.1</span> }; } }).<span class="hljs-title function_">addTo</span>(map); });

<span class="hljs-keyword">const</span> visitedCountries = [ <span class="hljs-string">'Spain'</span>, <span class="hljs-string">'Portugal'</span>, <span class="hljs-string">'Italy'</span>, <span class="hljs-string">'Morocco'</span>, <span class="hljs-string">'United Kingdom'</span>, <span class="hljs-string">'Austria'</span>, <span class="hljs-string">'Germany'</span>, <span class="hljs-string">'Belgium'</span>, <span class="hljs-string">'Netherlands'</span>, <span class="hljs-string">'United States of America'</span>, <span class="hljs-string">'Canada'</span>, <span class="hljs-string">'Mexico'</span>, <span class="hljs-comment">// etc</span> ];</pre></div><h1 id="5d94">Conclusion</h1><p id="fb24">And there you have it — a personalized map of visited countries built with basic HTML and JavaScript, and spiced up with Leaflet and GeoJSON data.</p><p id="ae40">This project is a testament to the power and simplicity of JavaScript, and a fantastic starting point for JavaScript beginners to work on a highly visual and original project.</p><p id="48dd">You can further enhance this by adding interactivity like pop-ups with your travel photos or notes for each country.</p><p id="9121">Take this as a starting point, and let your creativity flourish in your future JavaScript endeavors!</p><div id="229c" class="link-block"> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"> <div> <div> <h2>Using the Fetch API - Web APIs | MDN</h2> <div><h3>The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests…</h3></div> <div><p>developer.mozilla.org</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*bEeHWk4Wkle5ClBk)"></div> </div> </div> </a> </div><div id="a7c0" class="link-block"> <a href="https://leafletjs.com/"> <div> <div> <h2>Leaflet - an open-source JavaScript library for interactive maps</h2> <div><h3>Leaflet is a modern, lightweight open-source JavaScript library for mobile-friendly interactive maps.</h3></div> <div><p>leafletjs.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*_UABL836wJrHtA8G)"></div> </div> </div> </a> </div><div id="c9c8" class="link-block"> <a href="https://geojson-maps.ash.ms/"> <div> <div> <h2>GeoJSON Maps of the globe</h2> <div><h3>Click the map to select your countries or choose from the presets to the right.</h3></div> <div><p>geojson-maps.ash.ms</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div> </div> </div> </a> </div><div id="65f4" class="link-block"> <a href="https://medium.com/@calebpr/subscribe"> <div> <div> <h2>Get an email whenever Caleb publishes.</h2> <div><h3>Get an email whenever Caleb publishes. By signing up, you will create a Medium account if you don’t already have one…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*pPSGj3ORvqLvuBYg)"></div> </div> </div> </a> </div><p id="91bd"><i>Enjoyed the read? For more on Web Development, JavaScript, Next.js, Cybersecurity, and Blockchain, check out my other articles here:</i></p><div id="7e3a" class="link-block"> <a href="https://readmedium.com/a-roadmap-to-my-medium-writings-fd04e14cffd7"> <div> <div> <h2>A Roadmap to My Medium Writings</h2> <div><h3>undefined</h3></div> <div><p>undefined</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*FO4S90VIpPA05s9cP-gFPQ.png)"></div> </div> </div> </a> </div><p id="8496"><i>If you have questions or feedback, don’t hesitate to reach out at [email protected] or in the comments section.</i></p><p id="c73a"><i>[Disclosure: Every article I pen is a fusion of my ideas and the supportive capabilities of artificial intelligence. While AI assists in refining and elaborating, the core thoughts and concepts stem from my perspective and knowledge. <a href="https://readmedium.com/how-does-ai-help-me-write-my-articles-5df265d16527">To know more about my creative process, read this article.</a>]</i></p><div id="a005" class="link-block"> <a href="https://readmedium.com/how-does-ai-help-me-write-my-articles-5df265d16527"> <div> <div> <h2>How Does AI Help Me Write My Articles?</h2> <div><h3>The Medium landscape has seen a transformation, with an increasing number of articles appearing to have the distinct…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*sURudlO3SS5ntthELFumcg.jpeg)"></div> </div> </div> </a> </div><h1 id="e6d0">In Plain English</h1><p id="85cf"><i>Thank you for being a part of our community! Before you go:</i></p><ul><li><i>Be sure to <b>clap</b> and <b>follow</b> the writer! 👏</i></li><li><i>You can find even more content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a><b> 🚀</b></i></li><li><i>Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. 🗞️</i></li><li><i>Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a><b>(X</b></i>), <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><b><i>YouTube</i></b></a>, and <a href="https://discord.gg/XxRS92b2"><b><i>Discord</i></b></a><b><i>.</i></b></li></ul></article></body>

A Beginner’s JavaScript Tutorial: Visualizing Your Travels with OpenStreetMap

Embark on an exciting journey into the world of JavaScript by building a simple and visually appealing project — “Where I’ve Been.”

This tutorial will guide you through the process of combining a Leaflet map with GeoJSON data to highlight all the countries you have visited.

Presentation of the Project

“Where I’ve Been” is a project that allows you to visually highlight and display the countries you’ve visited on a map, using Leaflet for mapping and GeoJSON data for country borders.

It’s an excellent way to delve into JavaScript while working on a fun and personal project that brings your travel history to life.

I’d also like to say that it’s crucial to attempt to comprehend each segment of the code.

While it might seem challenging initially, understanding the functionality behind each line is instrumental in grasping JavaScript’s essence.

Your learning will be significantly enriched through this exploration.

This project is a unique project that seamlessly blends technology with your personal experiences. It’s an engaging way to familiarize yourself with JavaScript, offering a tangible and visual result of your coding efforts.

Furthermore, showcasing this project on your GitHub can be a great addition to your portfolio.

It demonstrates your skills in working with maps, handling JSON data with fetch, and integrating various technologies, making it a valuable project for both learning and demonstrating your abilities.

What we’re going to build

Prerequisites

Before starting this project, you should have a basic understanding of HTML and JavaScript.

Familiarity with JSON will be helpful but not necessary.

Project Initialization

Initialize a new npm project:

npm init -y

Then, install Leaflet:

npm install leaflet

Create two files in your project directory: index.html and app.js.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Visited Countries Map</title>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <style>
        #map {
            height: 100vh;
            width: 100%;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <script src="app.js"></script>
</body>
</html>

This HTML code sets up the basic structure for the project. Here’s a quick explanation of each part:

Inside the <head> tag:

  • <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />: This link tag includes the Leaflet CSS file from a CDN (Content Delivery Network), which provides the basic styles for the Leaflet map.

Inside the <style> tag:

  • The CSS rules target the #map element, setting it to take the full height and width of the viewport (100vh means 100% of the viewport height), positioning it absolutely at the top left corner of the page. This ensures that the map covers the entire visible area of the webpage.

Inside the <body> tag:

  • <div id="map"></div>: This div tag with an id of map is where the Leaflet map will be rendered.
  • The two <script> tags at the bottom of the body tag include the Leaflet JavaScript library (which provides the mapping functionality) and the app.js file (where your custom JavaScript code is located).

In essence, this HTML file is setting up a full-screen map by linking to the necessary Leaflet files, creating a container for the map, and linking to a custom JavaScript file (app.js) for additional functionality.

Adding Leaflets and Presenting Openstreetmap

In app.js, initialize the map using L.map and set the view to a global view.

const map = L.map('map').setView([20, 0], 3);

[20, 0]: These are the latitude and longitude coordinates for the initial center point of the map. 20 is the latitude and 0 is the longitude. It will center the map roughly around Northern Africa.

3: This is the initial zoom level of the map. The zoom level controls how far in or out the map is zoomed, with higher numbers being zoomed in further. A zoom level of 3 is a moderately zoomed out view, showing a large portion of the world map.

Then, add the OpenStreetMap tile layer to your map with L.tileLayer and add it to your map with .addTo(map).

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

This step lays the foundation for your map and connects it to the open-source map from OpenStreetMap.

Adding geo.json for Borders

For setting up the country borders on your map, you will need a geo.json file. Follow these steps to generate and add a geo.json file to your project:

  1. Visit https://geojson-maps.ash.ms/.
  2. On this website, you can generate a geo.json file containing the border data for all countries. Select the countries or areas you want to include and download the generated geo.json file.
  3. Place the downloaded geo.json file in the root directory of your project and rename it to custom.geo.json.

In app.js, fetch this custom.geo.json file, which contains the border data for the countries:

fetch('custom.geo.json')
    .then((response) => response.json())
    .then((data) => {...});

This file will be used to display the borders of the selected countries on the map. The countries’ borders will be visible, giving a clear distinction between each country on the map

If you’re not comfortable with fetch, please read this article:

Building the Logic for Highlighting Visited Countries

The logic for highlighting visited countries involves checking if the country name from the GeoJSON data is included in the visitedCountries array.

If it is, style the country with a different color and opacity.

L.geoJSON(data, {
    style: (feature) => {
        if (visitedCountries.includes(feature.properties.name)) {
            return { color: '#03DAC6', fillColor: '#03DAC6', fillOpacity: 0.3 };
        }
        return { color: '#E0E0E0', fillColor: '#fff', fillOpacity: 0.1 };
    }
}).addTo(map);

This will visually distinguish the visited countries from the others on the map.

At the end, your app.js should look like this:

const map = L.map('map').setView([20, 0], 3);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

fetch('custom.geo.json')
    .then((response) => response.json())
    .then((data) => {
        L.geoJSON(data, {
            style: (feature) => {
                if (visitedCountries.includes(feature.properties.name)) {
                    return { color: '#03DAC6', fillColor: '#03DAC6', fillOpacity: 0.3 };
                }
                return { color: '#E0E0E0', fillColor: '#fff', fillOpacity: 0.1 };
            }
        }).addTo(map);
    });

const visitedCountries = [
    'Spain', 
    'Portugal', 
    'Italy', 
    'Morocco', 
    'United Kingdom', 
    'Austria', 
    'Germany',
    'Belgium',
    'Netherlands',
    'United States of America',
    'Canada',
    'Mexico',
    // etc
];

Conclusion

And there you have it — a personalized map of visited countries built with basic HTML and JavaScript, and spiced up with Leaflet and GeoJSON data.

This project is a testament to the power and simplicity of JavaScript, and a fantastic starting point for JavaScript beginners to work on a highly visual and original project.

You can further enhance this by adding interactivity like pop-ups with your travel photos or notes for each country.

Take this as a starting point, and let your creativity flourish in your future JavaScript endeavors!

Enjoyed the read? For more on Web Development, JavaScript, Next.js, Cybersecurity, and Blockchain, check out my other articles here:

If you have questions or feedback, don’t hesitate to reach out at [email protected] or in the comments section.

[Disclosure: Every article I pen is a fusion of my ideas and the supportive capabilities of artificial intelligence. While AI assists in refining and elaborating, the core thoughts and concepts stem from my perspective and knowledge. To know more about my creative process, read this article.]

In Plain English

Thank you for being a part of our community! Before you go:

JavaScript
Web Development
Programming
Learning To Code
Open Source
Recommended from ReadMedium