Adding GeoJSON to Mapbox-GL: Stitching Together Seamless Styles

Sep 18, 2014 · 2 min read

Mapbox-GL was released a few weeks ago and, with the very recent release of Mapbox Studio, it’s easier than ever to create beautiful maps for the web.

But you may be experiencing growing pains if you’re working with vector tiles for the first time. (I certainly still am!) While the guys at Mapbox are still on an early version of GL that hasn’t stopped them from releasing some great examples to help you get started.

The screenshot below shows one example of bringing a GeoJSON line feature onto a Mapbox-GL map

If you’re like me, though, there’s only one thing you’re noticing: the labels being annoyingly blocked by the lime green GeoJSON line. Wait a second… I thought vector tiles gave you the ability to draw labels on top of GeoJSON?!

The promise of vector tiles has not been broken. The key is the drawing order. According to the docs:

Layers are drawn in the order given.

OK, that’s not so bad. So what order is the example giving the layers in?

style.layers.push({
// GeoJSON style here...
});

If you check out the code, you’ll see that style is JSON containing example style info pulled from Mapbox’s server, here:
https://www.mapbox.com/mapbox-gl-styles/styles/outdoors-v4.json

Because we’re using push, we’re just popping the new GeoJSON style right at the end of the style.layers array. That’s why it’s being drawn on top of the labels.

If we want to have the GeoJSON line show up below the labels, we’ll just use splice instead.

style.layers.splice(77, 0, {
// GeoJSON style here...
});

The crucial question is, where should we insert that new style into the array? Well, 77 is the magic-ish number here (it’s above the majority of the map but below the labels).

Voila!

Check out http://landonreed.github.io/mapbox-gl for a live example

This is a simple case, but I hope it encourages you to dive into the example Mapbox styles and maybe even create your own! There are some amazing things you can do with compositing and layering styles (even regex!) to make oh-so beautiful maps.

Looking for code for the example?

GitHub, Example Map
Original Mapbox example

    Landon Reed

    Written by

    Interested in transit, planning, maps, and the data that support them all.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade