Chapter 0: Introduction to Mapbox GL JS

Listen to this article

Hello good people! In this article, I want to introduce you to a library called Mapbox GL JS. This article will cover the basics like; What is Mapbox GL JS. What are the other alternatives? How to display a simple map? And finally, how to set up a base repository that we will use as a base for the next articles of this series.

As usual, you will find commit hashes when I'm talking about code from this base repository.

What is Mapbox GL JS? ๐Ÿค”

First of all, you need to know that Mapbox is the company name of the provider and maintainer of Mapbox GL JS. They also work on other solutions but let's not get ahead of ourselves.

Mapbox GL JS is a JavaScript library that uses WebGL to render interactive maps from vector tiles and Mapbox styles. [...]

Source

Simply put, Mapbox GL JS lets you display different formats of interactive maps using a technology called WebGL. What's pretty awesome about it is that it uses vector tiles to do so and it's very fast.

There is also a mobile SDK here which you should try if it's your cup of tea.

Mapbox as a company has a big portfolio of products such as custom map tiling service, navigation tools, point of interest search, and much more. You can check out their website, it's awesome!

But what about the other options in the market? ๐Ÿคนโ€โ™‚๏ธ

Of course, there are a lot of other options. Let's enumerate them:

  • Google Maps is pretty much a reference in the field. But its quotas might push you away from it.
  • OpenStreetMap is also a great alternative.
  • LeafletJS is also an awesome tool. Very well documented too!
  • DeckGL is also an underrated tool that's really worth the shot.
  • CesiumJS is much more advanced but can be amazingly powerful too!

Sadly, I can't list all of them here, but I think I've highlighted the big players.

You might now ask; Why should I work with Mapbox GL JS instead of other options then?

This is a legitimate question, and I advise you to research what every solution offers for your needs. As I always say, focus on your needs, not the technology.

In my client's case, we've chosen Mapbox GL JS after establishing a benchmark with some of the options I've enumerated above. Our goal was to display as much geographical data as possible while keeping the browser and the web application stable. Mapbox GL JS topped all our benchmark charts and proved very stable even with big data collections.

Prerequisites ๐Ÿ—

First of all, you'll need to create yourself an account here to have an access token. This will be mandatory for you to display a map. Don't worry Mapbox is very generous with the quotas ๐Ÿ˜€ !

Once you've created and validated your new Mapbox account, you can head to your account page, you'll see your account dashboard with your access tokens and other relevant information as below:

image.png

If you need your access token, you'll always find it here. For now, we'll work with your default token. But please don't share your token publicly as anyone will use it and deplete your quota.

If you head back to the documentation while connected with your Mapbox profile, you'll notice that code examples like here are already populated with your default access token which will be a handful for our first tests.

Our first map ๐Ÿ—บ

Let's create a folder for example called first-mapbox-example. Next, let's create a file inside and call it index.html. Open it with your favorite code editor and paste the code from this example page. If you open index.html with your favorite browser, you should see a map of New Jersey covering the browser's page like below:

image.png

โ„น Note: If the screen is all white, check your console, the error might be because you didn't set your access token. You'll have to set it in the following line:

mapboxgl.accessToken = 'SET_YOUR_TOKEN_HERE';

Now that we've displayed our map, let's try to understand how this code works and customize it for our needs. Let's start with the head of our page:

<link href="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>

As you can see, it's straightforward, we're referencing a stylesheet from Mapbox's API. This stylesheet is needed to display the map and other fun things we'll explore soon. Next, the JavaScript file is the full Mapbox GL JS library. For now, it's just linked as a resource, but we'll see how to use it as a module in the last section. Finally, the little style snippet just removes margins and padding from the default browser's stylesheet and sets our map div position to an absolute positioning to make the map resize properly following the window's size.

Let's move on to the body, you can see the following code:

<div id="map"></div>
<script>
    mapboxgl.accessToken = 'SET_YOUR_TOKEN_HERE';
    var map = new mapboxgl.Map({
        container: 'map', // container id
        style: 'mapbox://styles/mapbox/streets-v11', // style URL
        center: [-74.5, 40], // starting position [lng, lat]
        zoom: 9 // starting zoom
    });
</script>

As you can see, we have a div with an id "map" and a script tag. Inside that script, we can see that the first line is just defining our accessToken. Again this is mandatory so that Mapbox GL JS works. Just after, you can see we're initializing mapboxgl with some parameters:

  • container is the div that's supposed to hold the map content.
  • style tells Mapbox what map style we want to display, for example, satellite or terrain. We'll talk about this in the next article.
  • center takes an array of two coordinates as longitude and latitude, in the next section we'll try to play around with this.
  • zoom defines the level of zoom on the map we want to start with, a lower value like 5 will put the camera more away from the ground and a bigger value like 15 will put the camera very close to the ground.

Now that we understood how to get started with Mapbox, let's create a base repository that will be our base for the next guides in this series. You can directly fork the repository from here or follow step-by-step in the next section.

Configuring a repository ๐Ÿšฉ

Before we end this introduction guide, I would like to create a base repository that we'll use during this guide. I will guide you through how to use a template repository that I've prepared. It helps you create a frontend app with HTML, SCSS and, TypeScript.

โ„น Note: If you don't know what's TypeScript and SCSS, no worries! We're still doing JavaScript and CSS, I'll make sure to explain each concept that might be foreign to you. Plus it will be a good occasion for you to discover TypeScript and SCSS ๐Ÿ˜ !

Get started with a template repository ๐Ÿ‘• #a1d706a

Head to this repository here. Next, click on the green button "Use this template". You'll be redirected to a page similar to the user "Create a new repository" page. Fill-in your repository name, a simple description, and hit that "Create repository from template" button. Below a GIF capture of these steps:

use-repository-template.gif

Once done, clone your repository, open your favorite code editor, fire up your favorite terminal and input npm install. This will install the dependencies for the project. Once finished, you'll just need to run npm start and head to http://localhost:8080/ you'll see a white page with a simple "Hello Webpack and TypeScript โ™ฅ" text.

Setting up Mapbox GL JS โœ”

If you edit the index.html file in the project and copy-paste the HTML code we previously used and save, you'll see the same map we've set up. It's cool, but let's tidy up all this and make the project look more serious.

First, we need to install Mapbox GL JS as a dependency instead of using it as an external script. To do so, just type in your terminal npm install --save mapbox-gl, next we're going to move our code. Check out this commit diff here to understand what we did. I've refrained from putting the code snippets here to keep the article clear ๐Ÿ˜‰ .

Safely use your Mapbox access token ๐Ÿ”‘

You might have noticed that I've just left mapboxgl.accessToken = 'SET_YOUR_TOKEN_HERE'; in the code. This is because you should never commit your private tokens or keys. You might wonder; "How do I set up my Mapbox token without accidentally committing it in the code?"

The idea is simple, we'll create a config.json file and a config.sample.json file, the first will be your effective configuration file and will be added to the .gitignore file, this way, it will never be committed and your token will be safe. We'll commit the second file as a sample for other people who want to clone the repository and put their own Mapbox key. Let's do this.

Let's create a file named config.sample.json, its content will be as below:

{
    "mapboxKey": "SET_YOUR_TOKEN_HERE"
}

Now copy that same file as config.json and change the SET_YOUR_TOKEN_HERE with your own token. Don't commit anything for now!

Let's move on to our .gitignore and add the below last line to the file:

node_modules
.vscode
dist
/src/assets/config.json

Commit only your .gitignore file like here.

Finally, let's import our access token properly from our config.json file and set it up to Mapbox GL JS in our /src/app.ts file:

import './styles.scss';
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';

// We import our config.json file like any other module
import CONFIG from './assets/config.json';

// We assign the access token first thing by accessing it like a simple variable
mapboxgl.accessToken = CONFIG.mapboxKey;

const map = new mapboxgl.Map({
  container: 'map', // container ID
  style: 'mapbox://styles/mapbox/streets-v11', // style URL
  center: [-74.5, 40], // starting position [lng, lat]
  zoom: 9 // starting zoom
});

Now if you save and check your page, the map should display with no error. Congrats! Now you're importing dynamically your access token and it won't be committed accidentally ๐Ÿฅณ ! You can check out the final result (for now) in this commit.

Warp-up ๐Ÿ“ฆ

And that's it for now! In this article, we've discovered what's Mapbox GL JS. How to use it with our access token. How to set up our won repo and keep our access token safely and not committed. The next article in this series will be about our first map manipulations.

If you feel that I've forgotten a detail or didn't explain something well, please let me know.

Cheers!

Photo by @kjpargeter from Freepik.com.

No Comments Yet