How to add boundaries to Mapbox

17th November 2021

If you are using Mapbox to visualise the locations of a set of results, it can also be useful to highlight the city / town / village boundary these results fall in. In this article we're going to walk through how to add a basic map to your web page and then how to add a town boundary onto that map.

Prerequisites

Before we start you'll need to make sure you've registered for a Mapbox account and created an API token which you can do from the Access Tokens page. You may already have a token called "Default public token" which is perfect for development as it has no domain restrictions but in product you'll want to create a new token and limit it to the domain name you code will be sitting on.

Displaying a map

Now that we have our access token lets create a simple HTML webpage. This page will load the external JS and CSS files we need from Mapbox, define the element we'll be binding our map too and add a few lines of JavaScript to initalise the map.

Don't forget you'll need to replace the access token in the example with your own.

If all is well and good you should see a map appearing on your page, centered over Leeds, UK like the one below. If you're not seeing this be sure to check your console for any errors.

Adding a boundary

We have our basic map working so the next step is to add the boundary, in this example I'll be adding the boundary for Leeds, UK as that's where the map is centered on. To achieve this we need to define a new source and then add a new layer onto the map that uses that source.

The above code combined with the code from the previous step will give us our map with the boundary on it.

To obtain GeoJSON data for UK cities, towns and parishes you can use Mapbox Boundaries a service that provides this data, however it is not available for anyone to use and you will have to apply via their sales team.

Alternatively you can purchase our dataset which is a one time payment of £49.99 for a lifetime license. The data consists of 11,737 boundaries and you can use it on an unlimited number of personal and commercial products.