Search Plugin
Location search with autocomplete, using the OS Names API and any custom datasets. Custom datasets let you search addresses, features, or other geographic data.
Usage
import searchPlugin from '@defra/interactive-map/plugins/search'
const interactiveMap = new InteractiveMap({ plugins: [ searchPlugin({ osNamesURL: process.env.OS_NAMES_URL, transformRequest: transformGeocodeRequest, showMarker: true }) ]})Options
Options are passed to the factory function when creating the plugin.
osNamesURL
- Type:
string
URL for the OS Names API, with a {query} placeholder. When provided, it's the primary search source.
searchPlugin({ osNamesURL: 'https://api.os.uk/search/names/v1/find?query={query}&key=YOUR_KEY'})transformRequest
- Type:
(request: SearchRequestConfig, query: string) => SearchRequestConfig | Promise<SearchRequestConfig>
Called before each search request that isn't built by a dataset's buildRequest. Use it to add authentication headers or modify the request.
It receives the default request config — the url and the options passed to fetch — and the query string, and returns a (modified) request config. Can be async.
searchPlugin({ transformRequest: async (request, query) => ({ ...request, options: { ...request.options, headers: { Authorization: `Bearer ${token}` } } })})regions
- Type:
string[]- Default:
['england', 'scotland', 'wales']
UK regions to keep OS Names results from, matched case-insensitively against each result's country.
searchPlugin({ regions: ['england', 'wales']})customDatasets
- Type:
CustomDataset[]
Custom search sources to extend or replace the built-in OS Names search. Each defines how to fetch and parse results for a particular type of query.
See Custom datasets below for full details.
searchPlugin({ customDatasets: [gridRefDataset, parcelDataset]})showMarker
- Type:
boolean- Default:
true
Whether to place a marker on the map when a search result is selected.
marker
- Type:
MarkerOptions
Appearance of the marker placed when a search result is selected. When not set, the marker inherits from the constructor's symbolDefaults.
Accepts the same properties as MarkerOptions. See Symbol Config for the full property reference.
searchPlugin({ showMarker: true, marker: { symbol: 'circle', backgroundColor: { outdoor: '#1d70b8', dark: '#5694ca' } }})width
- Type:
string
CSS width of the search input on tablet and desktop, for example '300px'.
placeholder
- Type:
string- Default:
'Search'
Placeholder text shown in the search input when it's empty.
searchPlugin({ placeholder: 'Search for a location'})expanded
- Type:
boolean- Default:
false
When true, the search input is always shown and there's no open button.
- Mobile — the search form always lives in the
headerslot, above the top row. By default it's collapsed behind a button tap; settingexpanded: trueshows it inline at all times and removes the open button. - Tablet and desktop — the search always sits in the
top-leftslot regardless of this setting, but settingexpanded: trueremoves the open button so the input is immediately visible without interaction.
minSearchLength
- Type:
number- Default:
3
Minimum number of characters typed before a search starts.
searchPlugin({ minSearchLength: 4})maxSuggestions
- Type:
number- Default:
8
Maximum number of OS Names suggestions shown. Custom datasets control their own counts, in parseResults.
searchPlugin({ maxSuggestions: 5})noResultsMessage
- Type:
string- Default:
'No results available'
Message shown when a query returns no results. It's shown below the search input.
searchPlugin({ noResultsMessage: 'No matching locations found'})searchErrorMessage
- Type:
string- Default:
'Sorry, there was a problem with search'
Message shown when a dataset returns an error response, in place of noResultsMessage. It's shown below the search input.
searchPlugin({ searchErrorMessage: 'Search is temporarily unavailable'})manifest
- Type:
Partial<PluginManifest>
Overrides for the plugin's buttons, panels and controls, matched by id. See PluginDescriptor.manifest.
Custom datasets
Custom datasets let you add your own search sources alongside or instead of OS Names. Pass them via the customDatasets option as an array of dataset configuration objects.
const gridRefDataset = { name: 'gridref', includeRegex: /^[A-Z]{2}\d{6,10}$/i, buildRequest: (query) => ({ url: `https://api.example.com/gridref?q=${encodeURIComponent(query)}`, options: { method: 'GET' } }), parseResults: (json, query) => [{ id: query, text: query, marked: `<mark>${query}</mark> (Grid reference)`, point: [json.lon, json.lat], bounds: [json.minLon, json.minLat, json.maxLon, json.maxLat], type: 'gridref' }]}
searchPlugin({ customDatasets: [gridRefDataset]})CustomDataset properties
name
- Type:
string(required)
Unique identifier for the dataset. Included as the type property in the search:match event payload, which lets you distinguish between results from different datasets.
buildRequest
- Type:
(query: string) => SearchRequestConfig | Request
Builds the request for a query. If omitted, urlTemplate is used instead.
Return a { url, options } fetch config object (the URL and the options passed to fetch) or a Request. Use it when you need custom URL construction or fetch options. The plugin's transformRequest isn't applied to requests built here.
buildRequest: (query) => ({ url: `https://api.example.com/search?q=${encodeURIComponent(query)}`, options: { headers: { Accept: 'application/json' } }})urlTemplate
- Type:
string
URL template with a {query} placeholder. A simpler alternative to buildRequest for GET requests.
urlTemplate: 'https://api.example.com/search?q={query}'parseResults
- Type:
(json: any, query: string) => SearchSuggestion[](required)
Turns the parsed JSON response into suggestions. Return an empty array if there are no results. It receives the parsed JSON response and the original query string.
Each SearchSuggestion must have:
| Property | Type | Description |
|---|---|---|
id | string | Required. Unique identifier for the suggestion |
text | string | Required. Display text shown in the autocomplete list |
marked | string | Label text with query terms wrapped in <mark> tags. Any other markup is shown as text. If omitted, the suggestion label is blank |
point | [number, number] | Required. Centre coordinate for placing a marker |
bounds | [number, number, number, number] | Required. Bounding box to fit the map to when selected, as [minX, minY, maxX, maxY] |
type | string | Value included in the search:match payload to identify the source dataset |
Any additional properties on the suggestion object are passed through in the search:match event payload.
includeRegex
- Type:
RegExp
When set, the dataset is only queried when the input matches this pattern. Useful for datasets that only apply to specific input formats (e.g. grid references, parcel IDs).
excludeRegex
- Type:
RegExp
When set, the dataset is skipped when the input matches this pattern.
exclusive
- Type:
boolean
When true, if this dataset returns results no other datasets are queried. Useful for high-confidence lookups where you want to suppress the OS Names fallback.
Application mode
While the search form is open, the plugin sets the 'search' application mode, adding im-o-app--mode-search to the app root. It doesn't hide anything through the mode itself: search's own styles fade out the rest of the top row and side panels, keeping them in the tab order so Tab can move on from the form. You can still use the applicationModes option to hide extra items while search is open, e.g. { search: { exclude: ['myControl'] } }.
Methods
This plugin does not expose any public methods.
Events
Subscribe to events using interactiveMap.on().
search:match
Emitted when the user selects a search result.
- Payload:
The full suggestion object returned by the dataset's parseResults function, plus the original query string. At minimum:
{ query: 'NY7019', // The original search input id: '...', text: 'NY 701 924', marked: '<mark>NY 701 924</mark> (Grid reference)', point: [lng, lat], bounds: [west, south, east, north], type: 'gridref' // The dataset name, useful for distinguishing result types // ...any other properties returned by parseResults}interactiveMap.on('search:match', (event) => { if (event.type === 'parcel') { interactPlugin.selectFeature({ featureId: event.properties.id, layerId: 'parcels' }) }})search:clear
Emitted when the search input is cleared.
- Payload:
- None
interactiveMap.on('search:clear', () => { interactPlugin.unselectFeature({ featureId: selectedId })})search:open
Emitted when the open button is clicked to expand the search. Only applies when expanded is false, as that is the only case where an open button is rendered.
- Payload:
- None
search:close
Emitted when the search is dismissed — via the close button, a click outside the search, or (on mobile only) after a suggestion is selected or the form is submitted.
- Payload:
- None