OpenLayers

Accessing OS NGD API – Features via OpenLayers

OpenLayers 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 Maps API and OS NGD API – Features added to an API project in the OS Data Hub with an API Key.

  • A text editor like Visual Studio Code or Notepad to edit and save your HTML and JavaScript files.

Create a basic map

Step 1: Set up your HTML file

  1. Create a new HTML file with a text editor (for example, Notepad, Visual Studio Code).

  2. 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 – Features | Template (EPSG:3857) | OpenLayers</title>
    
    <!--Add the Ordnance Survey Styling-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/OrdnanceSurvey/os-api-branding@0.3.1/os-api-branding.css" />
    <script src="https://cdn.jsdelivr.net/gh/OrdnanceSurvey/os-api-branding@0.3.1/os-api-branding.js"></script>
    
    <!--Add the OpenLayers libraries-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v8.1.0/ol.css" />
    <script src="https://cdn.jsdelivr.net/npm/ol@v8.1.0/dist/ol.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>

Step 2: Insert your API Key and OS NGD collection

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

  2. 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).

// Set API Key 
 const apiKey = 'INSERT_API_KEY_HERE';
 
 const collectionId= 'INSERT_COLLECTIONID_HERE';

Step 3: Add a basemap

  • Create a source for the basemap layer using OS Maps API and initialise the ol.map class with the applicable map properties – target, layers and view. Add the following code inside the JavaScript block:

// Initialize the map object.
    const map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.XYZ({
                    url: `https://api.os.uk/maps/raster/v1/zxy/Light_3857/{z}/{x}/{y}.png?key=${apiKey}`
                })
            })
        ],
        view: new ol.View({
            projection: 'EPSG:3857',
            extent: ol.proj.transformExtent([ -10.76418, 49.528423, 1.9134116, 61.331151 ], 'EPSG:4326', 'EPSG:3857'),
            minZoom: 7,
            maxZoom: 20,
            center: ol.proj.fromLonLat([ -3.541809, 50.727589 ]),
            zoom: 18
        })
    });

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.

Step 4: Add an OS NGD API – Features layer

  1. Define and initialise the source using the ol.source.Vector class to make a request to OS NGD API – Features. By utilising the ol.loadingstrategy.bbox this means that data from OS NGD API – Features will be loaded based on the visible map extent.

  2. To create a separate layer to overlay OS NGD data onto the map, you will need to add the ngdFeatures layers to the ol.map object to render both layers on the map.

// Create the NGD Features API layer (with BBOX strategy).
    const ngdFeatures = new ol.layer.Vector({
        source: new ol.source.Vector({
            format: new ol.format.GeoJSON(),
            url: function(extent) {
                return (
                    `https://api.os.uk/features/ngd/ofa/v1/collections/${collectionId}/items?key=${apiKey}&bbox=${extent.join(',')}&bbox-crs=http://www.opengis.net/def/crs/EPSG/0/3857`
                );
            },
            strategy: ol.loadingstrategy.bbox
        })
    });

    // Add the NGD Features API layer to the map.
    map.addLayer(ngdFeatures);

Features within the viewport extent will load initially (first 100 features) and will continue to load as you pan across the map.

What's next?

Congratulations! You've successfully created a map using OpenLayers 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.

Last updated