Creating an Interactive Earth visualization with JavaScript and the Mapbox GL JS API
Tags: webdev, javascript, tutorial, maps
Published: 2023-07-15 12:56:29

---
title: Creating an Interactive Earth visualization with JavaScript and the Mapbox GL JS API
published: true
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wrgwvs7ycw2a956pmugf.png
tags: webdev, javascript, tutorial, maps
canonical_url: https://dev.to/sarahokolo/creating-an-interactive-earth-visualization-with-javascript-and-the-mapbox-gl-js-api-4464
---

## Introduction

Ever wanted to travel the world? wanted to get to see different locations in our planet? Well sometimes our pocket and time doesn't grant us such luxury, but don't worry, just hitch a ride with me and let's go around the world(from the comfort of your home I mean).
![holding back laugh](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clwink3fhrrpkjqbu9qu.gif)

In this article, I am going to walk you through how you can easily implement an interactive map into your project, that would enable you view our beautiful planet, from space, down to the very building of your house, or any other location of your choice.

Anyone with basic HTML, CSS and JavaScript skills would be able to follow along. So you, yes you, don't worry about not being well versed in any of the three, it's as easy as pie to implement, as the [Mapbox GL JS API](https://docs.mapbox.com/mapbox-gl-js/guides/) has been so very gracious to help with over 95% of the complexity of this task🤭.

[Mapbox](https://www.mapbox.com/) is a powerful vector-based rendering engine capable of rendering dynamic maps in real-time using [WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API). It allows developers to create interactive, customizable, and visually stunning maps and geospatial applications. 

Now that we know about Mapbox, let's get started with our project shall we? So buckle up, as we're about to take off.
![rocket take off](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtqtjlsl47k1uo1pt4wi.gif)


## Table Of Contents(TOC)

- [Setting Up the Html Structure](#suths)
- [Adding Styles to the Page](#asttp)
- [Registration and Obtaining Your Mapbox API Credentials](#raoymac)
- [Initializing the Map in your JavaScript File](#itmiyjf)
- [Setting Zooming and Panning Controls](#szapc)
- [Conclusion](#conclu)

<h2 id="suths">Setting Up the Html Structure</h2>
Before we get started, make sure you have created 3 empty files which are the Html, CSS and JavaScript files. Now, inside the Html file, we are just going to create our basic standard Html boilerplate before anything else.
```html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View the Earth</title>
</head>
<body>
    
</body>
</html>
```
Inside the `body` tag, we include the header section of our project:
```html
<header>
    <h1>View the Earth</h1>
</header>
```

Next, let's create the container that is going to hold our map element, as well as an extra `div` element that we are going to be styling later to create a shadow effect for more a 3D look of the planet.
```html
<div id="map-container">
    <div id="map"></div>
    <div id="shadow-overlay"></div>
</div>
```
After that, we create a little `button` element that would be responsible later on for resetting the zoom and pan level of the map.
```html
<button id="reset">Reset Map </button>
```
And that is basically all for our Html file. Now lets add a few styles to really beautify our page.

![spongebob and rainbow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4sqmwkcwvjvqtcaby9c.gif)


<h2 id="asttp">Adding Styles to the Page</h2>
Heading straight into our CSS file now, let us add some overall basic styling to the page first of all:
```css
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
```
Next, we style the body of the page:
```css
body{
    display:grid;
    place-items: center;
    min-height: 100vh;
    max-width: 100vw;
    background-image: url(https://images.unsplash.com/photo-1534796636912-3b95b3ab5986?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE2ODkyNjI2Nzl8&ixlib=rb-4.0.3&q=85);
    background-size: cover;
    background-attachment: fixed;
    background-position: center;
}
```
After that, lets go ahead to add styles to the rest sections of the page:
```css
header{
    padding-top: 5px;
    text-align: center;
    z-index:2;
}

h1{
    text-shadow: 2px 2px 5px #4069ff;
    color: aliceblue;
    letter-spacing: 2px;
    word-spacing: 5px;
    margin-bottom: 10px;
}

#map-container {
    position: relative;
    width: 70%;
    max-width:450px
}

#map{
    width: 100%; 
    height:100%;
    border-radius: 50%;
    padding-bottom: 100%;
    box-shadow: 1px 1px 50px #4069aa; 
}

#shadow-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    box-shadow: inset -20px -15px 30px #01011f;
    pointer-events: none; 
  }

button{
    margin-top: 10px;
    font-size: 20px;
    border-radius: 10px;
    background-color: #4069aa;
    padding: 10px;
    color: aliceblue;
    box-shadow: 0px 0px 50px #4069aa;
    border: none;
}
```

Okay, we are done dressing up our Html document in a pretty outfit🤭, let's get to the most fun parts of the project.

![happy minions ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ossjxqzkyl9blm7ct6sl.gif)


<h2 id="raoymac">Registration and Obtaining Your Mapbox API Credentials</h2>
To be able to make use of the mapbox GL JS API in your project, you are first required to have an account with them, so you can obtain your access token. This is a unique id that is given to every mapbox user, which enables them have access to all the amazing features mapbox has to offer.

To create an account with them is super easy. First, head into their [website](https://www.mapbox.com/), and then click on the **Start mapping for free** button
![mapbox landing page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yw6rmr661dsjln66w4uz.png)
After you have created an account with them, the next step you need to take is obtaining your access token. You can do this by logging into you account, which would take you to this page:
![mapbox home page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qsufr5pd7gc2362l455h.png)
Scroll down to **Access Tokens** and copy the default access token provided there and just place it somewhere safe for now, as we are going to be making use of it in our JavaScript file.


<h2 id="itmiyjf">Initializing the Map in your JavaScript File</h2>

When you are done signing up and obtaining your access token, on that same page go ahead and click on **Install Mapbox GL JS**, which would then take you to this page:
![install mapbox page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7em39aiss217nq5rzgu.png)

Because we want to keep this project as simple as possible, we would be making use of the Mapbox CDN and not the module bundler. So click on the **HTML** image. After that, you should see yourself right on this page:
![mapbox script tags](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mc606cu0zgj19y2aegl5.png)
Copy the script and link tags you find there, and place them inside the `head` tag in your Html file. This would enable your document have access to the map styles and functionalities. After you're done with that, click on the **Next** button, and it should take you to this page:

![mapbox initialization code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7xutgktd7fu65qun9kh.png) 
Now copy only the code that is imbetween the `script` tags, head into your JavaScript file and paste it in there. Replace `YOUR_MAPBOX_ACCESS_TOKEN` with your actual access token which you copied earlier, make sure it's still inside the double quotes.

There you have it, the map has been initialized in your project, as easy as pie. Now we need to modify just a few things in the code. For example, we need to change the map view style to give us a more 3d aerial view of the planet, for that, we simply head into the [mapbox styles page](https://docs.mapbox.com/api/maps/styles/) and select our desired style, which in this case would be the **Mapbox Satellite streets** style, you can find it by scrolling down on that page. Copy the style code beside it and replace the the value of the style property present in your JavaScript file with it. 


<h2 id="szapc">Setting Zooming and Panning Controls</h2>

Now that we are done Initializing the map in our project, we need to add and modify the pan and zoom levels accordingly. Inside the map object, set the initial zoom level of the map and also its starting position:
```javascript
center: [280.01, -5.01], // starting position
zoom: 1.5,
```
The center property takes in an array of 2, which is simply the longitude and latitude values(in that order) of the location you want to position to, you can set any location you want, simply just google the longitude and latitude values of the place, and place them in the array like that.

Outside the map object, we would need to set the minimum zoom level, so the map cant be zoomed out more than the specified value, in this case, we use ` 1.5 ` as our value:
```javascript
map.setMinZoom(1.5);
```
Next let us implement the functionality for our `reset map` button. In the JavaScript file, create a variable for the element to get its `id`:
```javascript
const reset = document.getElementById('reset');
```
After that, we create an `onclick` event for the element, which would enable us reset the initial values of the map's zoom level and position every time the button is clicked. We want to use the transition animation effect to achieve this, so we would be using the built-in `easeto()` mapbox function which takes in our `map` object.
```javascript
reset.onclick= ()=>{
  map.easeTo({
    zoom: 1.5,
    center: [280.01, -5.01],
    duration: 3000
  });
}
```
The `duration` property is used to set the value of how long we want the transition to last, in this case we set it to 3000 milliseconds( 3 seconds ).

And there, you have successfully created a live interactive visualization of earth. Cheers to you.
![cheers image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kan4mbsmcmjoddq2ubks.gif)


<h2 id="conclu">Conclusion</h2>

Well that's it for this article guys, you can view the result and entire code of this project in the pen below:
(**set pen zoom level to 0.5x on mobile for better view**)
{% codepen https://codepen.io/sarah-okolo/pen/NWEydRz %}

The Mapbox API still has a whole lot of addons and features you can incorporate into your own map to make it more dynamic and interesting, you can go to the Mapbox page to explore more of those features and all it has to offer. 

Hopefully you have learned something new, and can now also incorporate maps feature into any of your project.

Now, go ahead and view the entirety of our beautiful planet earth, explore the different locations you wish to visit😊. 
![All done](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jp1f0e95ghshbrq1wjm.gif)

If you have any questions, please, do not hesitate to ask them, I respond promptly. And as always, Happy Coding!🤗