Leaflet.Locate

repository·gh-pages·Indexed 21 days ago

https://github.com/domoritz/leaflet-locatecontrol

A 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.

Tokens
5K
Snippets
14
Records
16
Agent score
25%

What's inside leaflet.locatecontrol

  1. Import Leaflet.Locate in ESM or Bundlers

    gh-pages

    If 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);
  2. Include Leaflet.Locate via CDN

    gh-pages

    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>
  3. Configure maxZoom and keepCurrentZoomLevel

    gh-pages

    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
        }
      })
    );
  4. Extend the Locate control class

    gh-pages

    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();
  5. Control the locate control with start() and stop()

    gh-pages

    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();
  6. Handle location events on the map

    gh-pages

    The locate control fires several events on the Leaflet map object. You can listen to these to react to geolocation success, errors, or timeouts.

    Custom Map Events

    EventDescription
    locateactivateFired when the control is activated
    locatedeactivateFired when the control is deactivated
    locatelocationfoundFired when a location is found. Includes latlng, accuracy, bounds, control, and other geolocation data
    locationtimeoutFired when geolocation timeouts occur in watch mode

    Implementation Examples

    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
    });

    Note on Errors

    • The control's 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.
  7. Configure LocateControl options

    gh-pages

    The LocateControl is configured via a LocateOptions object passed to its constructor. Key configuration categories include:

    • View Behavior: Control how the map moves when location is found using setView (options: false, "once", "always", "untilPan", "untilPanOrZoom"), flyTo (boolean), and initialZoomLevel.
    • Visual Elements: Customize the appearance of the location marker, accuracy circle, and compass using markerStyle, circleStyle, compassStyle, followMarkerStyle, and followCircleStyle (all accepting PathOptions or MarkerOptions).
    • Click Behavior: Define what happens when the control is clicked using clickBehavior (options: inView, outOfView, inViewNotFollowing).
    • Localization: Customize UI text via the strings object (title, text, metersUnit, feetUnit, popup, outsideMapBoundsMsg).
    • Leaflet Integration: Pass native Leaflet location options through the locateOptions key.
    • Callbacks: Handle lifecycle events via onLocationError, onLocationOutsideMapBounds, or createButtonCallback.
    const locateControl = L.control.locate({
      setView: 'always',
      followCircleStyle: { color: 'red' },
      strings: {
        title: 'Find my location'
      }
    });