MapLibre GL JS
Accessing OS NGD API – Tiles via MapLibre GL JS
What you'll need
1
Set up your HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OS NGD API – Tiles | Template (EPSG:3857) | MapLibre GL JS</title>
<!--Add the Ordnance Survey Styling-->
<link rel="stylesheet" href="https://labs.os.uk/public/os-api-branding/v0.3.1/os-api-branding.css" />
<script src="https://labs.os.uk/public/os-api-branding/v0.3.1/os-api-branding.js"></script>
<!--Add the MapLibre GL JS libaries -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/maplibre-gl.css" />
<script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
<style>
/* Set the map container size and style */
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<!--Create a div element to hold the map-->
<div id="map"></div>
<!--Add your Javascript code below-->
<script>
// Your Javascript code will go here
</script>
</body>
</html>2
3
Adding a fetch and response interceptor
// Modify the JSON style request incorporate a `tiles` property which lists an array of tile endpoints.
// The '&key=' HTTP query parameter is also appended to each tile endpoint to authenticate the request.
// NOTE: The {z}, {x} and {y} template values are replaced with the corresponding integers at runtime.
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [ resource, config ] = args;
let response = await originalFetch(resource, config);
if( response.url != `https://api.os.uk/maps/vector/ngd/ota/v1/collections/${collectionId}/styles/3857` )
return response;
// Response interceptor.
const json = () =>
response.clone().json().then((data) => {
data.sources[ collectionId ].tiles = [ `${data.sources[ collectionId ].url}/{z}/{y}/{x}?key=${apiKey}` ];
delete data.sources[ collectionId ].url;
return data;
});
response.json = json;
return response;
};4
Create a map and map view
// Initialize the map object.
const map = new maplibregl.Map({
container: 'map',
minZoom: 6,
maxZoom: 19,
maxBounds: [ [ -8.74, 49.84 ], [ 1.96, 60.9 ] ],
style: `https://api.os.uk/maps/vector/ngd/ota/v1/collections/${collectionId}/styles/3857`,
center: [ -3.541809, 50.727589 ],
zoom: 17,
attributionControl: false
});
map.dragRotate.disable(); // Disable map rotation using right click + drag.
map.touchZoomRotate.disableRotation(); // Disable map rotation using touch rotation gesture.
// Add navigation control (excluding compass button) to the map.
map.addControl(new maplibregl.NavigationControl({
showCompass: false
}));What's next?
Last updated
Was this helpful?