How to add boundaries to Google Maps

23rd November 2021

If you want to add a boundary to Google Maps using the JavaScript API there are several ways to do it but fundamentally you just need a collection of lattitude and longitude coordinates. The method we are going to cover in this article is by adding an external data source in GeoJSON format.

Prerequisites

To use any of Google's API's you'll need to have an API key. You can do this from the Google Cloud Platform and enabling the Maps JavaScript API, once that service is enabled you can head over to the Credentials section and generate a key.

Unfortunately Google no longer gives you any free map loads so before you can use the JavaScript API in production you'll need to enable billing on your account.

Initializing 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 Google, 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.

Great, now that's working we can add our GeoJSON. With the Google Maps JavaScript API, every map has a data object which is a data layer for arbitrary geospatial data. We can call the loadGeoJSON method on that object to load a GeoJSON file which will then add the coordinates in that file onto the map.

In the example below we have loaded a GeoJSON file containing the boundary for Leeds UK and then used a bit of styling to improve it's appearance.

Although this is a basic example, that's pretty much all there is to it. The find out about more advanced styling and to hook into events check out Google's documentation page on the Data Layer.

Obtaining GeoJSON data

If you want to play around further with boundaries, you can purchase the Ultimate UK Map Boundary dataset which contains 11,737 boundaries for £49.99. The download contains seperate GeoJSON files for each city / town / parish boundary so you can easily integrate it into your application.

It's also a life time license which allow you to use the dataset on any number of personal and commercial projects.