### Install Leaflet.Locatecontrol via npm Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Use npm to install the plugin for production environments. This command downloads the necessary files to your project. ```bash npm install leaflet.locatecontrol ``` -------------------------------- ### Run Demo Locally Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Start the development server to run the demo locally. The server is a native Node.js script and does not require external dependencies. Modern browsers treat localhost as a secure context, enabling the Geolocation API. ```bash npm start ``` -------------------------------- ### Handle Location Found Event Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md React to location updates by listening for the 'locatelocationfound' event. This example logs the location and accuracy, then stops the control after the first successful find. ```javascript map.on("locatelocationfound", function (e) { console.log("Location found:", e.latlng); console.log("Accuracy:", e.accuracy, "meters"); e.control.stop(); // Stop after first location ("one-shot" behavior) }); ``` -------------------------------- ### Start and Stop Locate Control Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Programmatically start or stop the locate control. Useful for setting the location on page load or controlling updates. ```javascript let lc = L.control.locate().addTo(map); // request location update and set location lc.start(); ``` -------------------------------- ### Add Locate Control to Map (Default) Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Initialize the locate control with default options and add it to the Leaflet map. This is the basic setup for the control. ```javascript L.control.locate().addTo(map); ``` -------------------------------- ### Import Leaflet.Locatecontrol with npm (UMD) Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Import the plugin and its styles when using npm with a bundler or UMD setup. Ensure Leaflet is also imported. ```typescript import "leaflet.locatecontrol"; // Import plugin import "leaflet.locatecontrol/dist/L.Control.Locate.min.css"; // Import styles import L from "leaflet"; // Import L from leaflet to start using the plugin ``` -------------------------------- ### Import Leaflet.Locatecontrol with npm (ESM) Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Import the LocateControl class and styles when using npm with an ESM setup. This allows for direct instantiation of LocateControl. ```typescript import { LocateControl } from "leaflet.locatecontrol"; import "leaflet.locatecontrol/dist/L.Control.Locate.min.css"; ``` -------------------------------- ### Add Text to LocateControl Button Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md This example demonstrates how to add descriptive text next to the location icon on the LocateControl button. ```javascript let lc = L.control .locate({ strings: { title: "Show me where I am, yo!", text: "Locate me" } }) .addTo(map); ``` -------------------------------- ### Login to NPM Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Log in to the npm registry. This is required before publishing a new version. ```bash npm login ``` -------------------------------- ### Generate Minified Files Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Build the project to generate minified JavaScript and CSS files. This command is used to prepare the distributable assets. ```bash npm run build ``` -------------------------------- ### Update Changelog Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Update the CHANGELOG.md file with changes for the new version and commit the changes. This is the first step in making a release. ```bash git commit -am "chore: update changelog" ``` -------------------------------- ### Add Locate Control to Map (Custom Options) Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Initialize the locate control with custom options by passing a configuration object. This allows for fine-tuning the control's behavior. ```javascript L.control.locate(OPTIONS).addTo(map); ``` -------------------------------- ### Initialize Leaflet Map and LocateControl Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/demo/test-timeout.html Sets up the Leaflet map and adds the LocateControl with a specific timeout for testing. Useful for simulating realistic GPS delays. ```javascript const map = L.map("map").setView(\[51.505, -0.09\], 13); L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: "© OpenStreetMap" }).addTo(map); const lc = L.control .locate({ locateOptions: { timeout: 5000, maximumAge: 0, enableHighAccuracy: false, watch: true }, strings: { title: "Show my location" } }) .addTo(map); ``` -------------------------------- ### Publish to NPM Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Publish the new version of the package to the npm registry. This command should only be run by core developers after all release steps are completed. ```bash npm publish ``` -------------------------------- ### Initialize Leaflet Map with Locate Control Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/demo/esm/leaflet2.html This snippet shows how to initialize a Leaflet map and add the LocateControl plugin. Ensure Leaflet and the LocateControl plugin are included in your project. ```javascript { "imports": { "leaflet": "https://cdn.jsdelivr.net/npm/leaflet@2.0.0-alpha.1/dist/leaflet-src.js" } } ``` -------------------------------- ### Include CSS and JS via CDN Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Link to the Leaflet.Locatecontrol CSS and JavaScript files from the JsDelivr CDN. Replace [VERSION] with the specific release number or omit it for the latest version. ```html ``` -------------------------------- ### Review Release Changes Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Review the changes that will be included in the release by examining the git log between the previous tag and the current HEAD. ```bash git log $(git describe --tags --abbrev=0 HEAD^)..HEAD --oneline ``` -------------------------------- ### Bump Patch Version Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Automatically bump the patch version in package.json, run lint, tests, and build, then stage the dist/ files. This is part of the release process. ```bash npm run bump:patch ``` -------------------------------- ### Bump Minor Version Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Automatically bump the minor version in package.json, run lint, tests, and build, then stage the dist/ files. This is part of the release process. ```bash npm run bump:minor ``` -------------------------------- ### Clone Repository for Development Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Clone the GitHub repository to work with the source code during development. This provides access to the src/ directory. ```bash git clone https://github.com/domoritz/leaflet-locatecontrol ``` -------------------------------- ### L.control.locate() Options Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md The L.control.locate() method accepts a single object argument where you can specify various options to customize the locate control. These options control aspects like return to previous bounds, caching, compass display, drawing accuracy circles and markers, styling, icon classes, text elements, padding, callbacks, unit preferences, and more. ```APIDOC ## L.control.locate() Options ### Description This section details the available options for customizing the Leaflet LocateControl. These options allow fine-grained control over the control's behavior, appearance, and interaction with the map and user location data. ### Options Table | Option Name | Type | Description | Default Value | |---|---|---|---| | `returnToPrevBounds` | `boolean` | If set, save the map bounds just before centering to the user's location. When control is disabled, set the view back to the bounds that were saved. | `false` | | `cacheLocation` | `boolean` | Keep a cache of the location after the user deactivates the control. If set to false, the user has to wait until the locate API returns a new location before they see where they are again. | `true` | | `showCompass` | `boolean` | Show the compass bearing on top of the location marker | `true` | | `compassAccuracyThreshold` | `number` or `false` | Maximum allowed iOS compass accuracy in degrees (`webkitCompassAccuracy`) for displaying the compass. `-1` (uncalibrated) is always rejected. Set to `false` to always show the compass when heading data is available. | `45` | | `drawCircle` | `boolean` | If set, a circle that shows the location accuracy is drawn. | `true` | | `drawMarker` | `boolean` | If set, the marker at the users' location is drawn. | `true` | | `markerClass` | `class` | The class to be used to create the marker. | `LocationMarker` | | `compassClass` | `class` | The class to be used to create the compass marker. | `CompassMarker` | | `circleStyle` | [`Path options`](https://leafletjs.com/reference.html#path) | Accuracy circle style properties. | see code | | `markerStyle` | [`Path options`](https://leafletjs.com/reference.html#path) | Inner marker style properties. Only works if your marker class supports `setStyle`. | see code | | `compassStyle` | [`Path options`](https://leafletjs.com/reference.html#path) | Triangle compass heading marker style properties. Only works if your marker class supports `setStyle`. | see code | | `followCircleStyle` | [`Path options`](https://leafletjs.com/reference.html#path) | Changes to the accuracy circle while following. Only need to provide changes. | `{}` | | `followMarkerStyle` | [`Path options`](https://leafletjs.com/reference.html#path) | Changes to the inner marker while following. Only need to provide changes. | `{}` | | `followCompassStyle` | [`Path options`](https://leafletjs.com/reference.html#path) | Changes to the compass marker while following. Only need to provide changes. | `{}` | | `icon` | `string` | The CSS class for the icon. | `leaflet-control-locate-location-arrow` | | `iconLoading` | `string` | The CSS class for the icon while loading. | `leaflet-control-locate-spinner` | | `iconElementTag` | `string` | The element to be created for icons. | `span` | | `textElementTag` | `string` | The element to be created for the text. | `small` | | `circlePadding` | `array` | Padding around the accuracy circle. | `[0, 0]` | | `createButtonCallback` | `function` | This callback can be used in case you would like to override button creation behavior. | see code | | `getLocationBounds` | `function` | This callback can be used to override the viewport tracking behavior. | see code | | `onLocationError` | `function` | Called on location errors. Receives the error and the control instance. | see code | | `metric` | `boolean` | Use metric units. | `true` | | `onLocationOutsideMapBounds` | `function` | Called when the user's location is outside the bounds set on the map. Called repeatedly when the user's location changes. | see code | | `showPopup` | `boolean` | Display a pop-up when the user clicks on the inner marker. | `true` | | `strings` | `object` | Strings used in the control. Options are `title`, `text`, `metersUnit`, `feetUnit`, `popup` and `outsideMapBoundsMsg` | see code | | `strings.popup` | `string` or `function` | The string shown as popup. May contain the placeholders `{distance}`, `{unit}`, `{lat}`, `{lng}`, `{altitude}`, `{speed}` (in m/s), and `{heading}` (in degrees). If this option is specified as function, it will be executed with a single parameter `{distance, unit, lat, lng, altitude, speed, heading}` and expected to return a string. | see code | | `locateOptions` | [`Locate options`](https://leafletjs.com/reference.html#locate-options) | The default options passed to Leaflet's locate method. | see code | ### Example Usage To customize the position and the title: ```js let lc = L.control.locate({ position: "topright", strings: { title: "Show me where I am, yo!" } }).addTo(map); ``` To add text next to the location icon: ```js let lc = L.control.locate({ strings: { title: "Show me where I am, yo!", text: "Locate me" } }).addTo(map); ``` ``` -------------------------------- ### Push Changes and Tags Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Push local commits and tags to the remote repository. This makes the new version available on GitHub. ```bash git push && git push --tags ``` -------------------------------- ### Extend Locate Control Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Customize the behavior of the locate control by extending its class and overriding methods like _drawMarker. Note that customizations may become incompatible with future updates. ```javascript L.Control.MyLocate = L.Control.Locate.extend({ _drawMarker: function () { // override to customize the marker } }); let lc = new L.Control.MyLocate(); ``` -------------------------------- ### Import Leaflet with ESM Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/demo/esm/index.html Import Leaflet using its ES Module distribution from a CDN. This is a prerequisite for using ESM-compatible plugins. ```javascript import "leaflet"; const map = L.map('map'); const locateControl = L.control.locate({ position: 'topleft', strings: { title: 'Show me where I am' } }).addTo(map); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap contributors' }).addTo(map); ``` -------------------------------- ### Fix Linting Issues Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Automatically fix code style and linting issues. This command should be run before submitting a Pull Request to ensure code compliance. ```bash npm run lint:fix ``` -------------------------------- ### Dark Mode Toggle Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/demo/test-timeout.html Implements a dark mode toggle that persists the user's preference in local storage. Ensures the UI adapts to user preferences. ```javascript const root = document.documentElement; const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; const savedTheme = localStorage.getItem("theme"); if (savedTheme) { root.setAttribute("data-theme", savedTheme); } else if (prefersDark) { root.setAttribute("data-theme", "dark"); } function getCurrentTheme() { const dataTheme = root.getAttribute("data-theme"); if (dataTheme) return dataTheme; return prefersDark ? "dark" : "light"; } function toggleDarkMode() { const currentTheme = getCurrentTheme(); const newTheme = currentTheme === "dark" ? "light" : "dark"; root.setAttribute("data-theme", newTheme); localStorage.setItem("theme", newTheme); document.getElementById("dark-mode-toggle").textContent = newTheme === "dark" ? "☀️ Light Mode" : "🌙 Dark Mode"; } if (getCurrentTheme() === "dark") { document.getElementById("dark-mode-toggle").textContent = "☀️ Light Mode"; } ``` -------------------------------- ### Simulate Poor GPS Signal Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/demo/test-timeout.html Overrides `navigator.geolocation.watchPosition` and `clearWatch` to simulate timeout errors. Useful for testing how the application handles unreliable location data. ```javascript const activeWatchers = new Map(); let callCount = 0; navigator.geolocation.watchPosition = function (success, error, options) { callCount++; const watchId = callCount; log(`watchPosition (#${watchId}) timeout: ${options.timeout}ms`, "info"); const intervalId = setInterval(() => { if (!activeWatchers.has(watchId)) { clearInterval(intervalId); return; } log(`Timeout triggered (Watch #${watchId})`, "warning"); error({ code: 3, message: "Timeout (simulated)", TIMEOUT: 3 }); }, options.timeout || 5000); activeWatchers.set(watchId, intervalId); return watchId; }; navigator.geolocation.clearWatch = function (watchId) { if (activeWatchers.has(watchId)) { clearInterval(activeWatchers.get(watchId)); activeWatchers.delete(watchId); log(`clearWatch (#${watchId})`, "info"); } }; ``` -------------------------------- ### Stop Following Location Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Keep the plugin active but stop following the user's location. This is useful for a one-time location acquisition. ```javascript lc.stopFollowing(); ``` -------------------------------- ### Handle Location Events Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/demo/test-timeout.html Registers event listeners for location found, errors, and timeouts. Essential for debugging and providing user feedback during location attempts. ```javascript map.on("locationfound", (e) => { log(`locationfound - ${e.latlng.lat.toFixed(5)}, ${e.latlng.lng.toFixed(5)}`, "success"); }); map.on("locationerror", (e) => { const errorTypes = { 1: "PERMISSION_DENIED", 2: "POSITION_UNAVAILABLE", 3: "TIMEOUT" }; log(`locationerror - Code ${e.code} (${errorTypes[e.code]}): ${e.message}`, "error"); }); map.on("locationtimeout", (e) => { log(`locationtimeout EVENT - Count: ${e.count}`, "event"); if (e.count >= 3 && !visualFeedbackActive) { visualFeedbackActive = true; log("Visual feedback active (orange spinner)", "warning"); } }); map.on("locateactivate", () => { log("locateactivate - Geolocation started", "info"); visualFeedbackActive = false; }); map.on("locatedeactivate", () => { log("locatedeactivate - Geolocation stopped", "warning"); }); ``` -------------------------------- ### Lint Code Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Check for code style and linting issues. This command helps maintain code quality and consistency before submitting a Pull Request. ```bash npm run lint ``` -------------------------------- ### Customize LocateControl Position and Title Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Use this snippet to set the control's position on the map and customize the tooltip text for the locate button. ```javascript let lc = L.control .locate({ position: "topright", strings: { title: "Show me where I am, yo!" } }) .addTo(map); ``` -------------------------------- ### Handle Location Timeout Event Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Respond to geolocation timeouts in watch mode by listening for the 'locationtimeout' event. This can be used to provide custom feedback or implement retry logic. ```javascript map.on("locationtimeout", function (e) { console.log("Location timeout count:", e.count); // Provide custom feedback or retry logic }); ``` -------------------------------- ### Set Maximum Zoom Level Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Configure the maximum zoom level when the locate control is activated using 'maxZoom' within 'locateOptions'. This option only applies when 'keepCurrentZoomLevel' is false or the current zoom is outside a specified range. ```javascript map.addControl( L.control.locate({ locateOptions: { maxZoom: 10 } }) ); ``` -------------------------------- ### Enable High Accuracy Mode Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Enable high accuracy (GPS) mode for geolocation by setting 'enableHighAccuracy' to true within 'locateOptions'. ```javascript map.addControl( L.control.locate({ locateOptions: { enableHighAccuracy: true } }) ); ``` -------------------------------- ### Listen to locationtimeout event Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/demo/test-timeout.html Listen to the 'locationtimeout' event to inform users about signal issues beyond the control's visual feedback. The event object includes the count of consecutive timeouts. ```javascript map.on('locationtimeout', (e) => alert(`GPS timeout ${e.count}`)); ``` -------------------------------- ### Keep Current Zoom Level within a Range Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Use 'keepCurrentZoomLevel' with a range to maintain the current zoom level only when it falls within the specified bounds. 'maxZoom' can still be set for cases outside this range. ```javascript map.addControl( L.control.locate({ keepCurrentZoomLevel: [13, 18], locateOptions: { maxZoom: 16 } }) ); ``` -------------------------------- ### Disable Tap for Safari Compatibility Source: https://github.com/domoritz/leaflet-locatecontrol/blob/gh-pages/README.md Workaround for a bug in Leaflet 1.7.1 affecting Safari. Disable tap interaction on the map by setting 'tap: false' in the L.Map options. ```javascript let map = new L.Map('map', { tap: false, ... }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.