Leaflet
Accessing OS NGD API – Tiles via Leaflet
Last updated
Accessing OS NGD API – Tiles via Leaflet
Last updated
Leaflet is an open-source JavaScript library for displaying interactive maps on the web or mobile. A simple and lightweight library that will enable you to display and visualise location data and build dynamic applications.
OS NGD API – Tiles added to an API project in the OS Data Hub with an API Key. See for more information.
A text editor like Visual Studio Code or Notepad to edit and save your HTML and JavaScript files.
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.
To enable access to OS APIs an API Key is required. Inside the <script>
tag, add a variable called apiKey
, replacing 'INSERT_API_KEY_HERE'
with the API Key from your project.
Inside the <script>
tag, add another variable called collectionId
with the collection ID for the OS NGD API – Tiles basemap – ngd-base
.
We need to intercept and customise the style request, adding a tiles property to provide a correctly formatted URL and ensure authentication through the apiKey
is enabled to make sure that the correct tiles are requested.
Add the following code inside the JavaScript block:
Initialize the map object using the L.Map
class to configure the vector tile layer and the mapOptions
variable to define its properties – minZoom
, maxZoom
, maxBounds
, center
and zoom
.
The above code creates the main map instance using the Leaflet library where you can specify various properties:
minZoom
and maxZoom
: 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.
center
: Sets the initial centre point of the map.
zoom
: Sets the initial zoom level of the map.
Congratulations! You've successfully created a vector map using Leaflet 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.