Skip to main content

alphaThis is a new frontend component. Help us improve it and give your feedback on Slack.

Datasets Plugin

The datasets plugin renders GeoJSON and vector tile datasets on the map, with a Layers menu for turning them on and off. It supports polygon, line and symbol (point) layers, sublayer style rules, and runtime style and data updates.

NOTE

To show a key of the datasets' symbols, also add the Map Key plugin. Datasets and sublayers with showInKey: true appear in the key.

ESM usage

import createDatasetsPlugin from '@defra/interactive-map/plugins/datasets'
const datasetsPlugin = createDatasetsPlugin({
datasets: [
{
id: 'my-parcels',
label: 'My parcels',
geojson: 'https://example.com/api/parcels',
minZoom: 10,
maxZoom: 24,
showInKey: true,
showInMenu: true,
style: {
stroke: '#d4351c',
strokeWidth: 2,
fill: 'transparent'
}
}
]
})
const interactiveMap = new InteractiveMap({
plugins: [datasetsPlugin]
})

UMD usage

Copy the entire plugins/datasets/dist/umd/ directory to /your-assets-path/plugins/datasets/umd/. The plugin uses dynamic imports, so all files in the directory must be served from the same location. Then add the script tag:

<script defer src="/your-assets-path/plugins/datasets/umd/index.js"></script>
const datasetsPlugin = defra.datasetsPlugin({
datasets: [
{
id: 'my-parcels',
label: 'My parcels',
geojson: 'https://example.com/api/parcels',
minZoom: 10,
maxZoom: 24,
showInKey: true,
showInMenu: true,
style: {
stroke: '#d4351c',
strokeWidth: 2,
fill: 'transparent'
}
}
]
})
const interactiveMap = new defra.InteractiveMap('map', {
plugins: [datasetsPlugin]
})

NOTE

GOV.UK Prototype Kit — skip the copy step. All files are served automatically. Use this path instead:

<script defer src="/plugin-assets/%40defra%2Finteractive-map/plugins/datasets/dist/umd/index.js"></script>

Options

Options are passed to the factory function when creating the plugin.


datasets

Type:
Dataset[] (required)

The datasets to render on the map.

See Dataset configuration below.


hasMenu

Type:
boolean
Default:
true

Shows the Layers button and panel. Set to false when the layers are controlled by your own UI.


globals

Type:
{ opacityMode?: 'dataset' | 'global' | 'multiply', opacity?: number, visible?: boolean }
Default:
{ opacityMode: 'dataset', opacity: 1, visible: true }

Starting state that applies across all datasets, as later set by setGlobals, setOpacity and setDatasetVisibility without a scope.

createDatasetsPlugin({
datasets,
globals: { opacityMode: 'multiply', opacity: 0.8 }
})

manifest

Type:
Partial<PluginManifest>

Overrides for the plugin's buttons, panels and controls, matched by id. See PluginDescriptor.manifest.


Dataset configuration

Each entry in the datasets array is a data source and how it's rendered. Set one of geojson, dynamicGeoJSON or tiles.


id

Type:
string (required)

Unique identifier for the dataset. Used in all method calls.


label

Type:
string

Name shown in the Layers menu and Key panels.


geojson

Type:
string | GeoJSON.FeatureCollection

GeoJSON source: a URL for remote data, or a FeatureCollection for inline data.

For data that needs authentication headers or viewport-based filtering, use dynamicGeoJSON instead.


dynamicGeoJSON

Type:
DynamicGeoJSONConfig

Fetches GeoJSON for the current viewport as the map moves. Use instead of geojson for data too large to load at once.

The plugin calls your API as the map pans and zooms, and evicts features far from the viewport. A feature that's already held is kept as it is when a later fetch returns it again; use refreshDataset to reload changed data.

PropertyTypeDescription
urlstringRequired. Base URL of the GeoJSON API
idPropertystringRequired. Property that uniquely identifies each feature, used to deduplicate features across fetches. A feature without it is identified by its own id
transformRequest(url: string, context: { bbox: number[], zoom: number, dataset: Dataset }) => string | { url: string, headers?: Record<string, string> }Called before each fetch, with the viewport as [west, south, east, north]. Return a URL, or a URL and headers, e.g. to add the bbox to the URL and an auth header
maxFeaturesnumberCap on the features held in memory. Older features outside the viewport are evicted when it's exceeded

transformRequest signature: transformRequest(url, { bbox, zoom, dataset })

ArgumentTypeDescription
urlstringThe base URL
bboxnumber[]Current viewport bounds as [west, south, east, north]
zoomnumberCurrent map zoom level
datasetDatasetThe full dataset configuration
{
id: 'land-parcels',
dynamicGeoJSON: {
url: 'https://example.com/api/parcels',
idProperty: 'parcel_id',
transformRequest: (url, { bbox }) => {
const separator = url.includes('?') ? '&' : '?'
return {
url: `${url}${separator}bbox=${bbox.join(',')}`,
headers: { Authorization: `Bearer ${getToken()}` }
}
},
maxFeatures: 50000
},
minZoom: 10,
style: { stroke: '#d4351c', strokeWidth: 2 }
}

tiles

Type:
string | string[]

Vector tile URL template, or templates, e.g. 'https://example.com/tiles/{z}/{x}/{y}'. When set, the dataset uses a vector tile source instead of GeoJSON.


sourceLayer

Type:
string

The layer to render within the vector tile source. Required with tiles.


tileMatrixSet

Type:
{ origin: [number, number], extentAtZoom0: number }

OpenLayers only. The tile grid the tiles are cut on, in EPSG:27700 metres. Defaults to the OS National Grid tile grid, { origin: [-238375, 1376256], extentAtZoom0: 1835008 }.

It's a square grid where zoom 0 is a single tile and each zoom level splits every tile into four. origin is the top-left corner of tile 0/0/0 and extentAtZoom0 is its width. In the default grid, tile z/x/y is OS tile (z-3)/x/y. For tiles cut by a PostGIS function with ST_TileEnvelope, these are the bounds ST_MakeEnvelope(-238375, -458752, 1596633, 1376256, 27700). MapLibre uses the Web Mercator tile grid.

tileMatrixSet: {
origin: [0, 1300000],
extentAtZoom0: 1300000
}

idProperty

Type:
string

Property that uniquely identifies features in a static geojson source. Needed for setFeatureVisibility. For dynamicGeoJSON, set it inside that object instead.

The plugin promotes this property to the underlying engine's feature ID (MapLibre's promoteId; OpenLayers' ol/Feature id), so feature IDs are stable and come from your data. The IDs you pass to setFeatureVisibility must match its values.

// Features have { properties: { parcel_id: 'ABC123', ... } }
{
id: 'my-parcels',
geojson: 'https://example.com/api/parcels',
idProperty: 'parcel_id'
}

generateIds

Type:
boolean

MapLibre only. Gives GeoJSON features integer IDs by their position, for setFeatureVisibility when the features have no unique property. The IDs reset on every setData.

The IDs are 0-based array indexes, so if your data changes between setData calls, the same ID may refer to a different feature. Prefer idProperty whenever your data has a stable unique field. With OpenLayers, use idProperty instead.

{
id: 'my-parcels',
geojson: 'https://example.com/api/parcels',
generateIds: true
}

filter

Type:
FilterExpression

Only features that match are rendered.

A MapLibre-style filter expression, applied to the dataset's map layers. The OpenLayers provider evaluates it with its own expression engine.

NOTE

OpenLayers' expression parser is stricter than MapLibre's in places — e.g. in's second argument must be a real array (['literal', [...]]), where MapLibre also accepts a bare scalar.

filter: ['==', ['get', 'status'], 'active']

minZoom

Type:
number
Default:
6

Minimum zoom level at which the dataset is visible.


maxZoom

Type:
number
Default:
24

Maximum zoom level at which the dataset is visible.


visible

Type:
boolean
Default:
true

Initial visibility of the dataset.


visibleWhen

Type:
boolean | { mapStyleId?: string | string[], menu?: Record<string, Array<string | boolean>> }

Shows the dataset only for some map styles or menu choices. Applies on top of visible: both must allow it. Sublayers inherit it.

An object's conditions must all be met:

PropertyDescription
mapStyleIdThe current map style's id is this, or one of these
menuFor each key, the menu plugin's state is one of the listed values. For a radio group, the key is the group's id and the values are option ids. For a checkbox, the key is the checkbox's own id and the values are true or false
// Only on the dark basemap
visibleWhen: { mapStyleId: 'dark' }
// Only while the 'period' radio group has 'medieval' or 'roman' selected
visibleWhen: { menu: { period: ['medieval', 'roman'] } }

showInKey

Type:
boolean
Default:
false

Shows the dataset in the Key panel, which needs the map key plugin. Sublayers inherit it.

The entry shows the dataset's style symbol and label. Set showInKey: false on a sublayer to leave it out.


showInMenu

Type:
boolean
Default:
false

Shows the dataset in the Layers menu, so users can turn it on and off. Sublayers inherit it.

Set showInMenu: false on a sublayer to leave it out.

The Layers button is only shown while at least one dataset or sublayer is in the menu.


groupLabel

Type:
string

Groups this dataset with others that have the same groupLabel in the Layers menu. They're shown as a single collapsible group.


groupId

Type:
string

ID of the dataset's group in the Key panel, used to match MapKeyPluginOptions.groups and addSymbol entries. Defaults to the group label (groupLabel, else the dataset's label for its sublayers) in lower case, with spaces replaced by hyphens. Sublayers inherit it.

So a dataset labelled 'Land covers' with sublayers has the group ID 'land-covers'.


style

Type:
DatasetStyle

How the dataset looks. All style properties must be nested within this object.

A style that sets none of stroke, fill, fillPattern, fillPatternSvgContent, symbol or symbolSvgContent draws a default red outline (stroke: '#d4351c'), described in the key as 'red outline'. Setting any of them replaces that default, including an empty value such as stroke: null or fill: 'transparent'. Other properties, such as strokeWidth or opacity, apply to the default outline. For a sublayer, this applies to its style merged with the parent's.

Common properties:
PropertyTypeDescription
opacitynumberLayer opacity from 0 to 1
symbolDescriptionstring | Record<string, string>Accessible description of the symbol shown in the key
Polygon/line properties:
PropertyTypeDescription
strokestring | Record<string, string> | nullStroke (outline) colour. A colour, or colours keyed by map style id, e.g. { outdoor: '#d4351c', dark: '#ffffff' }
strokeWidthnumberStroke width in pixels. Default: 2
strokeDashArraynumber[]Dash pattern for the stroke, e.g. [4, 2]
fillstring | Record<string, string>Fill colour. Use 'transparent' for no fill. With a fill, the key symbol is a shape; without one it's a line. See Map Key: Key symbol shape
fillPatternstringNamed fill pattern, e.g. 'diagonal-cross-hatch', 'horizontal-hatch', 'dot' or 'vertical-hatch'
fillPatternSvgContentstringRaw SVG content for a custom fill pattern
fillPatternForegroundColorstring | Record<string, string>Foreground colour of the fill pattern
fillPatternBackgroundColorstring | Record<string, string>Background colour of the fill pattern
Symbol (point) properties:

Setting symbol or symbolSvgContent renders the dataset as a point layer instead of a polygon/line layer.

Each is documented in full in Symbol Config, under a symbol prefix here to distinguish them from the polygon/line properties in the same style object:

PropertySymbol Config property
symbolsymbol
symbolSvgContentsvgContent
symbolViewBoxviewBox
symbolAnchoranchor
symbolSizesize
symbolBackgroundColorbackgroundColor
symbolForegroundColorforegroundColor
symbolHaloWidthStroke width of the symbol's halo, in SVG units. Not currently documented in Symbol Config
symbolGraphicgraphic

They follow the same resolution order and support style-keyed colour objects in the same way as markers.

Any other symbol* property fills the custom token named after it without the prefix, so symbolAccentColor fills {{accentColor}}, on the map and in the key. Custom tokens are inherited by sublayers and can be changed with setStyle.

haloColor, selectedColor and activeColor are not settable here — they are basemap-level properties set on MapStyleConfig.

symbolDescription only affects how an entry looks in the Key panel — see Map Key: Key display properties for details.

// Polygon/line dataset
style: {
stroke: { outdoor: '#d4351c', dark: '#ffffff' },
strokeWidth: 2,
fill: 'rgba(212,53,28,0.1)',
symbolDescription: { outdoor: 'Red outline' }
}
// Point dataset — registered symbol with colour overrides
style: {
symbol: 'pin',
symbolBackgroundColor: '#1d70b8',
symbolForegroundColor: '#ffffff'
}
// Point dataset — style-keyed colours for multi-basemap support
style: {
symbol: 'pin',
symbolBackgroundColor: { outdoor: '#1d70b8', dark: '#5694ca' }
}
// Point dataset — custom inline SVG
style: {
symbolSvgContent: '<circle cx="19" cy="19" r="12" fill="{{backgroundColor}}"/>',
symbolViewBox: '0 0 38 38',
symbolAnchor: [0.5, 0.5],
symbolBackgroundColor: '#1d70b8'
}
// Point dataset — custom inline SVG with a custom token
style: {
symbolSvgContent: '<circle cx="19" cy="19" r="12" fill="{{backgroundColor}}" stroke="{{accentColor}}"/>',
symbolViewBox: '0 0 38 38',
symbolBackgroundColor: '#1d70b8',
symbolAccentColor: { outdoor: '#ffdd00', dark: '#f47738' }
}

sublayers

Type:
Sublayer[]

Rules that partition the dataset into visually distinct groups of features. Each sublayer is rendered as its own map layer.

Sublayer styles merge over the parent's — the sublayer wins on any property it sets. Rendering type is driven by the merged result: symbol > fillPattern/fill > stroke.

Sublayer properties

PropertyTypeDescription
idstringRequired. Unique identifier within the dataset
labelstringName shown in the Layers menu and Key panels
filterFilterExpressionWhich of the dataset's features belong to this sublayer
styleDatasetStyleStyle overrides, merged over the dataset's style
showInKeybooleanShows this sublayer in the Key panel. Inherits from the dataset when not set
showInMenubooleanShows this sublayer in the Layers menu. Inherits from the dataset when not set
Polygon/line example:
{
id: 'field-parcels',
label: 'Field parcels',
geojson: parcelsData,
showInKey: true,
showInMenu: true,
sublayers: [
{
id: 'active',
label: 'Active parcels',
filter: ['==', ['get', 'status'], 'active'],
style: {
stroke: '#00703c',
fill: 'rgba(0,112,60,0.1)',
symbolDescription: 'Green outline'
}
},
{
id: 'inactive',
label: 'Inactive parcels',
filter: ['==', ['get', 'status'], 'inactive'],
style: {
stroke: '#d4351c',
fillPattern: 'diagonal-cross-hatch',
fillPatternForegroundColor: '#d4351c'
}
}
]
}
Symbol (point) example — scheduled monuments by type:

Here the parent defines the shared symbol shape; each sublayer only overrides what differs.

{
id: 'scheduled-monuments',
geojson: scheduledMonumentsData,
showInKey: true,
showInMenu: true,
style: { symbol: 'square' },
sublayers: [
{
id: 'prehistoric',
label: 'Prehistoric sites',
filter: ['==', ['get', 'type'], 'prehistoric'],
style: { symbolBackgroundColor: '#0f7a52' }
},
{
id: 'roman',
label: 'Roman sites',
filter: ['==', ['get', 'type'], 'roman'],
style: { symbolBackgroundColor: '#54319f' }
},
{
id: 'medieval',
label: 'Medieval sites',
filter: ['==', ['get', 'type'], 'medieval'],
style: { symbolBackgroundColor: '#ca357c' }
}
]
}

Methods

Methods are called on the plugin instance after the datasets:ready event.

The API follows a consistent pattern: the primary value is the first argument, with an optional scope object as the second argument. Omitting the scope applies the operation globally where supported.


addDataset(dataset)

Add a dataset to the map. Call it after the datasets:ready event.

ArgumentTypeDescription
datasetDatasetThe dataset to add. Accepts the same properties as the datasets option's entries
interactiveMap.on('datasets:ready', () => {
datasetsPlugin.addDataset({
id: 'new-layer',
geojson: 'https://example.com/api/features',
minZoom: 10,
style: { stroke: '#0000ff' }
})
})

removeDataset(datasetId)

Remove a dataset from the map.

ArgumentTypeDescription
datasetIdstringID of the dataset to remove
datasetsPlugin.removeDataset('my-parcels')

setDatasetVisibility(visible, scope?)

Show or hide datasets, a dataset or a sublayer. Without a scope, it applies to all datasets.

Showing a dataset with sublayers keeps hidden any sublayers that were hidden on their own before the dataset was hidden.

ArgumentTypeDescription
visiblebooleantrue to show, false to hide
scope.datasetIdstringOptional. ID of the dataset. Leaving it out applies the method to all datasets
scope.sublayerIdstringOptional. ID of a sublayer of the dataset, to target only that sublayer
// Global — all datasets
datasetsPlugin.setDatasetVisibility(false)
datasetsPlugin.setDatasetVisibility(true)
// Single dataset
datasetsPlugin.setDatasetVisibility(false, { datasetId: 'my-parcels' })
// Single sublayer
datasetsPlugin.setDatasetVisibility(false, { datasetId: 'my-parcels', sublayerId: 'active' })

setFeatureVisibility(visible, featureIds, scope)

Show or hide features in a dataset without removing them from its source. The IDs are matched against the dataset's idProperty values, or the features' own id when it has none.

The dataset needs idProperty or generateIds: true for features to be matched. A warning is logged if it has neither.

ArgumentTypeDescription
visiblebooleantrue to show, false to hide
featureIdsArray<string | number>IDs of the features to show or hide
scope.datasetIdstringID of the dataset the features are in
// Dataset configured with idProperty: 'parcel_id'
datasetsPlugin.setFeatureVisibility(false, ['ABC123', 'DEF456'], {
datasetId: 'my-parcels'
})
// Show previously hidden features
datasetsPlugin.setFeatureVisibility(true, ['ABC123'], {
datasetId: 'my-parcels'
})

setStyle(style, scope)

Change the style of a dataset or sublayer. Only the properties given are changed. A sublayer keeps inheriting every other property from its dataset.

For symbol datasets, pass symbol or any other symbol* property to change the symbol.

ArgumentTypeDescription
styleDatasetStyleStyle properties to change. Accepts the same properties as a dataset's style
scope.datasetIdstringID of the dataset
scope.sublayerIdstringOptional. ID of a sublayer of the dataset, to target only that sublayer
// Polygon/line dataset
datasetsPlugin.setStyle(
{ stroke: '#0000ff', strokeWidth: 3 },
{ datasetId: 'my-parcels' }
)
// Sublayer — polygon
datasetsPlugin.setStyle(
{ stroke: '#00703c', fillPattern: 'diagonal-cross-hatch', fillPatternForegroundColor: '#00703c' },
{ datasetId: 'my-parcels', sublayerId: 'active' }
)
// Sublayer — symbol colour override
datasetsPlugin.setStyle(
{ symbolBackgroundColor: '#912b88' },
{ datasetId: 'flood-warnings', sublayerId: 'severe' }
)

getStyle(scope)

Get the current style of a dataset or sublayer.

Returns:
DatasetStyle | null. The style, or null if the dataset or sublayer isn't found.
ArgumentTypeDescription
scope.datasetIdstringID of the dataset
scope.sublayerIdstringOptional. ID of a sublayer of the dataset, to target only that sublayer
// Dataset style
const style = datasetsPlugin.getStyle({ datasetId: 'my-parcels' })
// Sublayer style
const style = datasetsPlugin.getStyle({ datasetId: 'my-parcels', sublayerId: 'active' })

setOpacity(opacity, scope?)

Set the opacity of a dataset or sublayer, or the global opacity without a scope. Safe to call on every change of a slider: it doesn't remove and re-add layers.

ArgumentTypeDescription
opacitynumberFrom 0 (transparent) to 1 (fully opaque)
scope.datasetIdstringOptional. ID of the dataset. Leave it out to set the global opacity
scope.sublayerIdstringOptional. ID of a sublayer of the dataset, to target only that sublayer
// Global — all datasets
datasetsPlugin.setOpacity(0.5)
// Single dataset
datasetsPlugin.setOpacity(0.5, { datasetId: 'my-parcels' })
// Single sublayer
datasetsPlugin.setOpacity(0.5, { datasetId: 'my-parcels', sublayerId: 'active' })

getOpacity(scope?)

Get the opacity of a dataset or sublayer, or the global opacity without a scope, e.g. to set a slider's starting value. The global opacity is 1 until it's set.

Returns:
number | null. The opacity, or null if the dataset or sublayer isn't found.
ArgumentTypeDescription
scope.datasetIdstringOptional. ID of the dataset. Leave it out to get the global opacity
scope.sublayerIdstringOptional. ID of a sublayer of the dataset, to target only that sublayer
// Global — read back after setOpacity() for slider initialisation
const opacity = datasetsPlugin.getOpacity()
// Single dataset
const opacity = datasetsPlugin.getOpacity({ datasetId: 'my-parcels' })
// Single sublayer
const opacity = datasetsPlugin.getOpacity({ datasetId: 'my-parcels', sublayerId: 'active' })

setData(geojson, scope)

Replace the GeoJSON data of a dataset. Has no effect on vector tile or dynamicGeoJSON datasets: use refreshDataset to reload a dynamicGeoJSON one.

ArgumentTypeDescription
geojsonGeoJSON.FeatureCollectionThe new data
scope.datasetIdstringID of the dataset to replace the data of
datasetsPlugin.setData(
{ type: 'FeatureCollection', features: [...] },
{ datasetId: 'my-parcels' }
)

refreshDataset(datasetId)

Reload a dynamicGeoJSON dataset: clear the features it holds and fetch the current viewport again. Use it when the data behind the API has changed, as features already held aren't replaced by later fetches. Has no effect on other datasets.

ArgumentTypeDescription
datasetIdstringID of the dataset to reload
datasetsPlugin.refreshDataset('land-parcels')

setGlobals(values)

Set state that applies across all datasets. Currently only opacityMode, which sets how the global opacity and each dataset's opacity combine:

  • 'dataset': each dataset uses its own style.opacity, and the global opacity is ignored
  • 'global': every dataset uses the global opacity, ignoring their own
  • 'multiply': each dataset's opacity is multiplied by the global opacity

An invalid opacityMode is ignored, with a warning.

ArgumentTypeDescription
values.opacityMode'dataset' | 'global' | 'multiply'How the global opacity and each dataset's opacity combine
datasetsPlugin.setGlobals({ opacityMode: 'multiply' })

Events

Subscribe to events using interactiveMap.on().


datasets:ready

Emitted once all datasets have been initialised and rendered on the map.

Payload:
None
interactiveMap.on('datasets:ready', () => {
console.log('Datasets are ready')
// Safe to call API methods from here
const style = datasetsPlugin.getStyle({ datasetId: 'my-parcels' }) // unchanged — scope object
})