2 Copyright (c) 2016 Dominik Moritz
4 This file is part of the leaflet locate control. It is licensed under the MIT license.
5 You can find the project at: https://github.com/domoritz/leaflet-locatecontrol
7 (function (factory, window) {
8 // see https://github.com/Leaflet/Leaflet/blob/master/PLUGIN-GUIDE.md#module-loaders
9 // for details on how to structure a leaflet plugin.
11 // define an AMD module that relies on 'leaflet'
12 if (typeof define === 'function' && define.amd) {
13 define(['leaflet'], factory);
15 // define a Common JS module that relies on 'leaflet'
16 } else if (typeof exports === 'object') {
17 if (typeof window !== 'undefined' && window.L) {
18 module.exports = factory(L);
20 module.exports = factory(require('leaflet'));
24 // attach your plugin to the global 'L' variable
25 if (typeof window !== 'undefined' && window.L){
26 window.L.Control.Locate = factory(L);
29 var LDomUtilApplyClassesMethod = function(method, element, classNames) {
30 classNames = classNames.split(' ');
31 classNames.forEach(function(className) {
32 L.DomUtil[method].call(this, element, className);
36 var addClasses = function(el, names) { LDomUtilApplyClassesMethod('addClass', el, names); };
37 var removeClasses = function(el, names) { LDomUtilApplyClassesMethod('removeClass', el, names); };
40 * Compatible with L.Circle but a true marker instead of a path
42 var LocationMarker = L.Marker.extend({
43 initialize: function (latlng, options) {
44 L.Util.setOptions(this, options);
45 this._latlng = latlng;
50 * Create a styled circle location marker
52 createIcon: function() {
53 var opt = this.options;
57 if (opt.color !== undefined) {
58 style += 'stroke:'+opt.color+';';
60 if (opt.weight !== undefined) {
61 style += 'stroke-width:'+opt.weight+';';
63 if (opt.fillColor !== undefined) {
64 style += 'fill:'+opt.fillColor+';';
66 if (opt.fillOpacity !== undefined) {
67 style += 'fill-opacity:'+opt.fillOpacity+';';
69 if (opt.opacity !== undefined) {
70 style += 'opacity:'+opt.opacity+';';
73 var icon = this._getIconSVG(opt, style);
75 this._locationIcon = L.divIcon({
76 className: icon.className,
78 iconSize: [icon.w,icon.h],
81 this.setIcon(this._locationIcon);
85 * Return the raw svg for the shape
87 * Split so can be easily overridden
89 _getIconSVG: function(options, style) {
90 var r = options.radius;
91 var w = options.weight;
94 var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="'+s2+'" height="'+s2+'" version="1.1" viewBox="-'+s+' -'+s+' '+s2+' '+s2+'">' +
95 '<circle r="'+r+'" style="'+style+'" />' +
98 className: 'leaflet-control-locate-location',
105 setStyle: function(style) {
106 L.Util.setOptions(this, style);
111 var CompassMarker = LocationMarker.extend({
112 initialize: function (latlng, heading, options) {
113 L.Util.setOptions(this, options);
114 this._latlng = latlng;
115 this._heading = heading;
119 setHeading: function(heading) {
120 this._heading = heading;
124 * Create a styled arrow compass marker
126 _getIconSVG: function(options, style) {
127 var r = options.radius;
128 var w = (options.width + options.weight);
129 var h = (r+options.depth + options.weight)*2;
130 var path = 'M0,0 l'+(options.width/2)+','+options.depth+' l-'+(w)+',0 z';
131 var svgstyle = 'transform: rotate('+this._heading+'deg)';
132 var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="'+(w)+'" height="'+h+'" version="1.1" viewBox="-'+(w/2)+' 0 '+w+' '+h+'" style="'+svgstyle+'">'+
133 '<path d="'+path+'" style="'+style+'" />'+
136 className: 'leafet-control-locate-heading',
145 var LocateControl = L.Control.extend({
147 /** Position of the control */
149 /** The layer that the user's location should be drawn on. By default creates a new layer. */
152 * Automatically sets the map view (zoom and pan) to the user's location as it updates.
153 * While the map is following the user's location, the control is in the `following` state,
154 * which changes the style of the control and the circle marker.
157 * - false: never updates the map view when location changes.
158 * - 'once': set the view when the location is first determined
159 * - 'always': always updates the map view when location changes.
160 * The map view follows the user's location.
161 * - 'untilPan': like 'always', except stops updating the
162 * view if the user has manually panned the map.
163 * The map view follows the user's location until she pans.
164 * - 'untilPanOrZoom': (default) like 'always', except stops updating the
165 * view if the user has manually panned the map.
166 * The map view follows the user's location until she pans.
168 setView: 'untilPanOrZoom',
169 /** Keep the current map zoom level when setting the view and only pan. */
170 keepCurrentZoomLevel: false,
172 * This callback can be used to override the viewport tracking
173 * This function should return a LatLngBounds object.
175 * For example to extend the viewport to ensure that a particular LatLng is visible:
177 * getLocationBounds: function(locationEvent) {
178 * return locationEvent.bounds.extend([-33.873085, 151.219273]);
181 getLocationBounds: function (locationEvent) {
182 return locationEvent.bounds;
184 /** Smooth pan and zoom to the location of the marker. Only works in Leaflet 1.0+. */
187 * The user location can be inside and outside the current view when the user clicks on the
188 * control that is already active. Both cases can be configures separately.
189 * Possible values are:
190 * - 'setView': zoom and pan to the current location
191 * - 'stop': stop locating and remove the location marker
194 /** What should happen if the user clicks on the control while the location is within the current view. */
196 /** What should happen if the user clicks on the control while the location is outside the current view. */
197 outOfView: 'setView',
199 * What should happen if the user clicks on the control while the location is within the current view
200 * and we could be following but are not. Defaults to a special value which inherits from 'inView';
202 inViewNotFollowing: 'inView',
205 * If set, save the map bounds just before centering to the user's
206 * location. When control is disabled, set the view back to the
207 * bounds that were saved.
209 returnToPrevBounds: false,
211 * Keep a cache of the location after the user deactivates the control. If set to false, the user has to wait
212 * until the locate API returns a new location before they see where they are again.
215 /** If set, a circle that shows the location accuracy is drawn. */
217 /** If set, the marker at the users' location is drawn. */
219 /** If set and supported then show the compass heading */
221 /** The class to be used to create the marker. For example L.CircleMarker or L.Marker */
222 markerClass: LocationMarker,
223 /** The class us be used to create the compass bearing arrow */
224 compassClass: CompassMarker,
225 /** Accuracy circle style properties. NOTE these styles should match the css animations styles */
227 className: 'leaflet-control-locate-circle',
229 fillColor: '#136AEC',
233 /** Inner marker style properties. Only works if your marker class supports `setStyle`. */
235 className: 'leaflet-control-locate-marker',
237 fillColor: '#2A93EE',
245 fillColor: '#2A93EE',
250 radius: 9, // How far is the arrow is from the center of of the marker
251 width: 9, // Width of the arrow
252 depth: 6 // Length of the arrow
255 * Changes to accuracy circle and inner marker while following.
256 * It is only necessary to provide the properties that should change.
258 followCircleStyle: {},
261 // fillColor: '#FFB000'
263 followCompassStyle: {},
264 /** The CSS class for the icon. For example fa-location-arrow or fa-map-marker */
265 icon: 'fa fa-map-marker',
266 iconLoading: 'fa fa-spinner fa-spin',
267 /** The element to be created for icons. For example span or i */
268 iconElementTag: 'span',
269 /** Padding around the accuracy circle. */
270 circlePadding: [0, 0],
271 /** Use metric units. */
274 * This callback can be used in case you would like to override button creation behavior.
275 * This is useful for DOM manipulation frameworks such as angular etc.
276 * This function should return an object with HtmlElement for the button (link property) and the icon (icon property).
278 createButtonCallback: function (container, options) {
279 var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
280 link.title = options.strings.title;
281 var icon = L.DomUtil.create(options.iconElementTag, options.icon, link);
282 return { link: link, icon: icon };
284 /** This event is called in case of any location error that is not a time out error. */
285 onLocationError: function(err, control) {
289 * This event is called when the user's location is outside the bounds set on the map.
290 * The event is called repeatedly when the location changes.
292 onLocationOutsideMapBounds: function(control) {
294 alert(control.options.strings.outsideMapBoundsMsg);
296 /** Display a pop-up when the user click on the inner marker. */
299 title: "Show me where I am",
300 metersUnit: "meters",
302 popup: "You are within {distance} {unit} from this point",
303 outsideMapBoundsMsg: "You seem located outside the boundaries of the map"
305 /** The default options passed to leaflets locate method. */
308 watch: true, // if you overwrite this, visualization cannot be updated
309 setView: false // have to set this to false because we have to
310 // do setView manually
314 initialize: function (options) {
315 // set default options if nothing is set (merge one step deep)
316 for (var i in options) {
317 if (typeof this.options[i] === 'object') {
318 L.extend(this.options[i], options[i]);
320 this.options[i] = options[i];
324 // extend the follow marker style and circle from the normal style
325 this.options.followMarkerStyle = L.extend({}, this.options.markerStyle, this.options.followMarkerStyle);
326 this.options.followCircleStyle = L.extend({}, this.options.circleStyle, this.options.followCircleStyle);
327 this.options.followCompassStyle = L.extend({}, this.options.compassStyle, this.options.followCompassStyle);
331 * Add control to map. Returns the container for the control.
333 onAdd: function (map) {
334 var container = L.DomUtil.create('div',
335 'leaflet-control-locate leaflet-bar leaflet-control');
337 this._layer = this.options.layer || new L.LayerGroup();
338 this._layer.addTo(map);
339 this._event = undefined;
340 this._compassHeading = null;
341 this._prevBounds = null;
343 var linkAndIcon = this.options.createButtonCallback(container, this.options);
344 this._link = linkAndIcon.link;
345 this._icon = linkAndIcon.icon;
348 .on(this._link, 'click', L.DomEvent.stopPropagation)
349 .on(this._link, 'click', L.DomEvent.preventDefault)
350 .on(this._link, 'click', this._onClick, this)
351 .on(this._link, 'dblclick', L.DomEvent.stopPropagation);
353 this._resetVariables();
355 this._map.on('unload', this._unload, this);
361 * This method is called when the user clicks on the control.
363 _onClick: function() {
364 this._justClicked = true;
365 var wasFollowing = this._isFollowing();
366 this._userPanned = false;
367 this._userZoomed = false;
369 if (this._active && !this._event) {
370 // click while requesting
372 } else if (this._active && this._event !== undefined) {
373 var behaviors = this.options.clickBehavior;
374 var behavior = behaviors.outOfView;
375 if (this._map.getBounds().contains(this._event.latlng)) {
376 behavior = wasFollowing ? behaviors.inView : behaviors.inViewNotFollowing;
379 // Allow inheriting from another behavior
380 if (behaviors[behavior]) {
381 behavior = behaviors[behavior];
390 if (this.options.returnToPrevBounds) {
391 var f = this.options.flyTo ? this._map.flyToBounds : this._map.fitBounds;
392 f.bind(this._map)(this._prevBounds);
397 if (this.options.returnToPrevBounds) {
398 this._prevBounds = this._map.getBounds();
403 this._updateContainerStyle();
408 * - activates the engine
409 * - draws the marker (if coordinates available)
415 this._drawMarker(this._map);
417 // if we already have a location but the user clicked on the control
418 if (this.options.setView) {
422 this._updateContainerStyle();
427 * - deactivates the engine
428 * - reinitializes the button
429 * - removes the marker
434 this._cleanClasses();
435 this._resetVariables();
437 this._removeMarker();
441 * Keep the control active but stop following the location
443 stopFollowing: function() {
444 this._userPanned = true;
445 this._updateContainerStyle();
450 * This method launches the location engine.
451 * It is called before the marker is updated,
452 * event if it does not mean that the event will be ready.
454 * Override it if you want to add more functionalities.
455 * It should set the this._active to true and do nothing if
456 * this._active is true.
458 _activate: function() {
460 this._map.locate(this.options.locateOptions);
463 // bind event listeners
464 this._map.on('locationfound', this._onLocationFound, this);
465 this._map.on('locationerror', this._onLocationError, this);
466 this._map.on('dragstart', this._onDrag, this);
467 this._map.on('zoomstart', this._onZoom, this);
468 this._map.on('zoomend', this._onZoomEnd, this);
469 if (this.options.showCompass) {
470 if ('ondeviceorientationabsolute' in window) {
471 L.DomEvent.on(window, 'deviceorientationabsolute', this._onDeviceOrientation, this);
472 } else if ('ondeviceorientation' in window) {
473 L.DomEvent.on(window, 'deviceorientation', this._onDeviceOrientation, this);
480 * Called to stop the location engine.
482 * Override it to shutdown any functionalities you added on start.
484 _deactivate: function() {
485 this._map.stopLocate();
486 this._active = false;
488 if (!this.options.cacheLocation) {
489 this._event = undefined;
492 // unbind event listeners
493 this._map.off('locationfound', this._onLocationFound, this);
494 this._map.off('locationerror', this._onLocationError, this);
495 this._map.off('dragstart', this._onDrag, this);
496 this._map.off('zoomstart', this._onZoom, this);
497 this._map.off('zoomend', this._onZoomEnd, this);
498 if (this.options.showCompass) {
499 this._compassHeading = null;
500 if ('ondeviceorientationabsolute' in window) {
501 L.DomEvent.off(window, 'deviceorientationabsolute', this._onDeviceOrientation, this);
502 } else if ('ondeviceorientation' in window) {
503 L.DomEvent.off(window, 'deviceorientation', this._onDeviceOrientation, this);
509 * Zoom (unless we should keep the zoom level) and an to the current view.
511 setView: function() {
513 if (this._isOutsideMapBounds()) {
514 this._event = undefined; // clear the current location so we can get back into the bounds
515 this.options.onLocationOutsideMapBounds(this);
517 if (this.options.keepCurrentZoomLevel) {
518 var f = this.options.flyTo ? this._map.flyTo : this._map.panTo;
519 f.bind(this._map)([this._event.latitude, this._event.longitude]);
521 var f = this.options.flyTo ? this._map.flyToBounds : this._map.fitBounds;
522 // Ignore zoom events while setting the viewport as these would stop following
523 this._ignoreEvent = true;
524 f.bind(this._map)(this.options.getLocationBounds(this._event), {
525 padding: this.options.circlePadding,
526 maxZoom: this.options.locateOptions.maxZoom
528 L.Util.requestAnimFrame(function(){
529 // Wait until after the next animFrame because the flyTo can be async
530 this._ignoreEvent = false;
540 _drawCompass: function() {
541 var latlng = this._event.latlng;
543 if (this.options.showCompass && latlng && this._compassHeading !== null) {
544 var cStyle = this._isFollowing() ? this.options.followCompassStyle : this.options.compassStyle;
545 if (!this._compass) {
546 this._compass = new this.options.compassClass(latlng, this._compassHeading, cStyle).addTo(this._layer);
548 this._compass.setLatLng(latlng);
549 this._compass.setHeading(this._compassHeading);
550 // If the compassClass can be updated with setStyle, update it.
551 if (this._compass.setStyle) {
552 this._compass.setStyle(cStyle);
557 if (this._compass && (!this.options.showCompass || this._compassHeading === null)) {
558 this._compass.removeFrom(this._layer);
559 this._compass = null;
564 * Draw the marker and accuracy circle on the map.
566 * Uses the event retrieved from onLocationFound from the map.
568 _drawMarker: function() {
569 if (this._event.accuracy === undefined) {
570 this._event.accuracy = 0;
573 var radius = this._event.accuracy;
574 var latlng = this._event.latlng;
576 // circle with the radius of the location's accuracy
577 if (this.options.drawCircle) {
578 var style = this._isFollowing() ? this.options.followCircleStyle : this.options.circleStyle;
581 this._circle = L.circle(latlng, radius, style).addTo(this._layer);
583 this._circle.setLatLng(latlng).setRadius(radius).setStyle(style);
588 if (this.options.metric) {
589 distance = radius.toFixed(0);
590 unit = this.options.strings.metersUnit;
592 distance = (radius * 3.2808399).toFixed(0);
593 unit = this.options.strings.feetUnit;
596 // small inner marker
597 if (this.options.drawMarker) {
598 var mStyle = this._isFollowing() ? this.options.followMarkerStyle : this.options.markerStyle;
600 this._marker = new this.options.markerClass(latlng, mStyle).addTo(this._layer);
602 this._marker.setLatLng(latlng);
603 // If the markerClass can be updated with setStyle, update it.
604 if (this._marker.setStyle) {
605 this._marker.setStyle(mStyle);
612 var t = this.options.strings.popup;
613 if (this.options.showPopup && t && this._marker) {
615 .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
616 ._popup.setLatLng(latlng);
618 if (this.options.showPopup && t && this._compass) {
620 .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
621 ._popup.setLatLng(latlng);
626 * Remove the marker from map.
628 _removeMarker: function() {
629 this._layer.clearLayers();
630 this._marker = undefined;
631 this._circle = undefined;
635 * Unload the plugin and all event listeners.
636 * Kind of the opposite of onAdd.
638 _unload: function() {
640 this._map.off('unload', this._unload, this);
644 * Sets the compass heading
646 _setCompassHeading: function(angle) {
647 if (!isNaN(parseFloat(angle)) && isFinite(angle)) {
648 angle = Math.round(angle);
650 this._compassHeading = angle;
651 L.Util.requestAnimFrame(this._drawCompass, this);
653 this._compassHeading = null;
658 * If the compass fails calibration just fail safely and remove the compass
660 _onCompassNeedsCalibration: function() {
661 this._setCompassHeading();
665 * Process and normalise compass events
667 _onDeviceOrientation: function(e) {
672 if (e.webkitCompassHeading) {
674 this._setCompassHeading(e.webkitCompassHeading);
675 } else if (e.absolute && e.alpha) {
677 this._setCompassHeading(360 - e.alpha)
682 * Calls deactivate and dispatches an error.
684 _onLocationError: function(err) {
685 // ignore time out error if the location is watched
686 if (err.code == 3 && this.options.locateOptions.watch) {
691 this.options.onLocationError(err, this);
695 * Stores the received event and updates the marker.
697 _onLocationFound: function(e) {
698 // no need to do anything if the location has not changed
700 (this._event.latlng.lat === e.latlng.lat &&
701 this._event.latlng.lng === e.latlng.lng &&
702 this._event.accuracy === e.accuracy)) {
707 // we may have a stray event
714 this._updateContainerStyle();
716 switch (this.options.setView) {
718 if (this._justClicked) {
723 if (!this._userPanned) {
727 case 'untilPanOrZoom':
728 if (!this._userPanned && !this._userZoomed) {
736 // don't set the view
740 this._justClicked = false;
744 * When the user drags. Need a separate event so we can bind and unbind event listeners.
746 _onDrag: function() {
747 // only react to drags once we have a location
748 if (this._event && !this._ignoreEvent) {
749 this._userPanned = true;
750 this._updateContainerStyle();
756 * When the user zooms. Need a separate event so we can bind and unbind event listeners.
758 _onZoom: function() {
759 // only react to drags once we have a location
760 if (this._event && !this._ignoreEvent) {
761 this._userZoomed = true;
762 this._updateContainerStyle();
768 * After a zoom ends update the compass and handle sideways zooms
770 _onZoomEnd: function() {
775 if (this._event && !this._ignoreEvent) {
776 // If we have zoomed in and out and ended up sideways treat it as a pan
777 if (!this._map.getBounds().pad(-.3).contains(this._marker.getLatLng())) {
778 this._userPanned = true;
779 this._updateContainerStyle();
786 * Compute whether the map is following the user location with pan and zoom.
788 _isFollowing: function() {
793 if (this.options.setView === 'always') {
795 } else if (this.options.setView === 'untilPan') {
796 return !this._userPanned;
797 } else if (this.options.setView === 'untilPanOrZoom') {
798 return !this._userPanned && !this._userZoomed;
803 * Check if location is in map bounds
805 _isOutsideMapBounds: function() {
806 if (this._event === undefined) {
809 return this._map.options.maxBounds &&
810 !this._map.options.maxBounds.contains(this._event.latlng);
814 * Toggles button class between following and active.
816 _updateContainerStyle: function() {
817 if (!this._container) {
821 if (this._active && !this._event) {
822 // active but don't have a location yet
823 this._setClasses('requesting');
824 } else if (this._isFollowing()) {
825 this._setClasses('following');
826 } else if (this._active) {
827 this._setClasses('active');
829 this._cleanClasses();
834 * Sets the CSS classes for the state.
836 _setClasses: function(state) {
837 if (state == 'requesting') {
838 removeClasses(this._container, "active following");
839 addClasses(this._container, "requesting");
841 removeClasses(this._icon, this.options.icon);
842 addClasses(this._icon, this.options.iconLoading);
843 } else if (state == 'active') {
844 removeClasses(this._container, "requesting following");
845 addClasses(this._container, "active");
847 removeClasses(this._icon, this.options.iconLoading);
848 addClasses(this._icon, this.options.icon);
849 } else if (state == 'following') {
850 removeClasses(this._container, "requesting");
851 addClasses(this._container, "active following");
853 removeClasses(this._icon, this.options.iconLoading);
854 addClasses(this._icon, this.options.icon);
859 * Removes all classes from button.
861 _cleanClasses: function() {
862 L.DomUtil.removeClass(this._container, "requesting");
863 L.DomUtil.removeClass(this._container, "active");
864 L.DomUtil.removeClass(this._container, "following");
866 removeClasses(this._icon, this.options.iconLoading);
867 addClasses(this._icon, this.options.icon);
871 * Reinitializes state variables.
873 _resetVariables: function() {
874 // whether locate is active or not
875 this._active = false;
877 // true if the control was clicked for the first time
878 // we need this so we can pan and zoom once we have the location
879 this._justClicked = false;
881 // true if the user has panned the map after clicking the control
882 this._userPanned = false;
884 // true if the user has zoomed the map after clicking the control
885 this._userZoomed = false;
889 L.control.locate = function (options) {
890 return new L.Control.Locate(options);
893 return LocateControl;