• Stars
    star
    732
  • Rank 61,915 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A leaflet control to geolocate the user.

Leaflet.Locate

npm version jsDelivr Hits

A useful control to geolocate the user with many options. Official Leaflet and MapBox plugin.

Tested with Leaflet 1.9.2 and Mapbox.js 3.3.1 in Firefox, Chrome and Safari.

Please check for breaking changes in the changelog.

Demo

Basic Usage

Set up:

tl;dr

  1. Get CSS and JavaScript files
  2. Include CSS and JavaScript files
  3. Initialize plugin

Download JavaScript and CSS files

For testing purposes and development, you can use the latest version directly from my repository.

For production environments, use Bower and run bower install leaflet.locatecontrol or download the files from this repository. Bower will always download the latest version and keep the code up to date. The original JS and CSS files are in \src and the minified versions suitable for production are in \dist.

You can also get the latest version of the plugin with npm. This plugin is available in the npm repository. Just run npm install leaflet.locatecontrol.

The control is available from JsDelivr CDN. If you don't need the latest version, you can use the mapbox CDN.

Add the JavaScript and CSS files

Then include the CSS and JavaScript files. In this example, we are loading the files from the JsDelivr CDN. In the URLs below, replace [VERSION] with the latest release number or remove @[VERSION] 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>

Add the following snippet to your map initialization:

This snippet adds the control to the map. You can pass also pass a configuration.

L.control.locate().addTo(map);

Possible options

The locate controls inherits options from Leaflet Controls.

To customize the control, pass an object with your custom options to the locate control.

L.control.locate(OPTIONS).addTo(map);

Possible options are listed in the following table. More details are in the code.

Option Type Description Default
position string Position of the control topleft
layer ILayer The layer that the user's location should be drawn on. a new layer
setView boolean or string Set the map view (zoom and pan) to the user's location as it updates. Options are false, 'once', 'always', 'untilPan', or 'untilPanOrZoom' 'untilPanOrZoom'
flyTo boolean Smooth pan and zoom to the location of the marker. Only works in Leaflet 1.0+. false
keepCurrentZoomLevel boolean Only pan when setting the view. false
initialZoomLevel false or integer After activating the plugin by clicking on the icon, zoom to the selected zoom level, even when keepCurrentZoomLevel is true. Set to false to disable this feature. false
clickBehavior object What to do when the user clicks on the control. Has three options inView, inViewNotFollowing and outOfView. Possible values are stop and setView, or the name of a behaviour to inherit from. {inView: 'stop', outOfView: 'setView', inViewNotFollowing: 'inView'}
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
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 marker. CompassMarker
circleStyle Path options Accuracy circle style properties. see code
markerStyle Path options Inner marker style properties. Only works if your marker class supports setStyle. see code
compassStyle Path options Triangle compass heading marker style properties. Only works if your marker class supports setStyle. see code
followCircleStyle Path options Changes to the accuracy circle while following. Only need to provide changes. {}
followMarkerStyle Path options Changes to the inner marker while following. Only need to provide changes. {}
followCompassStyle Path options 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
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 This even is called when the user's location is outside the bounds set on the map. 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 click 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} and {unit}. If this option is specified as function, it will be executed with a single parameter {distance, unit} and expected to return a string. see code
locateOptions Locate options The default options passed to leaflets locate method. see code

For example, to customize the position and the title, you could write

var lc = L.control
  .locate({
    position: "topright",
    strings: {
      title: "Show me where I am, yo!"
    }
  })
  .addTo(map);

Screenshot

screenshot

Users

Sites that use this locate control:

Advanced Usage

Methods

You can call start() or stop() on the locate control object to set the location on page load for example.

// create control and add to map
var lc = L.control.locate().addTo(map);

// request location update and set location
lc.start();

You can keep the plugin active but stop following using lc.stopFollowing().

Events

You can leverage the native Leaflet events locationfound and locationerror to handle when geolocation is successful or produces an error. You can find out more about these events in the Leaflet documentation.

Additionally, the locate control fires locateactivate and locatedeactivate events on the map object when it is activated and deactivated, respectively.

Extending

To customize the behavior of the plugin, use L.extend to override start, stop, _drawMarker and/or _removeMarker. Please be aware that functions may change and customizations become incompatible.

L.Control.MyLocate = L.Control.Locate.extend({
  _drawMarker: function () {
    // override to customize the marker
  }
});

var lc = new L.Control.MyLocate();

FAQ

How do I set the maximum zoom level?

Set the maxZoom in locateOptions (keepCurrentZoomLevel must not be set to true).

map.addControl(
  L.control.locate({
    locateOptions: {
      maxZoom: 10
    }
  })
);

How do I enable high accuracy?

To enable high accuracy (GPS) mode, set the enableHighAccuracy in locateOptions.

map.addControl(
  L.control.locate({
    locateOptions: {
      enableHighAccuracy: true
    }
  })
);

Safari does not work with Leaflet 1.7.1

This is a bug in Leaflet. Disable tap to fix it for now. See this issue for details.

let map = new L.Map('map', {
    tap: false,
    ...
});

Developers

Run the demo locally with yarn start or npm run start and then open localhost:9000/demo/index.html.

To generate the minified JS and CSS files, use grunt and run grunt. However, don't include new minified files or a new version as part of a pull request. If you need SASS, install it with brew install sass/sass/sass.

Prettify and linting

Before a Pull Request please check the code style.

Run npm run lint to check if there are code style or linting issues.

Run npm run:fix to automatically fix style and linting issues.

Making a release (only core developer)

A new version is released with npm run bump:minor. Then push the new code with git push && git push --tags and publish to npm with npm publish.

Terms

  • active: After we called map.locate() and before map.stopLocate(). Any time, the map can fire the locationfound or locationerror events.
  • following: Following refers to whether the map zooms and pans automatically when a new location is found.

Thanks

To all contributors and issue reporters.

License

MIT

SVG icons from Font Awesome v5.15.4: Creative Commons Attribution 4.0

More Repositories

1

leaflet-maskcanvas

A leaflet canvas layer for displaying large coverage data sets
JavaScript
196
star
2

arrow-tools

A collection of handy CLI tools to convert CSV and JSON to Apache Arrow and Parquet
Rust
151
star
3

streamlit-vega-lite

A Streamlit component to render interactive Vega, Vega-Lite, and Altair visualizations and access the selected data from Python
Python
90
star
4

csv2parquet

Convert CSV files to Apache Parquet.
Rust
72
star
5

arrow-wasm

Apache Arrow in WebAssembly
Rust
65
star
6

himawari-8-chrome

๐Ÿ›ฐ Experience the latest image from the Himawari, GOES, Meteosat, and DSCOVR satellites
TypeScript
56
star
7

json2parquet

Convert JSON files to Apache Parquet.
Rust
43
star
8

gameoflife-python

Conway's Game of Life in an infinite space implemented in Python
Python
41
star
9

open-mensa-android

Android OpenMensa Client, shows the meals for university canteens
Kotlin
40
star
10

label_generator

Training data generator for text detection
Python
38
star
11

clingo-wasm

Clingo on the web
TypeScript
32
star
12

streamlit-docker

Python
30
star
13

line-density

Fast heatmaps for massive time series.
TypeScript
29
star
14

domoritz.github.io

My homepage
JavaScript
22
star
15

json2arrow

Convert JSON files to Apache Arrow.
Rust
20
star
16

vbb-coverage

Visualization of the VBB data from http://daten.berlin.de/datensaetze/vbb-fahrplan2012
JavaScript
16
star
17

csv2arrow

Convert CSV files to Apache Arrow.
Rust
15
star
18

shorty

A minimal Python script to shorten DOIs in bibtex files
TeX
13
star
19

parquet-wasm

Rust
9
star
20

live-bus-seattle

Live bus map for seattle
JavaScript
9
star
21

D3-App-Template

A template for an interactive web application with D3
TypeScript
8
star
22

wasm-clingo

Clingo compiled for the web
HTML
7
star
23

S76D

Singing Very High Speed Integrated Circuit Hardware Description Language Board
VHDL
7
star
24

backbone-eventdata

This small backbone plugin allows you to pass eventData to your actions
JavaScript
6
star
25

random-csv

Generate a random CSV file
Python
6
star
26

breakfast

Friday breakfast
JavaScript
6
star
27

line-density-rust

Compute the density of time series with normalization
Rust
5
star
28

gameoflife-rust

Conway's Game of Life in an infinite space implemented in rust
Rust
4
star
29

SoSAT

SAT solver
Python
4
star
30

drummy

A drum recording software written in Qt/C++
C++
4
star
31

mosaic-motherduck

JavaScript
4
star
32

tvcg-journal-typst

A Typst template for TVCG journals
Typst
3
star
33

vis-csp

Visualization constraints with Answer Set Programming
Python
3
star
34

vis-grammar

A Visualization Grammar
TypeScript
3
star
35

summarization-go

Summarizing as I go
Go
3
star
36

seattlebusheatmap

Seattle bus concentration as heatmap
JavaScript
3
star
37

streamlit-vega-lite-demo

Demo for domoritz/streamlit-vega-lite.
Python
3
star
38

tree

Arduino Christmas Tree
C++
2
star
39

gameoflife-csharp

Conway's Game of Life in an infinite space implemented in C#
C#
2
star
40

vis-examples

Example visualizations in Vega and Vega-Lite
JavaScript
2
star
41

CSE512-reports

Reports for CSE 512
TeX
1
star
42

gameoflife-deno

TypeScript
1
star
43

assign-projects

Logic ASP program to calculate optimal placement of students in projects depending on a per student ranking.
Python
1
star
44

rust-alloc-test

JavaScript
1
star
45

gameoflife-go

Conway's Game of Life in an infinite space implemented in Golang
Go
1
star
46

informaticup-2012

Unser Beitrag zum Informaticup 2012
Python
1
star
47

Mensa-App

Android Apllication to get the canteen menu at the University of Potsdam.
Java
1
star
48

Professors

A Professors repository built on top of PopIt
JavaScript
1
star
49

vis-constraints

Vega-Lite and Compassql as constraints
TypeScript
1
star