OpenLayers
Accessing OS NGD API – Tiles via OpenLayers
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) | OpenLayers</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 OpenLayers libraries-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/ol.css" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ol.js"></script>
<script src="https://unpkg.com/[email protected]/dist/olms.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
Tile grid set up
// Define the Tile Grid and style
const tmsPromise = fetch('https://api.os.uk/maps/vector/ngd/ota/v1/tilematrixsets/3857').then((response) => response .json());
const glStylePromise = fetch(`https://api.os.uk/maps/vector/ngd/ota/v1/collections/${collectionId}/styles/3857`).then((response) => response .json());
Promise.all([tmsPromise, glStylePromise]).then((values) => {
const tms = values[0];
const glStyle = values[1];
const tilegrid = new ol.tilegrid.TileGrid({
resolutions: tms.tileMatrices.map(({ cellSize }) => cellSize),
origin: tms.tileMatrices[0].pointOfOrigin,
tileSize: [ tms.tileMatrices[0].tileHeight, tms.tileMatrices[0].tileWidth ]
});4
Define a vector tile layer
// Define the vector tile layer.
const formatMvt = new ol.format.MVT();
formatMvt.supportedMediaTypes.push('application/octet-stream');
const vectorTileLayer = new ol.layer.VectorTile({
source: new ol.source.OGCVectorTile({
url: `https://api.os.uk/maps/vector/ngd/ota/v1/collections/${collectionId}/tiles/3857?key=${apiKey}`,
format: formatMvt,
projection: 'EPSG:3857',
tileGrid: tilegrid
}),
declutter: true
});
// Apply a style function to the vector tile layer.
olms.applyStyle(
vectorTileLayer,
glStyle,
collectionId,
{ styleUrl: null } ,
tilegrid.getResolutions()
);5
Create a map and map view
// Initialize the map object.
const map = new ol.Map({
layers: [ vectorTileLayer ],
target: 'map',
view: new ol.View({
projection: 'EPSG:3857',
extent: ol.proj.transformExtent([ -10.76418, 49.528423, 1.9134116, 61.331151 ], 'EPSG:4326', 'EPSG:3857'),
resolutions: tilegrid.getResolutions(),
minZoom: 6,
maxZoom: 19,
center: ol.proj.fromLonLat([ -3.541809, 50.727589 ]),
zoom: 17
})
});
});What's next?
Last updated
Was this helpful?