Skip to main content

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

Interact Plugin

The interact plugin lets users select map features, select markers, or place a location marker.

Usage

import createInteractPlugin from '@defra/interactive-map/plugins/interact'
const interactPlugin = createInteractPlugin({
interactionModes: ['selectMarker', 'selectFeature'],
multiSelect: true,
layers: [
{ layerId: 'my-layer', idProperty: 'id' }
]
})
const interactiveMap = new InteractiveMap({
plugins: [interactPlugin]
})

Options

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


interactionModes

Type:
Array<'selectMarker' | 'selectFeature' | 'placeMarker'>
Default:
['selectMarker']

Which interactions are active when the user clicks the map. They're always processed in the order marker selection, feature selection, place marker. Values can be combined freely.

  • 'selectMarker' — clicking a placed marker toggles its selection state
  • 'selectFeature' — clicking the map attempts to match a feature from layers
  • 'placeMarker' — if no feature is matched (or selectFeature is not active), places a location marker at the clicked coordinates

NOTE

On touch, a crosshair and "Select" action button are shown when 'placeMarker' or 'selectFeature' is included — modes where a precise point on the map needs to be chosen. When 'selectMarker' is the only active mode, touch users tap markers directly and neither is shown. touchTarget turns them off for touch in every mode.

Keyboard users get the crosshair while the map has focus, and press Enter to select. Opening the map controls shows the crosshair and "Select" button for every input type.

Common combinations:
interactionModes: ['selectMarker'] // marker selection only (default)
interactionModes: ['selectFeature'] // feature selection only
interactionModes: ['placeMarker'] // always place a marker on click
interactionModes: ['selectMarker', 'selectFeature'] // select markers or features
interactionModes: ['selectFeature', 'placeMarker'] // select features, fall back to placing a marker
interactionModes: ['selectMarker', 'selectFeature', 'placeMarker'] // all interactions active

layers

Type:
InteractLayerConfig[]
Default:
[]

The layers whose features can be selected. Each entry says which layer to watch and how to identify its features.

layers: [
{ layerId: 'my-polygons', idProperty: 'guid' },
{ layerId: 'my-lines' }
]

InteractLayerConfig properties

PropertyTypeDescription
layerIdstringRequired. The map layer to enable selection on. For the datasets plugin, use the dataset ID, or the sublayer ID for datasets with sublayers. See Finding layer IDs
idPropertystringProperty used as the feature's unique identifier. If omitted, features are matched by index
labelPropertystringProperty used as the feature's label in the keyboard-accessible listbox. Required for features to appear in keyboard navigation
selectedStrokestringSelection stroke colour for this layer. Defaults to MapStyleConfig.selectedColor
selectedFillstringSelection fill colour for this layer. Defaults to transparent
selectedStrokeWidthnumberSelection stroke width for this layer. Defaults to 3
activeStrokestringKeyboard cursor ring colour for this layer. Defaults to MapStyleConfig.activeColor

Selection colours — by default the selection stroke colour comes from MapStyleConfig.selectedColor (falling back to the mapColorScheme scheme default), so it stays consistent with the rest of the map theme. The fill defaults to transparent. Set selectedStroke, selectedFill and selectedStrokeWidth on a layer to override them for that layer.

Finding layer IDs

What to use as layerId depends on how your data is added to the map — these are the layers the plugin will enable for feature selection:

  • Map provider directly — use the layer IDs defined in your style or added via your map provider's layer API
  • Datasets plugin — use the dataset ID, or the sublayer ID for datasets with sublayers
  • Draw plugin — uses generated layer IDs; inspect the map at runtime to find them (e.g. fill-inactive.cold, stroke-inactive.cold when using MapLibre)

If you're unsure of the layer IDs available at runtime, set debug: true in the interact plugin options — this lets you query the map and inspect layer names in the browser console.


multiSelect

Type:
boolean
Default:
false

When true, selecting more features adds them to the selection instead of replacing it.


contiguous

Type:
boolean
Default:
false

With multiSelect, keeps the selected features touching each other. Selecting a feature that doesn't touch the selection starts a new selection with it. Unselecting one that joins two parts keeps only the part connected to the first selected feature.

Use it, for example, to select parcels that can be merged.

Has no effect without multiSelect. Whether the selection is contiguous is also sent with interact:selectionchange, whatever this option is set to.


deselectOnClickOutside

Type:
boolean
Default:
false

When true, clicking outside any selectable feature clears the selection.


tolerance

Type:
number
Default:
10

Click detection radius in pixels for line features. Polygons and symbols use exact hit detection.

Lines are thin, so they need a buffer to be selected reliably.


touchTarget

Type:
boolean
Default:
true

When false, touch users tap features directly instead of using the crosshair and Select button. Only turn it off when the features are at least 44×44 CSS pixels at the zoom levels used.

Opening the map controls shows both again, for every input type. Keyboard behaviour is unchanged.

createInteractPlugin({
interactionModes: ['selectFeature'],
touchTarget: false
})

IMPORTANT

Only set touchTarget: false when the features users select are at least 44×44 CSS pixels at the zoom levels they use (WCAG 2.2 Target Size (Enhanced)), for example field parcels at a sensible zoom. Thin lines and small shapes are hard to tap accurately, especially for users with motor impairments, who rely on the crosshair to position the map instead.

NOTE

If you also use the draw plugin, disable interact while drawing or editing, so the two plugins don't both control the crosshair. See Application mode.


closeOnAction

Type:
boolean
Default:
true

When true, the app closes after the user clicks Done or Cancel.


marker

Type:
MarkerOptions

Appearance of the location marker. When not set, it inherits from the constructor's symbolDefaults.

Accepts the same properties as MarkerOptions. See Symbol Config for the full property reference.

createInteractPlugin({
marker: {
symbol: 'pin',
backgroundColor: { outdoor: '#d4351c', dark: '#ff6b6b' },
foregroundColor: '#ffffff'
}
})

debug

Type:
boolean

When true, lets you query the map and inspect layer names in the browser console. It logs the features under each click. See Finding layer IDs.


manifest

Type:
Partial<PluginManifest>

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


Methods

Methods are called on the plugin instance after the map is ready.


enable(options?)

Enable interaction. Shows the action buttons and turns on feature selection or marker placement. Any options given override the factory options for this session.

ArgumentTypeDescription
optionsInteractPluginOptionsOptional. Factory options to override for this session
interactiveMap.on('map:ready', () => {
interactPlugin.enable()
})
// Override options at runtime
interactPlugin.enable({ multiSelect: true, interactionModes: ['selectFeature'] })

disable()

Disable interaction. Hides the action buttons and turns interactions off.

interactPlugin.disable()

clear()

Clear all selected features and markers, and remove the location marker.

interactPlugin.clear()

selectFeature(featureInfo)

Select a feature. Without multiSelect, the feature replaces the current selection.

ArgumentTypeDescription
featureInfo.featureIdstringThe feature's identifier value
featureInfo.layerIdstringOptional. The layer the feature belongs to
featureInfo.idPropertystringOptional. The property used as the identifier
interactPlugin.selectFeature({
featureId: 'abc123',
layerId: 'my-layer',
idProperty: 'id'
})

unselectFeature(featureInfo)

Unselect a feature.

ArgumentTypeDescription
featureInfo.featureIdstringThe feature's identifier value
featureInfo.layerIdstringOptional. The layer the feature belongs to
featureInfo.idPropertystringOptional. The property used as the identifier
interactPlugin.unselectFeature({
featureId: 'abc123'
})

selectMarker(markerId)

Select a marker. Has no effect if it's already selected. Without multiSelect, it clears any selected features and replaces the marker selection; with it, the marker is added to the selection.

It works immediately after enable(), without waiting for a re-render.

ArgumentTypeDescription
markerIdstringThe ID of the marker to select
interactPlugin.selectMarker('my-marker')

unselectMarker(markerId)

Unselect a marker. Has no effect if it isn't selected.

It works immediately after enable(), without waiting for a re-render.

ArgumentTypeDescription
markerIdstringThe ID of the marker to unselect
interactPlugin.unselectMarker('my-marker')

Events

Subscribe to events using interactiveMap.on().


interact:done

Emitted when the user confirms their selection (clicks "Done").

Payload:
{
// If a location marker was placed:
coords: [lng, lat],
// If features were selected:
selectedFeatures: [...],
// If markers were selected:
selectedMarkers: ['...']
}
interactiveMap.on('interact:done', (event) => {
if (event.coords) {
console.log('Location selected:', event.coords)
}
if (event.selectedFeatures) {
console.log('Features selected:', event.selectedFeatures)
}
if (event.selectedMarkers) {
console.log('Markers selected:', event.selectedMarkers)
}
})

interact:cancel

Emitted when the user cancels the interaction (clicks "Back").

Payload:
None
interactiveMap.on('interact:cancel', () => {
console.log('Interaction cancelled')
})

interact:selectionchange

Emitted whenever the selected features or selected markers change.

Payload:
{
selectedFeatures: [
{ featureId: '...', layerId: '...', idProperty: '...', properties: {...} }
],
selectedMarkers: ['...'], // array of selected marker IDs
contiguous: boolean // true when 2+ features are selected and all form a single contiguous group
}
interactiveMap.on('interact:selectionchange', (event) => {
console.log('Selected features:', event.selectedFeatures)
})

interact:markerchange

Emitted when a location marker is placed or moved.

Payload:
{
coords: [lng, lat]
}
interactiveMap.on('interact:markerchange', ({ coords }) => {
console.log('Marker moved to:', coords)
})