LogoLogo
OS Docs HomeOS NGDOS APIs OS Download ProductsMore than MapsOS Data Hub
  • OS NGD Documentation
  • GETTING STARTED
    • OS NGD Key Benefits to Customers
    • OS NGD Core Principles
      • Terminology and access
      • File formats and naming
      • Data ordering and currency
      • COU supplies
      • Data schema versioning
      • Unique identifiers
      • Coordinate reference systems
      • Attribute information for feature types
    • OS NGD Sample Data Information
    • OS NGD Webinars, Tutorials and Case Studies
  • ACCESSING OS NGD
    • Downloading with OS Select+Build
      • Getting Started with GeoPackage
        • ArcGIS Pro
        • ArcMap
        • Cadcorp SIS
        • MapInfo Professional
        • QGIS
        • FME
        • GDAL
      • Getting Started with CSV
        • Loading CSV files
        • Processing COUs
      • Getting Started with Attribute Filtering
      • Getting Started with Temporal Filtering
    • Accessing OS NGD APIs
      • Getting started with an API project
      • OS NGD API – Features
        • What data is available?
        • Technical Specification
          • Landing page
          • Conformance
          • Collections
          • Collection
          • Schema
          • Queryables
          • Features
          • Feature
        • Getting Started
          • GIS Software
            • Cadcorp SIS
            • ESRI ArcGIS Online
            • ESRI ArcGIS Pro
            • QGIS
          • Libraries
            • Leaflet
            • MapLibre GL JS
            • OpenLayers
            • Python (Geopandas)
        • Code Examples
      • OS NGD API – Tiles
        • What data is available?
        • Technical Specification
          • Landing page
          • Conformance
          • Collections
          • Collection
          • Tile Matrix Sets
          • Tiles
          • Styles
        • Getting Started
          • GIS Software
            • Cadcorp SIS
            • QGIS
          • Libraries
            • Leaflet
            • MapLibre GL JS
            • OpenLayers
        • Code Examples
    • Additional Resources
      • Tutorials
      • Stylesheets
  • OS NGD NEWS
    • OS NGD News
    • What's New?
    • Change Log
    • OS NGD Improvements
    • Future OS NGD Data Enhancements
  • Data and Service Status
    • Data and Service Status Information
  • 🆕Live Service Disruption and Planned Maintenance
  • Current Known Data Issues
  • 🆕Resolved Data Issues
  • USING OS NGD DATA
    • OS NGD Buildings
      • Building Feature Type
      • How Building data is created
      • Building attribution
      • Known limitations
      • Summary
    • OS NGD Structures
      • Field Boundary
        • Field Boundary Feature Type
        • How Field Boundary data is created
        • Field Boundary attribution
        • Known limitations
        • Summary
    • OS NGD Transport
      • Pavements
        • Pavement polygons
        • Pavement attribution
        • Pavement Link feature type
      • Trams
        • Tram attribution on Road Link
        • Tram On Road Feature Type
        • Trams in the Rail Network
      • Street Light
        • Known limitations
    • OS NGD Land Cover Enhancements
      • Introduction
      • Habitat mapping
      • Percentage coverage
      • Cross reference table
      • Known limitations
      • Summary
    • Data Catalogue
    • FAQs
    • OS NGD Product Viewer Tool
  • DATA STRUCTURE
    • OS NGD Address
      • GB Address
        • Built Address
        • Historic Address
        • Non-Addressable Object
        • Pre-Build Address
        • Street Address
      • Islands Address
        • Built Address
        • Historic Address
        • Non-Addressable Object
        • Pre-Build Address
        • Street Address
      • Related Components
        • Alternate Address
        • Postal Address
        • Other Classification
        • Related Entity
      • Versioning information
      • GB Address Local Custodian Codes
      • Islands Address Local Custodian Codes
    • OS NGD Administrative and Statistical Units
      • Boundaries
        • Boundary High Water Mark
        • Ceremonial County
        • Country
        • Devolved Parliament Constituency
        • Devolved Parliament Electoral Region
        • Electoral Division
        • GLA Assembly Constituency
        • Historic County
        • Historic European Region
        • Lower Tier Local Authority
        • Parish Or Community
        • Polling District
        • Region
        • Regional Authority
        • Upper Tier Local Authority
        • Ward
        • Westminster Constituency
    • OS NGD Buildings
      • Building Features
        • Building
        • 🆕Building Access Location
        • Building Line
        • Building Part
    • OS NGD Geographical Names
      • Named Features
        • 🆕Crowd Sourced Name Point
        • Named Area
        • Named Point
        • Named Road Junction
    • OS NGD Land
      • Land Features
        • Land
        • Land Point
        • Landform
        • Landform Line
        • Landform Point
    • OS NGD Land Use
      • Land Use Features
        • Site
        • Site Access Location
        • ❌Site Routing Point
    • OS NGD Structures
      • Structure Features
        • Compound Structure
        • Field Boundary
        • Structure
        • Structure Line
        • Structure Point
    • OS NGD Transport
      • Routing and Asset Management Information (RAMI)
        • Average And Indicative Speed
        • Highway Dedication
        • Maintenance Area
        • Maintenance Line
        • Maintenance Point
        • Reinstatement Area
        • Reinstatement Line
        • Reinstatement Point
        • Restriction
        • Routing Hazard
        • Routing Structure
        • Special Designation Area
        • Special Designation Line
        • Special Designation Point
      • Transport Features
        • Cartographic Rail Detail
        • Rail
        • Road Line
        • Road Track Or Path
        • 🆕Street Light
      • Transport Network
        • Connecting Link
        • Connecting Node
        • Ferry Link
        • Ferry Node
        • Ferry Terminal
        • Path
        • Path Link
        • Path Node
        • Pavement Link
        • Railway Link
        • Railway Link Set
        • Railway Node
        • Road
        • Road Junction
        • Road Link
        • Road Node
        • Street
        • Tram On Road
    • OS NGD Water
      • Water Features
        • Inter Tidal Line
        • River Basin District Catchment
        • Tidal Boundary
        • Water
        • Water Point
        • Waterbody Catchment
      • Water Network
        • Water Link
        • Water Link Set
        • Water Node
  • Code Lists
    • Code Lists Overview
      • accesstypevalue
      • 🆕accesslevelvalue
      • 🆕accessmodevalue
      • 🆕accessobstructionvalue
      • 🆕accesspurposevalue
      • addressbasepostalvalue
      • addressclassificationsourcevalue
      • addressdescriptionvalue
      • addressstatusvalue
      • addressstreettypevalue
      • associatedstreetdatadescriptionvalue
      • averageandindicativespeeddescriptionvalue
      • basementpresencesourcevalue
      • boundaryhighwatermarkdescriptionvalue
      • boundarytypevalue
      • 🆕buildingaccesslocationdescriptionvalue
      • buildingageperiodvalue
      • buildingagesourcevalue
      • buildingconnectivitytypevalue
      • buildingdescriptionvalue
      • buildinglinedescriptionvalue
      • buildingpartdescriptionvalue
      • buildingpartoslandcovertieravalue
      • buildingpartoslandcovertierbvalue
      • buildingusevalue
      • buildstatusvalue
      • builtstructureheightconfidencevalue
      • capturemethodvalue
      • capturespecificationvalue
      • ceremonialcountydescriptionvalue
      • changetypevalue
      • classificationcorrelationvalue
      • compoundstructuredescriptionvalue
      • connectinglinkdescriptionvalue
      • connectingnodedescriptionvalue
      • constructionmaterialsourcevalue
      • constructionmaterialvalue
      • countryvalue
      • countrydescriptionvalue
      • 🆕crowdsourcednamedescriptionvalue
      • 🆕crowdsourcednamematchtypevalue
      • cyclefacilityvalue
      • dataentitycatalogue
      • dedicationvalue
      • devolvedparliamentconstituencydescriptionvalue
      • devolvedparliamentelectoralregiondescriptionvalue
      • electoraldivisiondescriptionvalue
      • extentoflinkvalue
      • ferrylinkdescriptionvalue
      • ferrynodedescriptionvalue
      • ferryterminaldescriptionvalue
      • fieldboundarydescriptionvalue
      • formofroadnodevalue
      • formofwaytypevalue
      • gaugevalue
      • glaassemblyconstituencydescriptionvalue
      • gssrolevalue
      • hazardtypevalue
      • heightingmethodvalue
      • highwaydedicationnetworkfeaturetypevalue
      • historiccountydescriptionvalue
      • historiceuropeanregiondescriptionvalue
      • intertidallinedescriptionvalue
      • 🆕illuminationvalue
      • junctiontypedescriptionvalue
      • landdescriptionvalue
      • landformdescriptionvalue
      • landformlinedescriptionvalue
      • landformpointdescriptionvalue
      • landoslandcovertieravalue
      • landoslandcovertierbvalue
      • landformvalue
      • landpointdescriptionvalue
      • languagevalue
      • linkdirectionvalue
      • 🆕linkreferenceconfidencevalue
      • lowertierlocalauthoritydescriptionvalue
      • maintenancevalue
      • 🆕matchedfeaturetypengdvalue
      • 🆕matchedthemengdvalue
      • matchstatusvalue
      • classificationcorrelationvalue
      • namedareaextentdefinitionvalue
      • nameddatevalue
      • nameddayvalue
      • namedescriptiongroupvalue
      • namedescriptionvalue
      • namedperiodvalue
      • namedroadjunctiondescriptionvalue
      • namedtimevalue
      • networkfeaturetypevalue
      • 🆕networknodefeaturetypevalue
      • networkoverunderbridgevalue
      • operationalstatevalue
      • operationalstatusvalue
      • oslandusetieravalue
      • oslandusetierbvalue
      • parentboundarydescriptionvalue
      • parentfeaturetypevalue
      • parishorcommunitydescriptionvalue
      • pathdescriptionvalue
      • pathnodedescriptionvalue
      • physicallevelvalue
      • 🆕physicalstatevalue
      • physicallevelvalue
      • pollingdistrictdescriptionvalue
      • positionalaccuracyvalue
      • postcodetypevalue
      • presencevalue
      • raildescriptionvalue
      • raildetaildescriptionvalue
      • railoslandcovertieravalue
      • railoslandcovertierbvalue
      • railwaylinkdescriptionvalue
      • railwaylinksetdescriptionvalue
      • railwaynodedescriptionvalue
      • railwayusevalue
      • regionalauthoritydescriptionvalue
      • regiondescriptionvalue
      • reinstatementtypevalue
      • relationshiptypevalue
      • restrictiontypedescriptionvalue
      • restrictionvalue
      • riverbasindistrictcatchmentdescriptionvalue
      • roadclassificationvalue
      • roaddescriptionvalue
      • roadfunctionvalue
      • roadlinedescriptionvalue
      • roadnodedescriptionvalue
      • roadstructurevalue
      • roadtrackorpathdescriptionvalue
      • roadtrackorpathoslandcovertieravalue
      • roadtrackorpathoslandcovertierbvalue
      • roadwidthconfidencelevelvalue
      • 🆕roofconfidenceindicatorvalue
      • 🆕roofmaterialvalue
      • 🆕roofshapevalue
      • pavementdescriptionvalue
      • sideofroadvalue
      • siteaccesslocationdescriptionvalue
      • sitedescriptionvalue
      • siteextentdefinitionvalue
      • siteroutingpointdescriptionvalue
      • sourceofmeasurevalue
      • specialdesignationtypevalue
      • stakeholdervalue
      • statusvalue
      • streetclassificationvalue
      • streetdescriptionvalue
      • streetgeometrysourcevalue
      • 🆕streetlightdescriptionvalue
      • streetstatevalue
      • streetsurfacevalue
      • streettypevalue
      • structuredescriptionvalue
      • structureoslandcovertieravalue
      • structureoslandcovertierbvalue
      • structurelinedescriptionvalue
      • structurepointdescriptionvalue
      • structuretypevalue
      • structurevalue
      • surfacetypevalue
      • themevalue
      • tidalboundarydescriptionvalue
      • trackrepresentationvalue
      • tramdescriptionvalue
      • 🆕transportfeaturetypevalue
      • uppertierlocalauthoritydescriptionvalue
      • usrnmatchindicatorvalue
      • vehiclequalifiervalue
      • warddescriptionvalue
      • waterbodycatchmentdescriptionvalue
      • waterbodycategoryvalue
      • waterdescriptionvalue
      • wateroslandcovertieravalue
      • wateroslandcovertierbvalue
      • waterlinkdescriptionvalue
      • waterlinkflowdirectionvalue
      • waterlinkgeometrysourcevalue
      • waterlinklevelofdetailvalue
      • waterlinkpermanencevalue
      • waterlinkphysicalcontainmentvalue
      • waterlinkprimacyvalue
      • waterlinksetdescriptionvalue
      • waterlinkwatertypevalue
      • watermarkvalue
      • waternodedescriptionvalue
      • waterpointdescriptionvalue
      • watertypevalue
      • westminsterconstituencydescriptionvalue
      • yesnovalue
  • EXTRA LINKS
    • Accessibility
    • Contact Us
    • Copyright
    • PSGA Product Summary
Powered by GitBook
On this page
  • What you'll need
  • What's next?

Was this helpful?

Export as PDF
  1. ACCESSING OS NGD
  2. Accessing OS NGD APIs
  3. OS NGD API – Tiles
  4. Getting Started
  5. Libraries

OpenLayers

Accessing OS NGD API – Tiles via OpenLayers

PreviousMapLibre GL JSNextAdditional Resources

Last updated 4 months ago

Was this helpful?

is a free and open-source JavaScript library for displaying interactive maps on the web. It is a powerful tool that can be used to create a wide variety of map-based applications, from simple web maps to complex GIS applications.

OpenLayers is easy to use and can be integrated with a variety of other web development frameworks.

What you'll need

  • 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.

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.

<!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/ol@v7.3.0/ol.css" />
    <script src="https://cdn.jsdelivr.net/npm/ol@v7.3.0/dist/ol.js"></script>
    <script src="https://unpkg.com/ol-mapbox-style@9.7.0/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

Insert your API Key

  • 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.

// Set API Key and collection ID
 const apiKey = 'INSERT_API_KEY_HERE';
 
 const collectionId = 'ngd-base';
3

Tile grid set up

  • To correctly render the vector tiles within OpenLayers, you will need to fetch the defined EPSG:3857 Tile Matrix Set and style definitions from the OS NGD API – Tiles service. The two endpoints provide information about the structure of the vector tiles and how the styles are to be applied.

  • A promise.all is used to process the data to ensure that both requests are completed before proceeding.

  • Based on the fetched Tile Matrix Set data, a tile grid is defined using the ol.tilegrid.TileGrid class. The tile grid provides information about the resolution, origin and tile sizes to handle the vector tiles correctly.

  • Add the following code inside the JavaScript block:

// 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 a new vector tiles layer and source that will be used to fetch vector tiles from OS NGD API – Tiles. The ol.layer.VectorTile uses a ol.source.OGCVectorTile source to retrieve tiles from the API.

  • After creating the vector layer, you will need to use a style function to ensure that the Ordnance Survey styles are applied to each tile. Use the olms.applyStyle function to retrieve the style sheets available for the basemap.

// 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 using the ol.map class to configure the vector tile layer and define its properties – target, layers and 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
        })
    });
});

The above code creates the main map instance using the OpenLayers library where you can specify various properties:

  • target: Defines where the map should be displayed. In this instance it is set to the ID of the <div> element.

  • layers: An array containing the layers to be added to the map.

  • view: Defines the initial view of the main, containing various settings such as projection, extent (the geographic bounds of the map), minimum and maximum zoom levels, centre of the map and the initial zoom level.

What's next?

Congratulations! You've successfully created a vector map using OpenLayers using OS NGD API – Tiles in a few steps.

Now you can continue to explore Ordnance Survey's to learn more about advanced features and functionality, such as adding markers, pop-ups, and additional layers.

OpenLayers
code examples
Getting started with an API project