MapSnippets logoMapSnippets logo

Show User Location on a Leaflet Map

Leaflet

Display the user's current GPS position on a Leaflet map using the browser Geolocation API with an accuracy circle.

progress_activityLoading map...
const map = L.map('map').setView([50.0755, 14.4378], 5);
L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
  tileSize: 256,
  attribution: '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
map.locate({ setView: true, maxZoom: 16 });
map.on('locationfound', (e) => {
  L.marker(e.latlng).addTo(map).bindPopup('You are here').openPopup();
  L.circle(e.latlng, { radius: e.accuracy, color: '#2196F3', fillOpacity: 0.15 }).addTo(map);
});
map.on('locationerror', (e) => {
  alert('Location access denied or unavailable.');
});

How it works

Leaflet’s map.locate() wraps the browser Geolocation API in a convenient method. Setting setView: true automatically pans the map to the detected position. The maxZoom option prevents zooming too close when accuracy is high.

The locationfound event fires with the coordinates and accuracy radius. A marker shows the user’s position, and a semi-transparent circle visualizes the accuracy range. The locationerror event handles cases where the user denies permission or geolocation is unavailable.

Key APIs

API Description Docs
map.locate() Request user location leafletjs.com/reference.html#map-locate
locationfound event Location success callback leafletjs.com/reference.html#map-locationfound
L.circle() Draw accuracy circle leafletjs.com/reference.html#circle

FAQ

Why does geolocation not work over HTTP?

Browsers require HTTPS for the Geolocation API. It works on localhost for development but requires a valid SSL certificate in production.

How do I track the user’s position continuously?

Pass { watch: true } to map.locate(). Call map.stopLocate() to stop tracking.

Common mistakes

  • Not handling the locationerror event: if the user denies permission, nothing happens and the map stays at the default view
  • Expecting high accuracy on desktop: GPS is typically only available on mobile devices; desktop uses IP-based geolocation
  • Calling map.locate() before the page is fully loaded: wrap it in a DOM ready event if needed
auto_awesome

Build maps using Leaflet with AI

Generate code like this show user location on a leaflet map example using the Leaflet skill in your IDE.