Skip to content

MapboxGL.js style json

NieneB edited this page Jul 9, 2018 · 11 revisions

Making our own style.json

The link style: 'mapbox://styles/nieneb/cjg3h8yp80oi82rldxukpu0oi', contains everything what is needed to show the vecotor tile map:

  • The vector tile source.
  • The styling information.
  • Fonts and Glyphs

Mapbox Studio's style editor provides the user interface where you can define your map style. Behind the scenes, Studio creates the style.json and hosts it on the Mapbox Styles API when published. This style is then accessible via endpoint to add to your map.

If we use the Mapbox hosting we need an access token. But we can also generate and host this all ourselves! We can do this by making a style.json file.

The style definition is most commonly supplied in a JSON format. 🔗 Mapbox provides good documentation on the style specifications

Here we will make our own style.json.

The style.json

The map style itself is written as rules which define its visual appearance using the Mapbox GL Style Specification. It specifies:

This is the basics of a style.json:

{
    "version": 8,
    "name": "Mijn eigen Stijl",
    "sprite": "url",
    "glyphs": "url/{fontstack}/{range}.pbf",
    "sources": {...},
    "layers": [...]
}

The 2 most important for now are the sources and the layers. The sources tell us where our data is coming from. Vector Tiles or GeoJSON data for example. By setting layers we can style every separate layer available in the vector tiles and assigning it colours etc.

▶️ Have a look at this file style.json in the text editor.

In order to use this we need to add the style file to the JavaScript map definition, instead of the mapbox url. We can also remove the access token now.

var map = new mapboxgl.Map({
        container: 'map',
        style: 'style.json',
        hash: true,
        zoom: 11,
        pitch: 60,
        bearing: 62.4,
        center: [ 4.8, 52.4]
    });

▶️ Save the style.json file in 📂yourDirectory.

▶️ Change the code in main.js so we are using our own style file. Remove the access token.

Sources

For now we start with 1 source, namely our vector tiles that are hosted by PDOK:

"sources": {
    "pdok":{
        "type": "vector",
        "tiles":  ["http://geodata.nationaalgeoregister.nl/beta/topotiles/{z}/{x}/{y}.pbf"]
    }
},

Layers

Next we can create layers, accordingly on what layers are available in the vector data. The first layer is a background layer with the background fill color white. Then we call a admin layer which is available in the vector tiles. We apply a filter to the layer in order to get only the province boundaries.

"layers":[ 
        { 
            "id":  "background",
            "type": "background",
            "paint": {
                "background-color":"#FFFFFF"
                }
        },
        {
            "id": "admin",
            "type": "fill",
            "source": "pdok",
            "source-layer": "admin",
            "maxzoom": 22,
            "minzoom": 0,
            "filter": ["==", "lod1", "province"],
            "paint": {
                "fill-color" :"#54D8CC",
                "fill-outline-color": "#ffffff"
            }
        }
    ]

ℹ️ The "id" is a custom name you give to the layer. You can give it any name you like.

ℹ️ The "source" is the name of the source provided in the beginning of the style object. We called it "pdok".

ℹ️ The "source-layer" is the name of the data layer in the vector tiles. This information is fixed. We provided all the names of the layers for you already. A bit further on we will explain how you can request the vector tile information.

ℹ️ "type" is the rendering type of the layer. It can be one of fill, line, symbol, circle, fill-extrusion, raster or background.

ℹ️ "paint" Default paint properties for this layer.

There are more options you can give to a layer. For example:

  • filter
  • minzoom
  • maxzoom

We can go on and on with adding layers.

▶️ Have a look at http://geodata.nationaalgeoregister.nl/beta/topotiles-viewer/styles/achtergrond.json to see a complete styling JSON for getting a map of the Netherlands.

▶️ Also have a look at the PDOK Vector Tile documentation on how the vector tile set is build up.

Adding a GeoJSON

We can add multiple sources to our style spec. Let's add our points from the GeoJSON.

"aardbeving_points":{
    "type": "geojson",
    "data": "../cursusdata/aardbevingen_NL.geojson"
}

▶️ Add the source to the style.json

And define a point layer:

{
    "id": "aardbeving",
    "type": "circle",
    "source": "aardbeving_points",
    "maxzoom": 22,
    "minzoom": 0,
    "paint":{
        "circle-radius": 5,
        "circle-color":{
            "type": "categorical",
            "property": "TYPE",
            "stops":[
                ["ind", "#f3ec9c"],
                ["tec", "#F5CB5B"]
            ]
        }
    }
}

▶️ Try the same for the municipalities!

Slow?

Adding a lot of GeoJSON's makes the map slow.. Therefore Vector Tiles are so important! We created the tiles for you already. This is the source URL:

https://vt1.maps.geocoders.nl/gmd/{z}/{x}/{y}.pbf

▶️ See if you can replace the GeoJSON source by the custom vector tile source. Also do not forget to change your layer type and style!

The custom tile set contains the following layers:

  • gemeenten (polygonen)
  • aardbevingen_point (punten)
  • aardbevingen_buffer (polygonen)

Make a beautiful map visualization.

▶️ Try adding more layers, like roads and buildings. Change the colors and make your own map!

Change your map settings so you get a nice view. Change colors, add extrusions and layers. Also see if you can use filters.

🔗 Make use of the Mapbox style spec: https://www.mapbox.com/mapbox-gl-js/style-spec/

🔗 Mapbox also provides a lot of examples: https://www.mapbox.com/mapbox-gl-js/example/simple-map/

Think about

  • Color
  • Typography
  • Icons
  • Texture

But also about:

  • Hierarchy
  • Scale
  • Density
  • Zoom levels

For inspiration: :link: Have a look at https://www.mapbox.com/resources/guide-to-map-design-part-1.pdf

From here on the steps do not contain any specific action but are just an explanation about the possibilities in the style.json. You can use these to create your own map.

🔗 https://www.mapbox.com/help/glossary/

When you are happy with your map design, let's go and publish it online!

➡️ Go to the next step hosting on github!


WebGL support

Do you want a pop-up when someone opens you application and does not have WebGL support? Add the following code to your JavaSript file:

    // Check for Mapbox gl support:
    if (!mapboxgl.supported()) {
        alert('Your browser does not support Mapbox GL');
    };

Glyphs & Fonts

In order to add labels we need a font. Fonts have also to be converted to pbf, in order to render them with WebGL, these are called Glyphs. Mapbox provides some fonts glyphs but then there are also some open source alternatives and of course we can host them ourselves. (see Advanced Glyps, Fonts)

We add the glyphs reference at the top of our style specification.

{
    "version": 8,
    "name": "Mijn eigen Stijl",
    "sprite": "url",
    "glyphs": "url/{fontstack}/{range}.pbf",
    "sources": {...},
    "layers": [...]
}

Using Mapbox fonts is possible by adding the glyphs to the style.json:

"glyphs": "mapbox://fonts/openmaptiles/{fontstack}/{range}.pbf",

But you do need your mapbox access token again.

If you do not want to depend on the Mapbox token we can use free providers or make our own. For example using fonts from openmaptiles:

"glyphs": "http://fonts.openmaptiles.org/{fontstack}/{range}.pbf",

In the advanced tutorial Glyphs you can learn how to transform you own font to pbf range.

Now we can add a label layer of type symbol :

{
            "id": "high_prior_labels",
            "type": "symbol",
            "source": "pdok",
            "source-layer": "label",
            "maxzoom": 20,
            "minzoom": 5,
            "filter": ["==", "z_index", 1000000],
            "layout": {
                "visibility": "visible",
                "symbol-placement": "point",
                "symbol-avoid-edges" : false,
                "text-field":"{name}",
                "text-font": ["Open Sans Regular"],
                "text-size": 20,
                "text-max-width": 5,
                "text-anchor": "center",
                "text-line-height": 1,
                "text-justify": "center",
                "text-padding": 20,
                "text-allow-overlap": false
            },
            "paint":{
                "text-opacity": 1,
                "text-color": "#535353"
            }
        }

There are a lot of options to style your labels. Have a look at :https://www.mapbox.com/mapbox-gl-js/style-spec#layers-symbol

The most important is "text-field" : "{name}". This takes the name attirubute to assign the label text.

Then "text-font":"["Open Sans Regular"] gets the Open Sans font which is available at our glyphs link.

"text-size" and "text-color" are also very important!

▶️ Add labels to your map! Use the PDOK labels. In the PDOK vector Tile Documentation you can find the layer name.

Glyph sources:

Mapbox Fonts

"glyphs": "mapbox://fonts/openmaptiles/{fontstack}/{range}.pbf",

Open map tiles Glyphs

"glyphs": "http://fonts.openmaptiles.org/{fontstack}/{range}.pbf",

"glyphs" : "https://free.tilehosting.com/fonts/{fontstack}/{range}.pbf?key={key}"

Maptiler

"glyphs" : "https://maps.tilehosting.com/fonts/{fontstack}/{range}.pbf.pict?key=ownkey"

Sprites & Icons

A sprite is a single image containing all icons included in a style. Sprites are often used in web development and even video games to improve performance. By combining lots of small images into a single image (sprite), you can reduce the number of requests needed to fetch all the images, improving performance and making your map faster.

🔗 https://www.mapbox.com/help/define-sprite/ 🔗 https://www.mapbox.com/mapbox-gl-js/style-spec/#sprite

Your style requires the image sprites used for patterns and icons.

"sprite": "http://openmaptiles.org/sprites/"

The link contains 2 files:

  • a png file with the images
  • a json file with the x and y location and reference name to the images.

The 2 files have the same file name.

Example of an icon in the json file:

"airport-15": {
  "width": 42,
  "height": 42,
  "x": 76,
  "y": 300,
  "pixelRatio": 2,
  "visible": true
}

This means that you can reference an icon by name, such as "airport-15", and our map renderer will reference the JSON file to get data about the icon and then only show the sprite at that specific icon.

In order to create your own sprites and self-host them via HTTP, you need to use the spritezero-cli. See the advanced Sprite tutorial to make them yourself.

For now we can use the OpenMaptile sprites. If you have a look at the Openmaptiles Github you can find the available icons and their reference name.

Use this sprite source in your style.json:

"sprite": "https://openmaptiles.github.io/klokantech-basic-gl-style/sprite"

To make a icon in your map we need a layer with type symbol:

{
           "id": "poi-park",
           "type": "symbol",
           "source": "oms",
           "source-layer": "poi",
           "minzoom": 15,
           "filter": [
               "all",
               [
                   "==",
                   "$type",
                   "Point"
               ],
               [
                   "in",
                   "subclass",
                   "park",
                   "playground"
               ]
           ],
           "layout": {
               "icon-image": "playground_11",
               "text-padding": 2,
               "text-font": [
                   "Lato"
               ],
               "text-anchor": "center",
               "text-field":"{name}",
               "text-offset": [
                   0,
                   0.6
               ],
               "text-size": 12,
               "text-max-width": 9
           },
           "paint": {
               "text-halo-blur": 0.5,
               "text-color": "#79906c",
               "text-halo-width": 1,
               "text-halo-color": "#ffffff"
           }
       },

ℹ️ In the layout we specify the "icon-image" to use. This is the reference name that is defined in the sprite.json file.

Sprite sources:

Openmaptiles

"sprite": "https://openmaptiles.github.io/klokantech-basic-gl-style/sprite"

Maptiler

"sprite": "https://maps.tilehosting.com/styles/basic/sprite"

Fill-Extrusion

Do you want this cool 3D effect? This is called fill-extrusion.

A fill-extrusion is only possible on polygons!

The type of layer is fill-extrusion:

   {
            "id": "aardbeving_extrusion",
            "type": "fill-extrusion",
            "source": "aardbeving_buffer",
            "maxzoom": 22,
            "minzoom": 11,
            "paint":{
                "fill-extrusion-height": [
                        "interpolate",["linear"],["zoom"],
                        11, ["*", 10, ["get", "DEPTH"]],
                        15, [ "*", 100 , ["get", "DEPTH"]]
                ],
                "fill-extrusion-color":{
                    "type": "categorical",
                    "property": "TYPE",
                    "stops":[
                        ["ind", "#f3ec9c"],
                        ["tec", "#F5CB5B"]
                    ]
                },
                "fill-extrusion-opacity": 0.9
            }
        },

▶️ Try to get one or more layers in fill-extrusion. (extrusion == 2,5D )

Interaction

The best part about developing your own map is we can add our own JavaScript interaction. This gives you a lot of freedom with the interactivity and the possibilities to extent your application with other libraries, like D3.js. Think about graphs, pop-ups, side panels, scroll stories.

Let's start with adding a simple mouse move action!

 //Adding hover effect
     map.on("mousemove", "admin", function(e) {
        panel.innerHTML = e.features[0].properties.name;
        map.setFilter("admin-hover", ["==", "name", e.features[0].properties.name]);
    });

    // Reset the state-fills-hover layer's filter when the mouse leaves the layer.
    map.on("mouseleave", "admin", function() {
        map.setFilter("admin-hover", ["==", "name", ""]);
    });

▶️ Add this code to your main.js JavaScript file.

We need an extra layer in the style.json. We make the layer with an empty filter. So it does not show up on the map on initialization. With the mousemove event we can change the filter so the layer is rendered.

 {
    "id": "admin-hover",
    "type": "fill",
    "source": "pdok",
    "source-layer": "admin",
    "maxzoom": 22,
    "minzoom": 0,
    "filter": ["==", "name", ""],
    "paint": {
        "fill-color" :"#3fa39a"
    }
},

▶️ Add this to the style.json

When you refresh your browser the Admin layer will change color on your mouse movement!

Get feature information in pop-up

We can also see attribute information about a feature on a mouse click.

▶️ Add the following code to your JavaScript and change the layer-name to the layer you want to query.

    // Get polygon infromation
    map.on('click', 'layer-name', function (e) {
    console.log(e.features[0]);
    new mapboxgl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(e.features[0].properties)
        .addTo(map);

    });

▶️ Refresh your browser. Does the pop-up show up when you click on a feature?

ℹ️ The console.log statement logs the first feature of the clicked object e. ▶️ Check your console logs for any errors or information about the feature. See if you can change the pop-up properties so it shows the information you want to see about object e.

On the Mapbox Example page there are more JavaScript interaction examples to find! Check out these:

Some styling tips.

  • The order of the layers in your style.json is the order of drawing. So first defined layer, "background", is drawn first, the next layer is drawn on top, etc.
  • The labels placing priority is also dependend on the layer order. Layers at the top have less drawing priority, layers at the bottom of the file have more drawing priority!
  • Is your map slow? Check out 🔗 Improve the performance of your MapboxGL map
  • Using a lot a fill-extrusions will also make your map slow.

Other Tile sources

PDOK

BGT en BRT data.

https://github.com/PDOK/vectortiles-bgt-brt

https://forum.pdok.nl/t/vector-tiles-brt-en-bgt-via-pdok/1103/12

http://geodata.nationaalgeoregister.nl/beta/topotiles/{z}/{x}/{y}.pbf

Amsterdam

https://api.data.amsterdam.nl/api/

https://github.com/maptime-ams/vector-tiles-workshop/blob/master/Workshop_Materials/Amsterdam/main.js

https://github.com/maptime-ams/vector-tiles-workshop/wiki

https://t1.data.amsterdam.nl/wm/{z}/{x}/{y}.pbf 

ESRI

http://blogs.esri.nl/de-topografische-basiskaart-een-vertrouwd-beeld-met-nieuwe-technologie/

https://tiles.arcgis.com/tiles/nSZVuSZjHpEZZbRo/arcgis/rest/services/Topo_RD/VectorTileServer/tile/1/0/0.pbf

https://www.arcgis.com/home/item.html?id=c8cb478cd4da4206a56e2a2fba545ccf

Openmaptiles

https://openmaptiles.com/downloads/europe/netherlands/

Maptiler

Maptiler

    https://maps.tilehosting.com/data/v3.json?key=personalkey
    https://maps.tilehosting.com/data/v3/{z}/{x}/{y}.pbf?key=personalkey"

Want to make your own tiles? Check out the advanced part.

Clone this wiki locally