MapLibre GL JS
Accessing OS NGD API – Tiles via MapLibre GL JS
MapLibre GL JS is a free and powerful JavaScript library for displaying interactive maps on the web. It's based on Mapbox GL JS and provides a wide range of features for creating maps with custom styles, markers and interactivity.
What you'll need
OS NGD API – Tiles added to an API project in the OS Data Hub with an API Key.
A text editor like Visual Studio Code or Notepad to edit and save your HTML and JavaScript files.
Create a basic vector map
Step 1: Set up your HTML file
Create a new HTML file with a text editor (for example, Notepad, Visual Studio Code).
Add the basic HTML structure to your file with a placeholder
<div>
for the map.
Step 2: Insert your API Key
To enable access to OS APIs an API Key is required. Inside the
<script>
tag, add a variable calledapiKey
, replacing'INSERT_API_KEY_HERE'
with the API Key from your project.Inside the
<script>
tag, add another variable calledcollectionId
with the collection ID for the OS NGD API – Tiles basemap –ngd-base
.
Step 3: Adding a fetch and response interceptor
We need to intercept and customise the style request, adding a
tiles
property to provide a correctly formatted URL and ensuring authentication through theapiKey
is enabled to make sure that the correct tiles are requested.Add the following code inside the JavaScript block:
Step 4: Create a map and map view
Initialise the map object using the
maplibregl.Map
class to configure the vector tile layer and define its properties –container
,minZoom
,maxZoom
,maxBounds
,style
,center
andzoom
.Add navigation controls to the map, excluding the compass button and disabling map rotation.
The above code creates the main map instance using the MapLibre GL JS library where you can specify various properties:
container
: Defines where the map should be displayed. In this instance, it is set to theID
of the<div>
element.minZoom
andmaxZoom
: Sets the minimum and maximum zoom level for the map. Users will not be able to go beyond these levels.maxBounds
: Defines the maximum bounds and restricts panning the map.style
: Defines the style of the map, configured via a URL pointing at the default style for the 'collectionId
' defined.center
: Sets the initial centre point of the map.zoom
: Sets the initial zoom level of the map.
What's next?
Congratulations! You've successfully created a vector map using MapLibre GL JS using OS NGD API – Tiles in a few steps.
Now you can continue to explore Ordnance Survey's code examples to learn more about advanced features and functionality, such as adding markers, pop-ups, and additional layers.
Last updated