Playground: Geolocate Control

How to move the map to the visitor's own position.

Unlike the address search, locating the user needs no plugin and no server: browsers ship a Geolocation API, and MapLibre GL JS wraps it in a ready-made control.

map.addControl(new maplibregl.GeolocateControl());

That is the whole feature: a button in the corner of the map, a permission prompt when it is pressed, a dot at the user's position and a circle showing how accurate that position is. addControl() takes a second argument if you want the button somewhere other than 'top-right'.

Nothing happens before the button is clicked — the browser only asks for permission on a user gesture, and never shares a position the user has not agreed to.

Options

Reacting to the position

Keep a reference to the control and it will tell you what happens:

const geolocate = new maplibregl.GeolocateControl();
map.addControl(geolocate);

geolocate.on('geolocate', (event) => console.log(event.coords.latitude, event.coords.longitude));
geolocate.on('error', (event) => console.log('no position:', event.message));

geolocate carries the browser's GeolocationCoordinates, and error fires when the user declines or no position can be determined — the control then disables its button.

Important

Geolocation only works in a secure context: https:// or localhost. Over plain http:// the browser refuses, and the control hides its button. A map inside a cross-origin iframe needs <iframe allow="geolocation"> on top of that — the preview above works without it because it is served from the same origin as this page.