Develop your own (trips) map with Mapbox (Beginner level)

MapBlogDevelopmentTripMapbox
5 months ago
Picture showing Mapbox's website and logo

What am I going to talk about?

On the article which presents the best tools to integrate a map on your blog, I was telling you about 4 different solutions to integrate a map on a website or on a blog. Among those solutions, you can find Mapbox, a well-known technology which will help you to display a map on your website, exactly as Google Maps services does.

We're going to see that map integration, is the most complicated solution, but also the cheapest one if you do it on your own. This is the way you'll reach the result you expect, that is branded for your website, but only if you have enough time to spend on it.

The note above isn't just pure luck: When I developed TraveledMap, I designed it in order to simplify usage of technologies like Mapbox or Google Maps, thinking about people who don't have time or don't have skills to use them.
Please note that I mainly used Mapbox with React, a web framework making it faster to develop, more reactive and less buggy, but it's more likely that your use case is pure Javascript ("Vanilla"). This is why I'll explain how to integrate a map with Mapbox without any framework  and I'll pay attention to explain how to do it with WordPress.

Summary



Create a map

To be able to start with Mapbox, you need to create an account, otherwise you won't be able to show a map. You can do it on this page. Once your account created and activated, you'll have access to your Dashboard, which contains a particular, very interesting piece of data:
Your access token (it should begin with pk.)

This access token is a key, which is necessary to be able to identify you when you'll want to show a map. You need to be identified for two main reasons:

  • It allows to link the map to your account, taking into account any change you did on maps of your Mapbox account. You can create custom styles for instance, thanks to the studio, and those styles wouldn't be found if you would use someone else's access token.
  • It also allows to count the number of map loads (or map displays) you asked for, which is necessary to have account and payment statistics.

Let's do this, let's show our first map !
I will explain how to do this in different steps, but don't worry, you'll find the final code at the end of this blog post.


To start with, open the file containing the HTML code of your page, or, on WordPress, edit the page that should show the map, by adding a new Custom HTML  bloc, and add this content:

<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css" rel="stylesheet" />


<div id="map" style="height: 500px; width: 100%"></div>

<script>
    mapboxgl.accessToken = 'Dont forget to replace this by your access token';
    var map = new mapboxgl.Map({
        container: 'map', // map container identifier
        style: 'mapbox://styles/mapbox/light-v10', // map style URL to use
        center: [2, 45], // default center of the map [lng, lat]
        zoom: 2 // default zoom
    });
</script>

Save, show the draft of your page and ... Eureka! 🎉
Now you should see the map displayed.

Your first map on a website or WordPress blog with Mapbox

Your first map on a website or WordPress blog with Mapbox

Let's split the code before in different pieces:

  • The two first lines are used to load the necessary resources to make the map work as expected:
    <script src="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js"></script>
    <link href="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css" rel="stylesheet" />
    
    Please note that the placement of those lines has an impact on the page speed. Ideally, they should be placed at the end of your site's <body> tag.
  • A single line is needed to place the map on the page, and it also defines the map container's style (500px height and 100% of the width):
    <div id="map" style="height: 500px; width: 100%"></div>
  • Finally, the script with let us to execute the code that allows us to load the map and show it:
    <script>
        mapboxgl.accessToken = 'Dont forget to replace this by your access token';
        var map = new mapboxgl.Map({
            container: 'map', // map container identifier
            style: 'mapbox://styles/mapbox/light-v10', // map style URL to use
            center: [2, 45], // default center of the map [lng, lat]
            zoom: 2 // default zoom
        });
    </script>

Don't forget to add your access token to this piece of code, otherwise, the map won't load.
Each parameter passed to the mapboxgl.Map initialization can be changed:

  • container: It should be the same as the id of the container's element (see above)
  • style: it's the map style. You can customize them or create new ones on the Mapbox Studio. Mapbox has 4 or 5 presets to help you get started quickly.  You can visualize them here.
  • center: this is the map's default center. The first figure (2) corresponds to the longitude, and the second one (45) corresponds to the latitude.
  • zoom: this is the default zoom, it should be a number between 0, which is the largest scale, the more dezoomed, and 20, which is the smallest scale, the more zoomed.
    With a zoom level equals to 20, you'll see the streets and homes. The best zoom level for a use case like showing worldwide trips is between 1 and 3.


Add markers

Now that the map is showing on the page with the zoom, center and style you chose, let's see how to add your trips on it (for instance). In this step, we'll create a list of destinations and show them on the map thanks to markers.

The first step is to create a single marker, so that we can understand how it works. Adding a marker on the map isn't complicated, you just need to keep the code we wrote to show the map and add this line  (just before closing the <script /> tag):

new mapboxgl.Marker()
    .setLngLat([2.35, 48.85])
    .addTo(map);

This line will add a pin (a marker) near Paris, at the following coordinates: 2.35, 48.85

Displaying a marker near Paris

Displaying a marker near Paris


During the second step we're going to create a list of trips and show a marker for each of them.
When using JavaScript (the language used in the previous lines), you can create lists of objects. In our use case, an object will represent a trip and will be represented by braces {}, and the list by brackets []
Here's an example with three trips:

var trips = [{ 
    coordinates: [2.35, 48.85],
}, { 
    coordinates: [-74, 40.71],
}, { 
    coordinates: [-7.99, 31.62],
}]

Now that we have a list, we have to iterate through the trips to show them (iterating is like doing an operation for each of them).
You can remove the previous piece of code (new Mapboxgl.Marker) and replace it with:

trips.forEach(trip => {
    new mapboxgl.Marker()
       .setLngLat(trip.coordinates)
       .addTo(map);
});

There should be 3 markers on the map now !  In order add your trips instead, you just have to replace those 3 objects by yours and add as many other objects as you want between the brackets.


Add trips' name

I think you may want to show the trip name under the marker. If it's the case, we can do it easily thanks to a Mapbox popup. Popups are really easy to use, we just have to add two lines to the previous code, showing the markers:

trips.forEach(trip => {
    new mapboxgl.Marker()
        .setLngLat(trip.coordinates)
        .setPopup(new mapboxgl.Popup({ anchor: 'top' }) // adds a popup
            .setHTML('<p>Trip to Marrakech</p>'))
        .addTo(map);
});

You should now be able to see the name "Marrakech" in a small white box under the marker, when clicking on it.
You probably noticed that whatever marker you click on, only Marrakech is written. To fix this, we're going to add a new proporty "name" to our trip objects:

var trips = [{ 
    coordinates: [2.35, 48.85],
    name: 'Paris'
}, { 
    coordinates: [-74, 40.71],
    name: 'New York'
}, { 
    coordinates: [-7.99, 31.62],
    name: 'Marrakech'
}]

and we're going to use it dynamically while iterating, just by replacing.setHTML('<p>Trip to Marrakech</p>')) by.setHTML('<p>' + trip.name + '</p>'))

Popup with Paris displayed in it

Popup with Paris displayed in it


Customize markers

Finally, we're going customize the markers by using an image that corresponds to your site branding. Only a few style lines are required to use the picture. Let's add a style tag just before the <div id="map">:

<style>
  .marker {
    background-image: url('https://www.traveledmap.com/images/home/marker-traveled.png');
    background-size: cover;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    cursor: pointer;
  }
</style>

It's also required that you create the marker on a custom element, that you'll add, by replacing the markers creation lines by those ones (please note that an offset of 15px is added because 15 is half of the marker's style height, defined above):

trips.forEach(trip => {
  var el = document.createElement('div');
  el.className = 'marker';

  new mapboxgl.Marker(el)
    .setLngLat(trip.coordinates)
    .setPopup(new mapboxgl.Popup({ anchor: 'top', offset: 15 })
      .setHTML('<span>' + trip.name + '</span>'))
    .addTo(map);
});

TL;DR

Here is the final result along with the final code
If you encounter any problem, if you have comments or if you need a developer to integrate a map on your website, don't hesitate to contact me at contact@traveledmap.com

Final result

Final result

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>My first map with Mapbox</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css" rel="stylesheet" />

<style>
  .marker {
    background-image: url('https://www.traveledmap.com/images/home/marker-traveled.png');
    background-size: cover;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    cursor: pointer;
  }
</style>


<div id="map" style="height: 500px; width: 100%"></div>

<script>
  mapboxgl.accessToken = 'Dont forget to replace this by your access token';

  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v10',
    center: [2, 45],
    zoom: 2
  });

  var trips = [{
      coordinates: [2.35, 48.85],
      name: 'Paris'
  }, {
      coordinates: [-74, 40.71],
      name: 'New York'
  }, {
      coordinates: [-7.99, 31.62],
      name: 'Marrakech'
  }];

  trips.forEach(trip => {
    var el = document.createElement('div');
    el.className = 'marker';

    new mapboxgl.Marker(el)
      .setLngLat(trip.coordinates)
      .setPopup(new mapboxgl.Popup({ anchor: 'top', offset: 15 })
        .setHTML('<span>' + trip.name + '</span>'))
      .addTo(map);
  });

</script>

</body>
</html>