Install Leaflet.Locate via npm
gh-pagesTo install the plugin for production use, use npm to add leaflet.locatecontrol to your project.
npm install leaflet.locatecontrolrepository·gh-pages·Indexed 21 days ago
https://github.com/domoritz/leaflet-locatecontrolA plugin for Leaflet and Mapbox.js (version 0.90.0) that provides a control to geolocate the user. It includes options for view behavior, visual customization of markers and accuracy circles, localization, and programmatic control via start(), stop(), and stopFollowing() methods. The control fires custom map events such as locateactivate, locatedeactivate, locatelocationfound, and locationtimeout to handle geolocation success, errors, or timeouts.
To install the plugin for production use, use npm to add leaflet.locatecontrol to your project.
npm install leaflet.locatecontrolIf you are using a module bundler or ESM, import LocateControl directly. Note that when using this method, you must use new LocateControl() instead of the L.control.locate() shorthand.
import { LocateControl } from "leaflet.locatecontrol";
import "leaflet.locatecontrol/dist/L.Control.Locate.min.css";
// Usage:
// const lc = new LocateControl().addTo(map);You can load the plugin directly from the JsDelivr CDN. Replace [VERSION] with the latest release number or remove it to always use the latest version.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol@[VERSION]/dist/L.Control.Locate.min.css" />
<script src="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol@[VERSION]/dist/L.Control.Locate.min.js" charset="utf-8"></script>You can customize the behavior and appearance of the control by passing an options object to L.control.locate(OPTIONS). The control inherits standard options from Leaflet Controls.
let lc = L.control
.locate({
position: "topright",
strings: {
title: "Show me where I am, yo!"
}
})
.addTo(map);To request high accuracy (GPS) from the browser, pass enableHighAccuracy: true within the locateOptions object.
map.addControl(
L.control.locate({
locateOptions: {
enableHighAccuracy: true
}
})
);You can control how the map zooms when a location is found using locateOptions and keepCurrentZoomLevel.
Set a maximum zoom level:
Use maxZoom inside locateOptions. This only applies if keepCurrentZoomLevel is false or if the current zoom is outside the specified range.
Restrict zoom range:
Use keepCurrentZoomLevel with an array [min, max] to only keep the current zoom level when it falls within that range. Outside that range, the map will zoom to the location.
// Example: Set max zoom to 10
map.addControl(
L.control.locate({
locateOptions: {
maxZoom: 10
}
})
);
// Example: Keep zoom only between levels 13 and 18, but cap at 16
map.addControl(
L.control.locate({
keepCurrentZoomLevel: [13, 18],
locateOptions: {
maxZoom: 16
}
})
);If you are using Safari with Leaflet 1.7.1, you may encounter a bug. The recommended workaround is to disable the tap option in your Leaflet map configuration.
let map = new L.Map('map', {
tap: false,
// ... other options
});After including the JavaScript and CSS files, initialize the control and add it to your Leaflet map instance using L.control.locate().addTo(map).
L.control.locate().addTo(map);You can customize the plugin's behavior by extending L.Control.Locate using L.extend. This allows you to override internal methods like _drawMarker or _removeMarker to change how the location marker is rendered.
Warning: Internal functions may change in future versions, which could break customizations.
L.Control.MyLocate = L.Control.Locate.extend({
_drawMarker: function () {
// override to customize the marker
}
});
let lc = new L.Control.MyLocate();You can programmatically control the location tracking by calling methods on the locate control instance. This is useful for setting the location automatically on page load or stopping tracking based on application logic.
start(): Requests a location update and sets the location.stop(): Stops the location tracking.stopFollowing(): Keeps the plugin active but stops the map from automatically zooming and panning to follow the location.// create control and add to map
let lc = L.control.locate().addTo(map);
// request location update and set location
lc.start();The locate control fires several events on the Leaflet map object. You can listen to these to react to geolocation success, errors, or timeouts.
| Event | Description |
|---|---|
locateactivate | Fired when the control is activated |
locatedeactivate | Fired when the control is deactivated |
locatelocationfound | Fired when a location is found. Includes latlng, accuracy, bounds, control, and other geolocation data |
locationtimeout | Fired when geolocation timeouts occur in watch mode |
One-shot behavior (get location once and stop):
map.on("locatelocationfound", function (e) {
console.log("Location found:", e.latlng);
console.log("Accuracy:", e.accuracy, "meters");
e.control.stop(); // Stop after first location
});Handling timeouts (useful for custom user feedback):
map.on("locationtimeout", function (e) {
console.log("Location timeout count:", e.count);
// Provide custom feedback or retry logic
});onLocationError callback (which shows a browser alert() by default) fires independently of the native Leaflet locationerror event. To suppress the default browser alert, you must override onLocationError.The LocateControl is configured via a LocateOptions object passed to its constructor. Key configuration categories include:
setView (options: false, "once", "always", "untilPan", "untilPanOrZoom"), flyTo (boolean), and initialZoomLevel.markerStyle, circleStyle, compassStyle, followMarkerStyle, and followCircleStyle (all accepting PathOptions or MarkerOptions).clickBehavior (options: inView, outOfView, inViewNotFollowing).strings object (title, text, metersUnit, feetUnit, popup, outsideMapBoundsMsg).locateOptions key.onLocationError, onLocationOutsideMapBounds, or createButtonCallback.const locateControl = L.control.locate({
setView: 'always',
followCircleStyle: { color: 'red' },
strings: {
title: 'Find my location'
}
});