Geolocation Control in MapLibre GL JS
MapLibre GL JSShow the user's current position on the map using the built-in maplibregl.GeolocateControl with tracking support.
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets-v4/style.json?key=YOUR_MAPTILER_KEY',
center: [14.42, 50.08],
zoom: 12
});
map.addControl(new maplibregl.NavigationControl());
const geolocate = new maplibregl.GeolocateControl({
positionOptions: { enableHighAccuracy: true },
trackUserLocation: true,
showUserHeading: true
});
map.addControl(geolocate);
map.on('load', () => { geolocate.trigger(); });How it works
The GeolocateControl uses the browser’s Geolocation API to find the user’s position and display it as a pulsing dot on the map. Setting trackUserLocation: true keeps the dot updated as the user moves.
The showUserHeading option adds a directional indicator showing which way the device is facing, useful on mobile devices with a compass sensor.
Calling geolocate.trigger() after load automatically requests the user’s location without requiring a button click. The browser will prompt for location permission.
Key APIs
| API | Description | Docs |
|---|---|---|
maplibregl.GeolocateControl |
Built-in geolocation button | maplibre.org docs |
trackUserLocation |
Continuously update position | maplibre.org docs |
geolocate.trigger() |
Programmatically start tracking | maplibre.org docs |
FAQ
What happens if the user denies location permission?
The control shows an error state. Listen for the error event on the GeolocateControl to handle this gracefully.
Does this work on desktop?
Yes, but accuracy is lower (based on IP/WiFi). Mobile devices with GPS provide much more accurate positions.
Common mistakes
- Calling
geolocate.trigger()before the map loads: the control is not ready yet - Using geolocation on HTTP instead of HTTPS: browsers block geolocation on insecure origins
- Expecting immediate results: the first GPS fix can take several seconds
Build maps using MapLibre GL JS with AI
Generate code like this geolocation control in maplibre gl js example using the MapLibre GL JS skill in your IDE.
Related Examples
- Initialize a MapLibre GL JS Map
- Live GPS Tracking with MapLibre GL JS
- See how to do this in Leaflet, MapTiler SDK or OpenLayers