MapLibre geocoder
Add an address search box with autocomplete to a MapLibre GL JS map. Our @opengeocoding/maplibre-gl-geocoder package (source, MIT) connects the official MapLibre GL Geocoder control to OpenGeocoding.
| The visitor… | Endpoint | Credits |
|---|---|---|
| types; suggestions appear | /v1/autocomplete | free |
| picks a suggestion | /v1/retrieve | 1 |
| presses Enter without picking | /v1/search | 1 |
types coordinates such as 55.68, 12.57 | /v1/reverse | 1 |
1. Create a browser key
In the dashboard, create a browser key and list the origins of the pages that show the map, such as https://www.example.com or http://localhost:5173 for development. The key is visible in your page’s source; it only works from the listed origins. Never put a secret server key in browser code. See browser keys.
2. Install
npm install maplibre-gl @maplibre/maplibre-gl-geocoder @opengeocoding/maplibre-gl-geocoder 3. Add the control
import maplibregl from 'maplibre-gl';
import MaplibreGeocoder from '@maplibre/maplibre-gl-geocoder';
import { createGeocoderApi } from '@opengeocoding/maplibre-gl-geocoder';
import 'maplibre-gl/dist/maplibre-gl.css';
import '@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css';
const map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [12.57, 55.68],
zoom: 11,
attributionControl: {
customAttribution:
'Search data © <a href="https://opengeocoding.com/legal/attributions">OpenStreetMap contributors and others</a>'
}
});
map.addControl(
new MaplibreGeocoder(createGeocoderApi({ apiKey: 'og_your_browser_key' }), {
maplibregl,
showResultsWhileTyping: true,
reverseGeocode: true
}),
'top-left'
); showResultsWhileTyping: true is required: without it, the control only searches when the visitor presses Enter, and autocomplete never runs. The control follows the map view, so suggestions near the visible area rank higher once the map is zoomed in past level 9. Pass countries: 'dk' to limit suggestions to one country.
Notes
- Suggestions carry an ID and a label, never coordinates. Coordinates come from
/v1/retrievewhen a suggestion is picked, which is why only the pick costs a credit. - Errors such as an exhausted credit balance or an origin missing from the key show as the control’s error message. The errors page lists the codes.
- Show the data credits wherever you display results. The
customAttributionline above links to the full list.