arrow-left

All pages
gitbookPowered by GitBook
1 of 11

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

GIS software

hashtag
Accessing OS NGD data with OS NGD API – Features via GIS software

The following sub-sections provide step-by-step instructions on how to access OS NGD data via OS NGD API – Features in various GIS software packages:

  • Cadcorp SIS

ESRI ArcGIS Online

Accessing OS NGD data with OS NGD API – Features via ESRI ArcGIS Online

ArcGIS Online is a web-based platform geographic information system (GIS). ArcGIS Online services are managed by Esri and accessed by a client running on a wide range of options.

The instructions that follow demonstrate how to connect to OS NGD API – Features using ESRI ArcGIS Online.

hashtag
What you need

ESRI ArcGIS Online
ESRI ArcGIS Pro
QGIS
Access to the ESRI ArcGIS Online service.
  • A preloaded base map, for example, .

  • OS NGD API – Features added to an API project in the OS Data Hub with an API Key. See for more information.

  • hashtag
    Instructions

    1

    hashtag
    Add a new layer

    Once you've signed into your ESRI ArcGIS Online account and opened the map viewer. Zoom in to a small area to reduce the number of requests that are initially sent to the API.

    • Select Layers > Add > Add layer from URL.

    2

    hashtag
    Add an API and set up custom parameters

    In the Add Layer dialog:

    • URL

    3

    hashtag
    Adding layers to the map

    In the Add Layer dialog:

    • To add a layer to the map

    : Enter the base URL for OS NGD API – Features, excluding the API Key. For example, https://api.os.uk/features/ngd/ofa/v1.
  • Type: Select OGC feature layer.

  • Select Custom request parameters and enter the following:

    • Parameter: key

    • Value: [Insert your OS API Key here]

  • Click Next.

  • : Select a layer to add to the map and then click
    Add to map
    .

    The layer will then display in the Layers panel and the data will display on the map:

    Features will automatically refresh when you zoom or pan on the map. If you wish to add multiple layers to the same map, repeat steps 2 and 3.

    ArcGIS Online Layers dialog.
    ESRI ArcGIS Pro Add OGC API Server Connection dialog with URL and custom request parameters set.
    ArcGIS Online Add Layers dialog: Select a layer to add field.
    ArcGIS Online UI showing OS NGD API – Features data in the map area.
    ArcGIS Online Layers dialog.
    ESRI ArcGIS Pro Add OGC API Server Connection dialog with URL and custom request parameters set.
    ArcGIS Online Add Layers dialog: Select a layer to add field.
    ArcGIS Online UI showing OS NGD API – Features data in the map area.

    Getting started

    The following pages provide an overview of how to get started using OS NGD API – Features. They provide step-by-step instructions to get started in the most common and .

    circle-info

    These pages should be read in conjunction with the more detailed pages within the and the API's .

    GIS software
    web mapping libraries
    Data Structure section
    technical specification

    Cadcorp SIS

    Accessing OS NGD data with OS NGD API – Features via Cadcorp SIS

    The Cadcorp Spatial Information System® (Cadcorp SIS®) is an integrated family of geospatial products comprising desktop, web, and developer applications.

    Cadcorp SIS Desktop connects directly to the OS Data Hub through dedicated wizards.

    hashtag
    What you need

    • Cadcorp SIS (version SIS 9 or later).

    • A preloaded base map, for example, or .

    • OS NGD API – Features added to an API project in the OS Data Hub with an API Key. See for more information.

    hashtag
    Instructions

    circle-info

    These instructions are based on Cadcorp SIS Desktop version 9.1.1668.

    1

    hashtag
    Add overlay

    Once a new map has been set up, in the Home tab, click Add Overlay.

    2

    hashtag
    Select API

    In the Overlay Types dialog:

    • Select Ordnance Survey (GB) > OS (GB) Data Hub, and then click Next.

    In the OS (GB) Data Hub dialog:

    • Select OS National Geographic Database (NGD) API – Features.

    • API Key: Enter your API key.

    • Premium/Public Sector Plan: Select this option if you have this plan.

    • Save in the UI settings database (encrypted): Select this option.

    • Click Next.

    3

    hashtag
    Adding layers to the map

    In the OS Data Hub NGD API – Features Data Themes and Feature Types dialog:

    • Well-known ‘recipe’: Select a predefined recipe, if available.

    • Data Themes: Select your data themes.

    • Features: If necessary, use the editing tools (on the right) to delete feature types or to change the order in which they display in your SIS Workspace Definition (SWD). By default, all feature types within the selected data themes are available in the right panel.

    • Local cache: Select this option to store the data temporarily on your machine. If you save and reopen the SWD, the data will still be available as it is fetched from your local cache.

    • One-off import: Select this option to do a one-off import of the data. If you save and reopen the SWD, the data will not be available and you will need to re-import it. These imports have a larger file size.

    • Filtering: These settings are used in conjunction and define how much data is required for display. It is recommended that you always set a spatial filter and feature limit.

      • Spatial: The Intersect with current view extent option limits the download to only selected features within the current window extent. You can also load features within a specific area of interest using the polygon feature to draw your area of interest on the map BEFORE opening the Add Overlay dialog.

      • Maximum number of features

    • Click Finish.

    The selected layer(s) will then display in the SIS Workspace Definition (SWD) and the data will display in the map area:

    Cadcorp SIS Desktop UI highlighting Add Overlay button.
    Cadcorp SIS Desktop UI highlighting Add Overlay button.
    : Limits the number of feature values downloaded to the number set.
    This limit is applied per feature within any filtered spatial area.
    Cadcorp SIS Desktop OS (GB) Data Hub dialog with the Next button and API Key button highlighted.
    Cadcorp SIS Desktop OS (GB) Data Hub dialog
    Cadcorp SIS Desktop UI showing OS NGD API – Features data in the map area.
    Cadcorp SIS Desktop UI showing OS NGD API – Features data.

    Python (Geopandas)

    Accessing OS NGD API – Features via Python (Geopandas)

    This example will provide an introduction on how to use OS NGD API – Features to extract and plot OS NGD data! We’ll be using GeoPandasarrow-up-right, a library that builds on Pandas to help manage and analyse spatial data.

    hashtag
    What you'll need

    • OS NGD API – Features added to an API project in the OS Data Hub with an API Key. See for more information.

    • The following dependencies installed:

    circle-info

    More examples in an executable notebook format are available through our .

    1

    hashtag
    Import the required libraries

    2

    QGIS

    Accessing OS NGD data with OS NGD API – Features via QGIS

    QGIS is an open GIS (Geospatial Information System) desktop application that allows you to display, interrogate, visualise and create geospatial information including from geo-centric APIs (for example, a WFS).

    The instructions that follow demonstrate how to connect to OS NGD API – Features using QGIS.

    hashtag
    What you need

    • QGIS (version 3.12.0 or later).

    • A preloaded basemap, for example, or .

    • OS NGD API – Features added to an API project in the OS Data Hub with an API Key. See for more information.

    hashtag
    Instructions

    circle-info

    hashtag
    Connecting to OS NGD API – Features

    If you are connecting to the OS NGD API for the first time then you can follow either step 2 or step 3 to set up a new connection via QGIS. It is not necessary to follow both steps.

    1

    hashtag
    Set up a new connection

    Once a new project with a base map has been set up, zoom in to a small area to reduce the number of requests that are initially sent to the API. Select Layer > Add Layer > Add WFS / OGC API - Features Layer.

    2

    Leaflet

    Accessing OS NGD API – Features via 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.

    hashtag
    What you'll need

    Libraries

    hashtag
    Accessing OS NGD data with OS NGD API – Features via web mapping libraries

    The following sub-sections provide step-by-step instructions on how to access OS NGD data via OS NGD API – Features in various web mapping libraries:

  • MapLibre GL JS

  • OpenLayers

  • Python (Geopandas)

  • Leaflet
    Shapelyarrow-up-right
    hashtag
    Set up your OS API credentials
    3

    hashtag
    Request data from OS NGD API – Features

    4

    hashtag
    Load data into a GeoPandas DataFrame

    5

    hashtag
    Plot Data

    GeoPandasarrow-up-right
    Requestsarrow-up-right
    OS APIs Python wrapperarrow-up-right
    An example plot of the wtr-fts-water-2 data covering the Glastonbury Canals.

    hashtag
    Create a new connection in the WFS Connection dialog

    In the Data Source Manager | WFS / OGC API - Features dialog click New and in the New WFS Connection dialog:

    • Name: Provide a name for the connection. You can reuse this connection in the future.

    • URL: Copy the OS NGD API – Features endpoint address from the OS Data Hub and paste it into this field. Your API Key is automatically appended to this URL in the key parameter.

    • Authentication: Leave these settings at their defaults. You do not need a username or password as authentication is done through your API Key.

    • Version: Click Detect to identify the version.

    • Enable feature paging: Select this option, if necessary.

    • Page size: Enter a maximum page size. This limits the page size to a maximum number of features. We recommend a setting of about 100 to speed up response times. Larger values may result in a very slow response time.

    • Other: Leave the other settings at their defaults.

    • Click OK.

    3

    hashtag
    Create a new connection using a saved server configuration

    The Ordnance Survey GitHub repository contains API resources contains configuration files that can be loaded directly into the QGIS Data Source Manager following the Connecting to web services guide in the QGIS documentationarrow-up-right.

    4

    hashtag
    Adding layers to the map

    Data Source Manager | WFS / OGC API - Features dialog:

    • Select your new connection in the dropdown, if necessary.

    • Click Connect.

    When you click Connect, a list of layers available in OS NGD API – Features populates in the main box:

    • To add a layer to the map: Select the layer to highlight it. You can select multiple layers by using the Ctrl key.

    circle-info

    As best practice, only load layers that relate to your current task – not all layers. The more features you call, the longer it takes to load them into QGIS. In addition, each feature, regardless of its layer, counts towards your .

    • Only request features overlapping the view extent: Select this option.

    • Click Add.

    The layer will then display in the Layers panel and the data will display on the map:

    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.

  • 1

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

    2

    hashtag
    Insert your API Key and OS NGD collection

    • To enable access to OS APIs an API Key is required. Inside the <script> tag, add a variable called

    3

    hashtag
    Add a basemap

    • Define the configuration options for the map, defining minZoom, maxZoom

    4

    hashtag
    Add an OS NGD API – Features layer

    • Create a function called fetchFeatures that fetches the API based on the current map extent (bounding box) by generating a bbox string.

    5

    hashtag
    Load and update features on the map dynamically

    The map.on('moveend',...) event handler fetches and updates the features based on the map's current extent.

    circle-exclamation

    hashtag
    What's next?

    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 examplesarrow-up-right to learn more about advanced features and functionality, such as adding markers, pop-ups, and additional layers.

    Leaflet arrow-up-right
    # Define your bounding box
    bbox = [-314177.76517933805,6641680.87433119,-304909.7754997604,6653318.411887609] # Example: Glastonbury Canal
    
    # Initialize an empty list to collect all features
    all_features = []
    
    # Loop through 20 pages
    for page in range(20):
     offset = page * 100  # Calculate the offset based on the page number
     params = {
            "key": api_key,
            "bbox": ",".join(map(str, bbox)),
            "limit": 100,
            "offset": offset,
            "bbox-crs": "http://www.opengis.net/def/crs/EPSG/0/3857",
            "crs": "http://www.opengis.net/def/crs/EPSG/0/3857",
     }
     
     # Send a request to the OS NGD API - Features
     response = requests.get(f"{base_url}/collections/{collection}/items", params=params)
     
     # Check if the request was successful
     if response.status_code == 200:
       data = response.json()
       features = data.get("features", [])
       all_features.extend(features)
       if len(features) < params["limit"]:  # Stop as there are no more features to retrieve 
         break
     else:
       print(f"Error: {response.status_code}")
       break  # Stop the loop in case of an error
    # Extract the geometries and attributes for each feature
    geometry = [shape(feature["geometry"]) for feature in all_features]
    attributes = [feature["properties"] for feature in all_features]
    
    # Create a GeoDataFrame from the geometries and attributes
    gdf = gpd.GeoDataFrame(attributes, geometry=geometry)
    
    # Set the CRS of the GeoDataFrame to EPSG:3857 (Web Mercator)
    gdf.set_crs("EPSG:3857", inplace=True)
    # Plot the features
    gdf.plot(figsize=(12,8),facecolor="#2d8fb6", edgecolor="#b19d3e", lw=0.05)
    import requests
    import geopandas as gpd
    from shapely.geometry import shape
    # OS NGD API - Features API Key
    api_key = "INSERT_API_KEY"
    
    # OS NGD API - Features base URL
    base_url = "https://api.os.uk/features/ngd/ofa/v1"
    
    # OS NGD API - Features CollectionId
    collection= "wtr-fts-water-2"
    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).

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

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

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

    rate limitsarrow-up-right
    QGIS Create a New WFS Connection dialog.
    QGIS Data Source Manager | WFS > Server Connections.
    QGIS Data Source Manager | WFS > Server Connections.
    QGIS Data Source Manager | WFS / OGC API - Features.
    QGIS Data Source Manager | WFS / OGC API - Features.
    QGIS UI showing OS NGD API - Features data in the Layers panel and map area.
    QGIS UI showing OS NGD API – Features data in the Layers panel and map area.
    <!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) | Leaflet</title>
        
        <!--Add the Ordnance Survey Styling-->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/OrdnanceSurvey/[email protected]/os-api-branding.css" />
        <script src="https://cdn.jsdelivr.net/gh/OrdnanceSurvey/[email protected]/os-api-branding.js"></script>
        
        <!--Add the Leaflet libraries-->
        <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
        <script src="https://unpkg.com/[email protected]/dist/leaflet.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>
    // Add event which will be triggered when the map has finshed moving (pan + zoom).
    // Implements a simple strategy to only request data when the map viewport invalidates
    // certain bounds.
        map.on('moveend', function() {
            let bounds1 = new L.latLngBounds(bounds.getSouthWest(), bounds.getNorthEast()),
                bounds2 = map.getBounds();
    
            if( JSON.stringify(bounds) !== JSON.stringify(bounds1.extend(bounds2)) ) {
                bounds = bounds2;
                fetchFeatures(bounds);
            }
        });
    // Set API Key 
     const apiKey = 'INSERT_API_KEY_HERE';
     
     const collectionId= 'INSERT_COLLECTIONID_HERE';
    // Initialize the map.
        const mapOptions = {
            minZoom: 7,
            maxZoom: 20,
            center: [ 50.727589, -3.541809 ],
            zoom: 18,
            maxBounds: [
                [ 49.528423, -10.76418 ],
                [ 61.331151, 1.9134116 ]
            ],
            attributionControl: false
        };
    
        const map = L.map('map', mapOptions);
    
        // Load and display ZXY tile layer on the map.
        const basemap = L.tileLayer(`https://api.os.uk/maps/raster/v1/zxy/Light_3857/{z}/{x}/{y}.png?key=${apiKey}`, {
            maxZoom: 20
        }).addTo(map);
    // Add layer group to make it easier to add or remove layers from the map.
        const lyrGroup = new L.layerGroup().addTo(map);
    
    // Define an asynchronous function to fetch and display the NGD Features API features.
        async function fetchFeatures(bounds) {
            // Generate a BBOX string for the map extent.
            const bbox = bounds.toBBoxString();
    
            // Construct the NGD Features API request URL.
            const url = `https://api.os.uk/features/ngd/ofa/v1/collections/${collectionId}/items?key=${apiKey}&bbox=${bbox}`;
    
            // Fetch features from the API endpoint.
            const features = await fetch(url).then(response => response.json());
    
            // Parse the GeoJSON data and display it on the map.
            lyrGroup.clearLayers().addLayer(L.geoJSON(features));
        }
    
    // Get the visible map bounds (BBOX).
        let bounds = map.getBounds();
    
    // Initial fetch and display of features.
        fetchFeatures(bounds);

    ESRI ArcGIS Pro

    Accessing OS NGD data with OS NGD API – Features via ESRI ArcGIS Pro

    ESRI ArcGIS Pro is a desktop geographic information system (GIS) application that allows users to maintain, visualise and analyse spatial data.

    The instructions that follow demonstrate how to connect to OS NGD API – Features using ESRI ArcGIS Pro.

    hashtag
    What you'll need

    • ESRI ArcGIS Pro (version 3.4.0 or later).

    • A preloaded base map, for example, or .

    • OS NGD API – Features added to an API project in the OS Data Hub with an API Key. See for more information.

    hashtag
    Instructions

    1

    hashtag
    Set up a connection

    Once a new project with a new map has been set up, select Insert > Connections > Server > New OGC API Server.

    2

    hashtag
    Add an API URL and set up custom parameters

    In the Add OGC API Server Connection dialog:

    • Server URL: Enter the URL for OS NGD API – Features, excluding the API Key. For example, https://api.os.uk/features/ngd/ofa/v1.

    ESRI ArcGIS Pro Add OGC API Server Connection dialog.
    • Select Custom request parameters and enter the following:

      • Parameter: key

      • Value: [Insert your OS API Key here]

    • Click OK.

    3

    hashtag
    Adding layers to the map

    You can explore the available layers in OS NGD API – Features by using the ArcGIS Pro Catalog panel.

    In the Catalog panel:

    • To add a layer to the map: Right-click on a layer and select Add to Current Map.

    In the pop-up Add OGC API Layer(s) dialog:

    • Set the maximum features returned: Set the maximum number of features to be displayed (we suggest 1000).

    • To specify the extent:

      • Select the Use Spatial Extent checkbox.

    The layer will then display in the Contents panel and the data will display on the map:

    4

    hashtag
    Adjusting the map view

    Features will not automatically refresh when you zoom or pan on the map. This is purposely designed to protect the API from unnecessary spikes in usage.

    If the extent of the screen changes and you need to update the features displayed, right-click on the layer in the Contents panel, then select the OGC Features property for the layer, re-click Current visible extent, and click Apply and OK. This will force ESRI ArcGIS Pro to send a new request to the API and load features based on the new extent.

    ESRI ArcGIS Pro UI showing how to add a new connection via Insert -> Connections -> Server -> New OGC API Server.
    ESRI ArcGIS Pro UI.

    OpenLayers

    Accessing OS NGD API – Features via 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.

    hashtag
    What you'll need

    Get extent from: Select Current visible extent.

  • Click OK to load the features onto the map.

  • ESRI ArcGIS Pro Add OGC API Server Connection dialog displaying the OS NGD API – Features base URL and custom parameters added.
    ESRI ArcGIS Pro Add OGC API Server Connection dialog with custom request parameters set.
    ESRI ArcGIS Pro Catalog panel showing a list of available layers alongside the Add OGC Layer(s) dialog box to set the extent.
    ESRI ArcGIS Pro Add OGC API Layer(s) dialog and the Catalog panel.
    A map in ESRI ArcGIS Pro with features loaded from a selected layer.
    ESRI ArcGIS Pro UI showing OS NGD API – Features data in the map area.
    ESRI ArcGIS Pro UI showing OS NGD API – Features data in the map area. Layer Properties dialog box with the OGC Features property displayed that defines the number of features loaded and the extent used. This dialog box allows these properties to be changed.
    ESRI ArcGIS Pro UI showing OS NGD API – Features data in the map area and a Layer Properties dialog for one of the layers.
    ESRI ArcGIS Pro Add OGC API Server Connection dialog displaying the OS NGD API – Features base URL.

    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.

  • 1

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

    2

    hashtag
    Insert your API Key and OS NGD collection

    • To enable access to OS APIs an API Key is required. Inside the <script> tag, add a variable called

    3

    hashtag
    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

    4

    hashtag
    Add an OS NGD API – Features layer

    • Define and initialise the source using the ol.source.Vector class to make a request to OS NGD API – Features. By utilising the

    hashtag
    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 examplesarrow-up-right to learn more about advanced features and functionality, such as adding markers, pop-ups, and additional layers.

    OpenLayers arrow-up-right

    MapLibre GL JS

    Accessing OS NGD API – Features via MapLibre GL JS

    MapLibre GL JSarrow-up-right is a free and powerful JavaScript library for displaying interactive maps on the web. It's based on Mapbox GL JS and provides a wide range of features for creating maps with custom styles, markers and interactivity.

    hashtag
    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. See for more information.

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

    1

    hashtag
    Set up your HTML file

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

    hashtag
    What's next?

    Congratulations! You've successfully created a map using MapLibre GL JS and added an OS NGD layer using OS NGD API – Features 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.

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

  • ,
    layers
    and
    view
    . Add the following code inside the JavaScript block:

    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.

    ol.loadingstrategy.bbox
    this means that data from OS NGD API – Features will be loaded based on the visible map extent.
  • 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.

  • circle-exclamation

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

    Add the basic HTML structure to your file with a placeholder <div> for the map.

    2

    hashtag
    Insert your API Key and OS NGD collection

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

    3

    hashtag
    Add a basemap

    • To add the OS Maps API, you will need to define the map style using MapLibre GL JS's format. This specifies the source of map tiles, which will be retrieved from OS Maps API in the 'Light' raster tiles style.

    • Initialise the map object using the maplibregl.Map class to configure the basemap layer and define its properties – container, minZoom, maxZoom, maxBounds, style, center and zoom.

    • Add navigation controls to the map, excluding the compass button and disabling map rotation.

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

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

    • minZoom and maxZoom: Sets the minimum and maximum zoom level for the map. Users will not be able to go beyond these levels.

    4

    hashtag
    Add an OS NGD API – Features layer

    • Create an empty GeoJSON placeholder to hold the feature objects called by OS NGD API – Features.

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

    5

    hashtag
    Load and update features on the map dynamically

    • Event listeners are triggered when the map loads and finishes moving (panning or zooming) to load and update features based on the map's updated extent. Inside the map.on('load',...) event handler, we add styles for various types of features, including polygons, linestrings and points so that any collectionId specified will render.

    The map.on('moveend',...) event handler will then fetch and update the features based on the map's current extent.

    circle-exclamation

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

    code examplesarrow-up-right
    <!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/[email protected]/os-api-branding.css" />
        <script src="https://cdn.jsdelivr.net/gh/OrdnanceSurvey/[email protected]/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>
        
        <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>
    // Set API Key 
     const apiKey = 'INSERT_API_KEY_HERE';
     
     const collectionId= 'INSERT_COLLECTIONID_HERE';
    // 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
            })
        });
    // 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);
    <!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) | Maplibre GL JS</title>
        
        <!--Add the Ordnance Survey Styling-->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/OrdnanceSurvey/[email protected]/os-api-branding.css" />
        <script src="https://cdn.jsdelivr.net/gh/OrdnanceSurvey/[email protected]/os-api-branding.js"></script>
        
        <!--Add the Maplibre GL JSlibraries-->
        <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>

    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.

  • center: Sets the initial centre point of the map.

  • zoom: Sets the initial zoom level of the map.

  • // Set API Key 
     const apiKey = 'INSERT_API_KEY_HERE';
     
     const collectionId= 'INSERT_COLLECTIONID_HERE';
    // Create a map style object using the ZXY service.
        const style = {
        "version": 8,
            "sources": {
                "raster-tiles": {
                "type": "raster",
                "tiles": [`https://api.os.uk/maps/raster/v1/zxy/Light_3857/{z}/{x}/{y}.png?key=${apiKey}`],
                "tileSize": 256
                }
             },
             "layers": [{
                 "id": "os-maps-zxy",
                 "type": "raster",
                 "source": "raster-tiles"
             }]
         };
         
         // Initialize the map object.
             const map = new maplibregl.Map({
                 container: 'map',
                 minZoom: 6,
                 maxZoom: 19,
                 style: style,
                 maxBounds: [
                     [-10.76418, 49.528423],
                     [1.9134116, 61.331151]
                 ],
                 center: [-3.541809, 50.727589],
                 zoom: 17
             });
             
             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
                 }));
    let layers = [ 'polygon', 'linestring', 'point' ];
    
    // Create an empty GeoJSON FeatureCollection.
    const geoJson = {
        "type": "FeatureCollection",
        "features": []
    };
    
    // Define an asynchronous function to fetch and display the NGD Features API features.
    async function fetchFeatures(bounds) {
            // Generate a BBOX string for the map extent.
            const bbox = bounds.toArray().toString();
    
            // Construct the NGD Features API request URL.
            const url = `https://api.os.uk/features/ngd/ofa/v1/collections/${collectionId}/items?&key=${apiKey}&bbox=${bbox}`;
    
            // Fetch features from the API endpoint.
            const features = await fetch(url).then(response => response.json());
    
            // Update the source data with the new GeoJSON data.
            layers.forEach((element) => map.getSource(element).setData(features))
    }
    map.on('load', () => {
        // Add a fill style layer to render polygons on the map.
        map.addLayer({
            "id": "polygon",
            "type": "fill",
            "source": {
                "type": "geojson",
                "data": geoJson
            },
            "layout": {},
            "paint": {
                "fill-color": "rgba(51,136,255,0.3)",
                "fill-outline-color": "#38f"
            },
            "filter": [ "==", "$type", "Polygon" ]
        });
    
        // Add a line style layer to render linestrings on the map.
        map.addLayer({
            "id": "linestring",
            "type": "line",
            "source": {
                "type": "geojson",
                "data": geoJson
            },
            "layout": {},
            "paint": {
                "line-color": "#38f",
                "line-width": 1
            },
            "filter": [ "==", "$type", "LineString" ]
        });
    
        // Add a circle style layer to render points on the map.
        map.addLayer({
            "id": "point",
            "type": "circle",
            "source": {
                "type": "geojson",
                "data": geoJson
            },
            "layout": {},
            "paint": {
                "circle-color": "rgba(51,136,255,0.8)",
                "circle-radius": 4,
                "circle-stroke-color": "#fff",
                "circle-stroke-width": 1
            },
            "filter": ["==", "$type", "Point"]
        });
    
        // Get the visible map bounds (BBOX).
        let bounds = map.getBounds();
    
        // Initial fetch and display of features.
        fetchFeatures(bounds);
            
        // Add event which will be triggered when the map has finshed moving (pan + zoom).
        // Implements a simple strategy to only request data when the map viewport invalidates
        // certain bounds.
        map.on('moveend', function() {
            let bounds1 = new maplibregl.LngLatBounds(bounds.getSouthWest(), bounds.getNorthEast()),
                bounds2 = map.getBounds();
    
            if( JSON.stringify(bounds) !== JSON.stringify(bounds1.extend(bounds2)) ) {
                bounds = bounds2;
                fetchFeatures(bounds);
            }
        });
    });
    OS Maps API
    Getting started with an API project
    OS Maps API
    OS Vector Tile API
    Getting started with an API project
    Getting started with an API project
    Getting started with an API project
    OS Maps API
    OS Vector Tile API
    Getting started with an API project
    Getting started with an API project
    Getting started with an API project
    OS Maps API
    OS Vector Tile API
    Getting started with an API project
    osngd-resources/api-resources at main · OrdnanceSurvey/osngd-resourcesGitHubchevron-right
    Access the OS NGD API resources here
    Logo