Mapbox GL 101

Javier Portillo
Worldsensing TechBlog
6 min readJul 23, 2019

--

This article presents a little course to make your first Mapbox GL web application. This article has 100% interactive examples. We encourage you to run, modify, destroy and redo these examples because it’s the best way to learn.

Introduction

In the last Worldsensing Hack Week, my team played with Mapbox GL to adapt some of our products to a new Vector Tiles Map. It was only a test, but we learned a lot.

First of all, what is Mapbox GL? Mapbox gives us this short definition.

Mapbox GL is a suite of open-source libraries for embedding highly customizable and responsive client-side maps in Web, mobile, and desktop applications. […] You can also manipulate every aspect of the style’s appearance dynamically, because Mapbox GL renders vector tiles.

We will use JavaScript libraries for all our examples.

Firsts Steps

The first step is to display the map.

This example has the first step of all the Mapbox GL app: creating the map. Let’s see the HTML code.

<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.js'></script><link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.css' rel='stylesheet' />

First, we need to import Mapbox GL library. Then, in the JavaScript code:

mapboxgl.accessToken = ' <no token for ICGC>';
map = new mapboxgl.Map({
container: 'map',
style: 'https://tilemaps.icgc.cat/tileserver/styles/blavos.json',
center: [2.16859, 41.3954],
zoom: 13,
maxZoom: 14.8,
hash: true,
pitch: 45
});

We construct the Mapbox GL map. Its more important parameters are:
- container: div id where the map will be placed.
- style: it is the map style. If we use a Mapbox style we need an access token, but we use an ICGC style, and it is free to use. Thanks, ICGC!
- center, zoom, pitch: they are the initial status of the map.

Add Layers

Good, now let’s add a new layer.

Now we can see 3 points on the map. To add a new layer we need two things:
- A source: in the example, the source is a literal GeoJSON.
- A layer: the layer has the configuration to show the source.

Technically, all the layers of the map (roads, buildings, sea, terrain, etc) are the same: a source and a layer, but out layer is the last created, so, it is in the top of the layers.

To add the new source we call the function map.addSource. Its parameters are an id to reference the data and a GeoJSON. In this case, it contains 3 points with no properties.

Then, we add a layer, with function map.addLayer. The parameter is a JSON with the layer properties: source id, layer id, type and paint properties.

We drew circles, but we can draw other shapes.

There is a fill extrude layer. Mapbox GL has many kinds of layers and all have different paint properties and need different sources. Mapbox GL has good documentation of all of them.

In this example we add an important change: the two polygons have a different height. Each polygon is a feature in the GeoJSON, and each feature has a “property” named “height” with different values. Then, we set the extrusion height with this property:

map.addLayer({
"id": "area_example",
"type": "fill-extrusion",
"source": "parks",
"paint": {
"fill-extrusion-color": "rgba(86, 206, 60, 1)",
"fill-extrusion-opacity": 0.5,
"fill-extrusion-height": ['get', 'height'],
}
});

Value ['get', 'height'] gets the feature property “height”. We can do a lot of complex expressions; to more information go to Mapbox documentation.

Interact With Layers

Now we can draw on the map, the next step is to interact with it.

Let’s click the extruded polygons!

For this example, the first of all is to detect the layer interaction, the “click”. To do it we use the function map.on, which needs 3 parameters:
- Event type: in this example, we use “click”, but there are others as “mouseover”, “mouseleave” and more.
- Layer id: the layer id that will be affected by this function.
- Callback: the callback function is called when the event is fired.

Now, we can detect the layer events, the next step is to change the layer properties. In this case, we change the layer paint properties, Mapbox GL has a lot of functions to modify the layers and sources dynamically. These are some of them:
- map.setPaintProperty: this is the function used in the example, changes a layer paint property.
- map.setLayoutProperty: changes a layer layout property.
- map.setFeatureState: changes a source feature state.
- map.setFilter: changes the layout filter.
- Much more!

We played with the layers, now it’s time to play with the data.

Click the button and the circles!

In this example we only change the source data:
1. With the button, we add a feature in the GeoJSON and update the source.
2. Clicking a circle, we change the property “color” of this circle and update the source. In the “click” event, the callback has a parameter that will be the data from the clicked feature. With this data, we can know what circle is clicked.

These two operations require the source update. First, get the source with map.getSource and the source id as a parameter, and then update the data with source.setData and the new data as a parameter.

For the last example, we will use an existing source and layer from the map.

The best way to explore map sources and layers is Maputnik. Click open and load the style from the URL.

Maputnik view with all the layers.

The last example creates a new layer with the “building” source (an existing source) and defines an event when the mouse is over the “building-copy” layer (an existing layer). As we said before, the existing layers in the map are ordinary layers, so, we can apply to it all we learned before.

In the map.addLayer function we pass a new parameter, this parameter is a layer id and the new layer is created just below this layer. We do this to evade that the new layer covers the map symbols.

Difference between add the new layer below the symbols or in the top of the map

Finally, the polygon extrusion depends on the feature state “hover”. This state is individual for each polygon. We set it to “true” when the mouse is over the building and false if not. In addition, layer property fill-extrusion-height depends on the “hover” state as follows:

"fill-extrusion-height": [
"case",
["feature-state", "hover"],100,
0
]

This expression mean that if “hover” is “true” sets fill-extrusion-height to 100, else sets it to 0.

Conclusion

With this article we have learned to:
- Load a map.
- Add sources and layers to the map.
- Interact with the map layers.
- Modify layers and sources dynamically.

These are good first steps but Mapbox GL has much more, don’t stop reading about it in Mapbox website. Examples.

Special greetings to the ICGC for helping us in the Hack Week and for their resources. I hope you liked this article and it could help you.

If you found this post interesting, we are always hiring and interested in meeting all types of engineers, regardless of your skills or what tools you use day-to-day. Your intelligence, creativity, energy and enthusiasm are much more important to us than your experience with our stack.

Check out our careers page in here — https://worldsensing.wpengine.com/engineering/

Thanks for reading!

--

--