Leaflet
Accessing OS NGD API – Features via Leaflet
Last updated
Accessing OS NGD API – Features 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 Maps API and OS NGD API – Features 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.
Add a variable called collectionID
, replacing 'INSERT_COLLECTIONID_HERE'
with the collection ID for the desired OS NGD feature type and version (for example, bld-fts-buildingpart-1).
Define the configuration options for the map, defining minZoom
, maxZoom
, center
, zoom
, maxBounds
, attributionControl
.
minZoom
and maxZoom
: Sets the minimum and maximum zoom level for the map. Users will not be able to go beyond these levels.
center
: Sets the initial centre point of the map.
zoom
: Sets the initial zoom level of the map.
maxBounds
: Defines the maximum bounds and restricts panning the map.
style
: Defines the style of the map, configured via a URL pointing at the style specified.
attributionControl
: When set to 'false', it hides the attribution control which displays map credits.
Initialize the map with the id
of the <div>
element and the configuration option defined in mapOptions
.
Using the 'L.tileLayer
' method, specify the basemap layer for OS Maps API, which includes your API Key to load the tiles to your map.
Create a function called fetchFeatures
that fetches the API based on the current map extent (bounding box) by generating a bbox string.
Construct the API request URL to fetch OS NGD data from OS NGD API – Features. The URL includes the collectionId
, bbox
and apiKey
.
Once the features have been returned in JSON, update the source data of the map's layers to display the features.
The map.on('moveend',...)
event handler fetches and updates the features based on the map's current extent.
Features within the viewport extent will load initially (first 100 features) and will continue to load as you pan and zoom across the map.
Congratulations! You've successfully created a map using Leaflet and added an OS NGD layer using OS NGD API – Features 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.