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: 'leafet-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,
171 /** Smooth pan and zoom to the location of the marker. Only works in Leaflet 1.0+. */
174 * The user location can be inside and outside the current view when the user clicks on the
175 * control that is already active. Both cases can be configures separately.
176 * Possible values are:
177 * - 'setView': zoom and pan to the current location
178 * - 'stop': stop locating and remove the location marker
181 /** What should happen if the user clicks on the control while the location is within the current view. */
183 /** What should happen if the user clicks on the control while the location is outside the current view. */
184 outOfView: 'setView',
187 * If set, save the map bounds just before centering to the user's
188 * location. When control is disabled, set the view back to the
189 * bounds that were saved.
191 returnToPrevBounds: false,
193 * Keep a cache of the location after the user deactivates the control. If set to false, the user has to wait
194 * until the locate API returns a new location before they see where they are again.
197 /** If set, a circle that shows the location accuracy is drawn. */
199 /** If set, the marker at the users' location is drawn. */
201 /** If set and supported then show the compass heading */
203 /** The class to be used to create the marker. For example L.CircleMarker or L.Marker */
204 markerClass: LocationMarker,
205 /** The class us be used to create the compass bearing arrow */
206 compassClass: CompassMarker,
207 /** Accuracy circle style properties. NOTE these styles should match the css animations styles */
209 className: 'leaflet-control-locate-circle',
211 fillColor: '#136AEC',
215 /** Inner marker style properties. Only works if your marker class supports `setStyle`. */
217 className: 'leaflet-control-locate-marker',
219 fillColor: '#2A93EE',
227 fillColor: '#2A93EE',
232 radius: 9, // How far is the arrow is from the center of of the marker
233 width: 9, // Width of the arrow
234 depth: 6 // Length of the arrow
237 * Changes to accuracy circle and inner marker while following.
238 * It is only necessary to provide the properties that should change.
240 followCircleStyle: {},
243 // fillColor: '#FFB000'
245 followCompassStyle: {},
246 /** The CSS class for the icon. For example fa-location-arrow or fa-map-marker */
247 icon: 'fa fa-map-marker',
248 iconLoading: 'fa fa-spinner fa-spin',
249 /** The element to be created for icons. For example span or i */
250 iconElementTag: 'span',
251 /** Padding around the accuracy circle. */
252 circlePadding: [0, 0],
253 /** Use metric units. */
256 * This callback can be used in case you would like to override button creation behavior.
257 * This is useful for DOM manipulation frameworks such as angular etc.
258 * This function should return an object with HtmlElement for the button (link property) and the icon (icon property).
260 createButtonCallback: function (container, options) {
261 var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
262 link.title = options.strings.title;
263 var icon = L.DomUtil.create(options.iconElementTag, options.icon, link);
264 return { link: link, icon: icon };
266 /** This event is called in case of any location error that is not a time out error. */
267 onLocationError: function(err, control) {
271 * This event is called when the user's location is outside the bounds set on the map.
272 * The event is called repeatedly when the location changes.
274 onLocationOutsideMapBounds: function(control) {
276 alert(control.options.strings.outsideMapBoundsMsg);
278 /** Display a pop-up when the user click on the inner marker. */
281 title: "Show me where I am",
282 metersUnit: "meters",
284 popup: "You are within {distance} {unit} from this point",
285 outsideMapBoundsMsg: "You seem located outside the boundaries of the map"
287 /** The default options passed to leaflets locate method. */
290 watch: true, // if you overwrite this, visualization cannot be updated
291 setView: false // have to set this to false because we have to
292 // do setView manually
296 initialize: function (options) {
297 // set default options if nothing is set (merge one step deep)
298 for (var i in options) {
299 if (typeof this.options[i] === 'object') {
300 L.extend(this.options[i], options[i]);
302 this.options[i] = options[i];
306 // extend the follow marker style and circle from the normal style
307 this.options.followMarkerStyle = L.extend({}, this.options.markerStyle, this.options.followMarkerStyle);
308 this.options.followCircleStyle = L.extend({}, this.options.circleStyle, this.options.followCircleStyle);
309 this.options.followCompassStyle = L.extend({}, this.options.compassStyle, this.options.followCompassStyle);
313 * Add control to map. Returns the container for the control.
315 onAdd: function (map) {
316 var container = L.DomUtil.create('div',
317 'leaflet-control-locate leaflet-bar leaflet-control');
319 this._layer = this.options.layer || new L.LayerGroup();
320 this._layer.addTo(map);
321 this._event = undefined;
322 this._compassHeading = null;
323 this._prevBounds = null;
325 var linkAndIcon = this.options.createButtonCallback(container, this.options);
326 this._link = linkAndIcon.link;
327 this._icon = linkAndIcon.icon;
330 .on(this._link, 'click', L.DomEvent.stopPropagation)
331 .on(this._link, 'click', L.DomEvent.preventDefault)
332 .on(this._link, 'click', this._onClick, this)
333 .on(this._link, 'dblclick', L.DomEvent.stopPropagation);
335 this._resetVariables();
337 this._map.on('unload', this._unload, this);
343 * This method is called when the user clicks on the control.
345 _onClick: function() {
346 this._justClicked = true;
347 this._userPanned = false;
348 this._userZoomed = false;
350 if (this._active && !this._event) {
351 // click while requesting
353 } else if (this._active && this._event !== undefined) {
354 var behavior = this._map.getBounds().contains(this._event.latlng) ?
355 this.options.clickBehavior.inView : this.options.clickBehavior.outOfView;
362 if (this.options.returnToPrevBounds) {
363 var f = this.options.flyTo ? this._map.flyToBounds : this._map.fitBounds;
364 f.bind(this._map)(this._prevBounds);
369 if (this.options.returnToPrevBounds) {
370 this._prevBounds = this._map.getBounds();
375 this._updateContainerStyle();
380 * - activates the engine
381 * - draws the marker (if coordinates available)
387 this._drawMarker(this._map);
389 // if we already have a location but the user clicked on the control
390 if (this.options.setView) {
394 this._updateContainerStyle();
399 * - deactivates the engine
400 * - reinitializes the button
401 * - removes the marker
406 this._cleanClasses();
407 this._resetVariables();
409 this._removeMarker();
413 * This method launches the location engine.
414 * It is called before the marker is updated,
415 * event if it does not mean that the event will be ready.
417 * Override it if you want to add more functionalities.
418 * It should set the this._active to true and do nothing if
419 * this._active is true.
421 _activate: function() {
423 this._map.locate(this.options.locateOptions);
426 // bind event listeners
427 this._map.on('locationfound', this._onLocationFound, this);
428 this._map.on('locationerror', this._onLocationError, this);
429 this._map.on('dragstart', this._onDrag, this);
430 this._map.on('zoomstart', this._onZoom, this);
431 this._map.on('zoomend', this._onZoomEnd, this);
432 if (this.options.showCompass) {
433 if ('ondeviceorientationabsolute' in window) {
434 L.DomEvent.on(window, 'deviceorientationabsolute', this._onDeviceOrientation, this);
435 } else if ('ondeviceorientation' in window) {
436 L.DomEvent.on(window, 'deviceorientation', this._onDeviceOrientation, this);
443 * Called to stop the location engine.
445 * Override it to shutdown any functionalities you added on start.
447 _deactivate: function() {
448 this._map.stopLocate();
449 this._active = false;
451 if (!this.options.cacheLocation) {
452 this._event = undefined;
455 // unbind event listeners
456 this._map.off('locationfound', this._onLocationFound, this);
457 this._map.off('locationerror', this._onLocationError, this);
458 this._map.off('dragstart', this._onDrag, this);
459 this._map.off('zoomstart', this._onZoom, this);
460 this._map.off('zoomend', this._onZoomEnd, this);
461 if (this.options.showCompass) {
462 this._compassHeading = null;
463 if ('ondeviceorientationabsolute' in window) {
464 L.DomEvent.off(window, 'deviceorientationabsolute', this._onDeviceOrientation, this);
465 } else if ('ondeviceorientation' in window) {
466 L.DomEvent.off(window, 'deviceorientation', this._onDeviceOrientation, this);
472 * Zoom (unless we should keep the zoom level) and an to the current view.
474 setView: function() {
476 if (this._isOutsideMapBounds()) {
477 this._event = undefined; // clear the current location so we can get back into the bounds
478 this.options.onLocationOutsideMapBounds(this);
480 if (this.options.keepCurrentZoomLevel) {
481 var f = this.options.flyTo ? this._map.flyTo : this._map.panTo;
482 f.bind(this._map)([this._event.latitude, this._event.longitude]);
484 var f = this.options.flyTo ? this._map.flyToBounds : this._map.fitBounds;
485 f.bind(this._map)(this._event.bounds, {
486 padding: this.options.circlePadding,
487 maxZoom: this.options.locateOptions.maxZoom
496 _drawCompass: function() {
497 var latlng = this._event.latlng;
499 if (this.options.showCompass && latlng && this._compassHeading !== null) {
500 var cStyle = this._isFollowing() ? this.options.followCompassStyle : this.options.compassStyle;
501 if (!this._compass) {
502 this._compass = new this.options.compassClass(latlng, this._compassHeading, cStyle).addTo(this._layer);
504 this._compass.setLatLng(latlng);
505 this._compass.setHeading(this._compassHeading);
506 // If the compassClass can be updated with setStyle, update it.
507 if (this._compass.setStyle) {
508 this._compass.setStyle(cStyle);
513 if (this._compass && (!this.options.showCompass || this._compassHeading === null)) {
514 this._compass.removeFrom(this._layer);
515 this._compass = null;
520 * Draw the marker and accuracy circle on the map.
522 * Uses the event retrieved from onLocationFound from the map.
524 _drawMarker: function() {
525 if (this._event.accuracy === undefined) {
526 this._event.accuracy = 0;
529 var radius = this._event.accuracy;
530 var latlng = this._event.latlng;
532 // circle with the radius of the location's accuracy
533 if (this.options.drawCircle) {
534 var style = this._isFollowing() ? this.options.followCircleStyle : this.options.circleStyle;
537 this._circle = L.circle(latlng, radius, style).addTo(this._layer);
539 this._circle.setLatLng(latlng).setRadius(radius).setStyle(style);
544 if (this.options.metric) {
545 distance = radius.toFixed(0);
546 unit = this.options.strings.metersUnit;
548 distance = (radius * 3.2808399).toFixed(0);
549 unit = this.options.strings.feetUnit;
552 // small inner marker
553 if (this.options.drawMarker) {
554 var mStyle = this._isFollowing() ? this.options.followMarkerStyle : this.options.markerStyle;
556 this._marker = new this.options.markerClass(latlng, mStyle).addTo(this._layer);
558 this._marker.setLatLng(latlng);
559 // If the markerClass can be updated with setStyle, update it.
560 if (this._marker.setStyle) {
561 this._marker.setStyle(mStyle);
568 var t = this.options.strings.popup;
569 if (this.options.showPopup && t && this._marker) {
571 .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
572 ._popup.setLatLng(latlng);
574 if (this.options.showPopup && t && this._compass) {
576 .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
577 ._popup.setLatLng(latlng);
582 * Remove the marker from map.
584 _removeMarker: function() {
585 this._layer.clearLayers();
586 this._marker = undefined;
587 this._circle = undefined;
591 * Unload the plugin and all event listeners.
592 * Kind of the opposite of onAdd.
594 _unload: function() {
596 this._map.off('unload', this._unload, this);
600 * Sets the compass heading
602 _setCompassHeading: function(angle) {
603 if (!isNaN(parseFloat(angle)) && isFinite(angle)) {
604 angle = Math.round(angle);
606 this._compassHeading = angle;
607 L.Util.requestAnimFrame(this._drawCompass, this);
609 this._compassHeading = null;
614 * If the compass fails calibration just fail safely and remove the compass
616 _onCompassNeedsCalibration: function() {
617 this._setCompassHeading();
621 * Process and normalise compass events
623 _onDeviceOrientation: function(e) {
628 if (e.webkitCompassHeading) {
630 this._setCompassHeading(e.webkitCompassHeading);
631 } else if (e.absolute && e.alpha) {
633 this._setCompassHeading(360 - e.alpha)
638 * Calls deactivate and dispatches an error.
640 _onLocationError: function(err) {
641 // ignore time out error if the location is watched
642 if (err.code == 3 && this.options.locateOptions.watch) {
647 this.options.onLocationError(err, this);
651 * Stores the received event and updates the marker.
653 _onLocationFound: function(e) {
654 // no need to do anything if the location has not changed
656 (this._event.latlng.lat === e.latlng.lat &&
657 this._event.latlng.lng === e.latlng.lng &&
658 this._event.accuracy === e.accuracy)) {
663 // we may have a stray event
670 this._updateContainerStyle();
672 switch (this.options.setView) {
674 if (this._justClicked) {
679 if (!this._userPanned) {
683 case 'untilPanOrZoom':
684 if (!this._userPanned && !this._userZoomed) {
692 // don't set the view
696 this._justClicked = false;
700 * When the user drags. Need a separate event so we can bind and unbind event listeners.
702 _onDrag: function() {
703 // only react to drags once we have a location
705 this._userPanned = true;
706 this._updateContainerStyle();
712 * When the user zooms. Need a separate event so we can bind and unbind event listeners.
714 _onZoom: function() {
715 // only react to drags once we have a location
717 this._userZoomed = true;
718 this._updateContainerStyle();
724 * After a zoom ends update the compass
726 _onZoomEnd: function() {
733 * Compute whether the map is following the user location with pan and zoom.
735 _isFollowing: function() {
740 if (this.options.setView === 'always') {
742 } else if (this.options.setView === 'untilPan') {
743 return !this._userPanned;
744 } else if (this.options.setView === 'untilPanOrZoom') {
745 return !this._userPanned && !this._userZoomed;
750 * Check if location is in map bounds
752 _isOutsideMapBounds: function() {
753 if (this._event === undefined) {
756 return this._map.options.maxBounds &&
757 !this._map.options.maxBounds.contains(this._event.latlng);
761 * Toggles button class between following and active.
763 _updateContainerStyle: function() {
764 if (!this._container) {
768 if (this._active && !this._event) {
769 // active but don't have a location yet
770 this._setClasses('requesting');
771 } else if (this._isFollowing()) {
772 this._setClasses('following');
773 } else if (this._active) {
774 this._setClasses('active');
776 this._cleanClasses();
781 * Sets the CSS classes for the state.
783 _setClasses: function(state) {
784 if (state == 'requesting') {
785 removeClasses(this._container, "active following");
786 addClasses(this._container, "requesting");
788 removeClasses(this._icon, this.options.icon);
789 addClasses(this._icon, this.options.iconLoading);
790 } else if (state == 'active') {
791 removeClasses(this._container, "requesting following");
792 addClasses(this._container, "active");
794 removeClasses(this._icon, this.options.iconLoading);
795 addClasses(this._icon, this.options.icon);
796 } else if (state == 'following') {
797 removeClasses(this._container, "requesting");
798 addClasses(this._container, "active following");
800 removeClasses(this._icon, this.options.iconLoading);
801 addClasses(this._icon, this.options.icon);
806 * Removes all classes from button.
808 _cleanClasses: function() {
809 L.DomUtil.removeClass(this._container, "requesting");
810 L.DomUtil.removeClass(this._container, "active");
811 L.DomUtil.removeClass(this._container, "following");
813 removeClasses(this._icon, this.options.iconLoading);
814 addClasses(this._icon, this.options.icon);
818 * Reinitializes state variables.
820 _resetVariables: function() {
821 // whether locate is active or not
822 this._active = false;
824 // true if the control was clicked for the first time
825 // we need this so we can pan and zoom once we have the location
826 this._justClicked = false;
828 // true if the user has panned the map after clicking the control
829 this._userPanned = false;
831 // true if the user has zoomed the map after clicking the control
832 this._userZoomed = false;
836 L.control.locate = function (options) {
837 return new L.Control.Locate(options);
840 return LocateControl;