]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/leaflet/leaflet.locate.js
Update to iD v2.15.2
[rails.git] / vendor / assets / leaflet / leaflet.locate.js
1 /*!
2 Copyright (c) 2016 Dominik Moritz
3
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
6 */
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.
10
11     // define an AMD module that relies on 'leaflet'
12     if (typeof define === 'function' && define.amd) {
13         define(['leaflet'], factory);
14
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);
19         } else {
20             module.exports = factory(require('leaflet'));
21         }
22     }
23
24     // attach your plugin to the global 'L' variable
25     if (typeof window !== 'undefined' && window.L){
26         window.L.Control.Locate = factory(L);
27     }
28 } (function (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);
33         });
34     };
35
36     var addClasses = function(el, names) { LDomUtilApplyClassesMethod('addClass', el, names); };
37     var removeClasses = function(el, names) { LDomUtilApplyClassesMethod('removeClass', el, names); };
38
39     /**
40      * Compatible with L.Circle but a true marker instead of a path
41      */
42     var LocationMarker = L.Marker.extend({
43         initialize: function (latlng, options) {
44             L.Util.setOptions(this, options);
45             this._latlng = latlng;
46             this.createIcon();
47         },
48
49         /**
50          * Create a styled circle location marker
51          */
52         createIcon: function() {
53             var opt = this.options;
54
55             var style = '';
56
57             if (opt.color !== undefined) {
58                 style += 'stroke:'+opt.color+';';
59             }
60             if (opt.weight !== undefined) {
61                 style += 'stroke-width:'+opt.weight+';';
62             }
63             if (opt.fillColor !== undefined) {
64                 style += 'fill:'+opt.fillColor+';';
65             }
66             if (opt.fillOpacity !== undefined) {
67                 style += 'fill-opacity:'+opt.fillOpacity+';';
68             }
69             if (opt.opacity !== undefined) {
70                 style += 'opacity:'+opt.opacity+';';
71             }
72
73             var icon = this._getIconSVG(opt, style);
74
75             this._locationIcon = L.divIcon({
76                 className: icon.className,
77                 html: icon.svg,
78                 iconSize: [icon.w,icon.h],
79             });
80
81             this.setIcon(this._locationIcon);
82         },
83
84         /**
85          * Return the raw svg for the shape
86          *
87          * Split so can be easily overridden
88          */
89         _getIconSVG: function(options, style) {
90             var r = options.radius;
91             var w = options.weight;
92             var s = r + w;
93             var s2 = s * 2;
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+'" />' +
96             '</svg>';
97             return {
98                 className: 'leaflet-control-locate-location',
99                 svg: svg,
100                 w: s2,
101                 h: s2
102             };
103         },
104
105         setStyle: function(style) {
106             L.Util.setOptions(this, style);
107             this.createIcon();
108         }
109     });
110
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;
116             this.createIcon();
117         },
118
119         setHeading: function(heading) {
120             this._heading = heading;
121         },
122
123         /**
124          * Create a styled arrow compass marker
125          */
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+'" />'+
134             '</svg>';
135             return {
136                 className: 'leafet-control-locate-heading',
137                 svg: svg,
138                 w: w,
139                 h: h
140             };
141         },
142     });
143
144
145     var LocateControl = L.Control.extend({
146         options: {
147             /** Position of the control */
148             position: 'topleft',
149             /** The layer that the user's location should be drawn on. By default creates a new layer. */
150             layer: undefined,
151             /**
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.
155              *
156              * Possible values:
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.
167              */
168             setView: 'untilPanOrZoom',
169             /** Keep the current map zoom level when setting the view and only pan. */
170             keepCurrentZoomLevel: false,
171             /**
172              * This callback can be used to override the viewport tracking
173              * This function should return a LatLngBounds object.
174              *
175              * For example to extend the viewport to ensure that a particular LatLng is visible:
176              *
177              * getLocationBounds: function(locationEvent) {
178              *    return locationEvent.bounds.extend([-33.873085, 151.219273]);
179              * },
180              */
181             getLocationBounds: function (locationEvent) {
182                 return locationEvent.bounds;
183             },
184             /** Smooth pan and zoom to the location of the marker. Only works in Leaflet 1.0+. */
185             flyTo: false,
186             /**
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
192              */
193             clickBehavior: {
194                 /** What should happen if the user clicks on the control while the location is within the current view. */
195                 inView: 'stop',
196                 /** What should happen if the user clicks on the control while the location is outside the current view. */
197                 outOfView: 'setView',
198                 /**
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';
201                  */
202                 inViewNotFollowing: 'inView',
203             },
204             /**
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.
208              */
209             returnToPrevBounds: false,
210             /**
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.
213              */
214             cacheLocation: true,
215             /** If set, a circle that shows the location accuracy is drawn. */
216             drawCircle: true,
217             /** If set, the marker at the users' location is drawn. */
218             drawMarker: true,
219             /** If set and supported then show the compass heading */
220             showCompass: true,
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 */
226             circleStyle: {
227                 className:   'leaflet-control-locate-circle',
228                 color:       '#136AEC',
229                 fillColor:   '#136AEC',
230                 fillOpacity: 0.15,
231                 weight:      0
232             },
233             /** Inner marker style properties. Only works if your marker class supports `setStyle`. */
234             markerStyle: {
235                 className:   'leaflet-control-locate-marker',
236                 color:       '#fff',
237                 fillColor:   '#2A93EE',
238                 fillOpacity: 1,
239                 weight:      3,
240                 opacity:     1,
241                 radius:      9
242             },
243             /** Compass */
244             compassStyle: {
245                 fillColor:   '#2A93EE',
246                 fillOpacity: 1,
247                 weight:      0,
248                 color:       '#fff',
249                 opacity:     1,
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
253             },
254             /**
255              * Changes to accuracy circle and inner marker while following.
256              * It is only necessary to provide the properties that should change.
257              */
258             followCircleStyle: {},
259             followMarkerStyle: {
260                 // color: '#FFA500',
261                 // fillColor: '#FFB000'
262             },
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. */
272             metric: true,
273             /**
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).
277              */
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 };
283             },
284             /** This event is called in case of any location error that is not a time out error. */
285             onLocationError: function(err, control) {
286                 alert(err.message);
287             },
288             /**
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.
291              */
292             onLocationOutsideMapBounds: function(control) {
293                 control.stop();
294                 alert(control.options.strings.outsideMapBoundsMsg);
295             },
296             /** Display a pop-up when the user click on the inner marker. */
297             showPopup: true,
298             strings: {
299                 title: "Show me where I am",
300                 metersUnit: "meters",
301                 feetUnit: "feet",
302                 popup: "You are within {distance} {unit} from this point",
303                 outsideMapBoundsMsg: "You seem located outside the boundaries of the map"
304             },
305             /** The default options passed to leaflets locate method. */
306             locateOptions: {
307                 maxZoom: Infinity,
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
311             }
312         },
313
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]);
319                 } else {
320                     this.options[i] = options[i];
321                 }
322             }
323
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);
328         },
329
330         /**
331          * Add control to map. Returns the container for the control.
332          */
333         onAdd: function (map) {
334             var container = L.DomUtil.create('div',
335                 'leaflet-control-locate leaflet-bar leaflet-control');
336
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;
342
343             var linkAndIcon = this.options.createButtonCallback(container, this.options);
344             this._link = linkAndIcon.link;
345             this._icon = linkAndIcon.icon;
346
347             L.DomEvent
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);
352
353             this._resetVariables();
354
355             this._map.on('unload', this._unload, this);
356
357             return container;
358         },
359
360         /**
361          * This method is called when the user clicks on the control.
362          */
363         _onClick: function() {
364             this._justClicked = true;
365             var wasFollowing =  this._isFollowing();
366             this._userPanned = false;
367             this._userZoomed = false;
368
369             if (this._active && !this._event) {
370                 // click while requesting
371                 this.stop();
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;
377                 }
378
379                 // Allow inheriting from another behavior
380                 if (behaviors[behavior]) {
381                     behavior = behaviors[behavior];
382                 }
383
384                 switch (behavior) {
385                     case 'setView':
386                         this.setView();
387                         break;
388                     case 'stop':
389                         this.stop();
390                         if (this.options.returnToPrevBounds) {
391                             var f = this.options.flyTo ? this._map.flyToBounds : this._map.fitBounds;
392                             f.bind(this._map)(this._prevBounds);
393                         }
394                         break;
395                 }
396             } else {
397                 if (this.options.returnToPrevBounds) {
398                   this._prevBounds = this._map.getBounds();
399                 }
400                 this.start();
401             }
402
403             this._updateContainerStyle();
404         },
405
406         /**
407          * Starts the plugin:
408          * - activates the engine
409          * - draws the marker (if coordinates available)
410          */
411         start: function() {
412             this._activate();
413
414             if (this._event) {
415                 this._drawMarker(this._map);
416
417                 // if we already have a location but the user clicked on the control
418                 if (this.options.setView) {
419                     this.setView();
420                 }
421             }
422             this._updateContainerStyle();
423         },
424
425         /**
426          * Stops the plugin:
427          * - deactivates the engine
428          * - reinitializes the button
429          * - removes the marker
430          */
431         stop: function() {
432             this._deactivate();
433
434             this._cleanClasses();
435             this._resetVariables();
436
437             this._removeMarker();
438         },
439
440         /**
441          * Keep the control active but stop following the location
442          */
443         stopFollowing: function() {
444             this._userPanned = true;
445             this._updateContainerStyle();
446             this._drawMarker();
447         },
448
449         /**
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.
453          *
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.
457          */
458         _activate: function() {
459             if (!this._active) {
460                 this._map.locate(this.options.locateOptions);
461                 this._active = true;
462
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);
474                     }
475                 }
476             }
477         },
478
479         /**
480          * Called to stop the location engine.
481          *
482          * Override it to shutdown any functionalities you added on start.
483          */
484         _deactivate: function() {
485             this._map.stopLocate();
486             this._active = false;
487
488             if (!this.options.cacheLocation) {
489                 this._event = undefined;
490             }
491
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);
504                 }
505             }
506         },
507
508         /**
509          * Zoom (unless we should keep the zoom level) and an to the current view.
510          */
511         setView: function() {
512             this._drawMarker();
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);
516             } else {
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]);
520                 } else {
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
527                     });
528                     L.Util.requestAnimFrame(function(){
529                         // Wait until after the next animFrame because the flyTo can be async
530                         this._ignoreEvent = false;
531                     }, this);
532
533                 }
534             }
535         },
536
537         /**
538          *
539          */
540         _drawCompass: function() {
541             var latlng = this._event.latlng;
542
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);
547                 } else {
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);
553                     }
554                 }
555                 // 
556             }
557             if (this._compass && (!this.options.showCompass || this._compassHeading === null)) {
558                 this._compass.removeFrom(this._layer);
559                 this._compass = null;
560             }
561         },
562
563         /**
564          * Draw the marker and accuracy circle on the map.
565          *
566          * Uses the event retrieved from onLocationFound from the map.
567          */
568         _drawMarker: function() {
569             if (this._event.accuracy === undefined) {
570                 this._event.accuracy = 0;
571             }
572
573             var radius = this._event.accuracy;
574             var latlng = this._event.latlng;
575
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;
579
580                 if (!this._circle) {
581                     this._circle = L.circle(latlng, radius, style).addTo(this._layer);
582                 } else {
583                     this._circle.setLatLng(latlng).setRadius(radius).setStyle(style);
584                 }
585             }
586
587             var distance, unit;
588             if (this.options.metric) {
589                 distance = radius.toFixed(0);
590                 unit =  this.options.strings.metersUnit;
591             } else {
592                 distance = (radius * 3.2808399).toFixed(0);
593                 unit = this.options.strings.feetUnit;
594             }
595
596             // small inner marker
597             if (this.options.drawMarker) {
598                 var mStyle = this._isFollowing() ? this.options.followMarkerStyle : this.options.markerStyle;
599                 if (!this._marker) {
600                     this._marker = new this.options.markerClass(latlng, mStyle).addTo(this._layer);
601                 } else {
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);
606                     }
607                 }
608             }
609
610             this._drawCompass();
611
612             var t = this.options.strings.popup;
613             if (this.options.showPopup && t && this._marker) {
614                 this._marker
615                     .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
616                     ._popup.setLatLng(latlng);
617             }
618             if (this.options.showPopup && t && this._compass) {
619                 this._compass
620                     .bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
621                     ._popup.setLatLng(latlng);
622             }
623         },
624
625         /**
626          * Remove the marker from map.
627          */
628         _removeMarker: function() {
629             this._layer.clearLayers();
630             this._marker = undefined;
631             this._circle = undefined;
632         },
633
634         /**
635          * Unload the plugin and all event listeners.
636          * Kind of the opposite of onAdd.
637          */
638         _unload: function() {
639             this.stop();
640             this._map.off('unload', this._unload, this);
641         },
642
643         /**
644          * Sets the compass heading
645          */
646         _setCompassHeading: function(angle) {
647             if (!isNaN(parseFloat(angle)) && isFinite(angle)) {
648                 angle = Math.round(angle);
649
650                 this._compassHeading = angle;
651                 L.Util.requestAnimFrame(this._drawCompass, this);
652             } else {
653                 this._compassHeading = null;
654             }
655         },
656
657         /**
658          * If the compass fails calibration just fail safely and remove the compass
659          */
660         _onCompassNeedsCalibration: function() {
661             this._setCompassHeading();
662         },
663
664         /**
665          * Process and normalise compass events
666          */
667         _onDeviceOrientation: function(e) {
668             if (!this._active) {
669                 return;
670             }
671
672             if (e.webkitCompassHeading) {
673                 // iOS
674                 this._setCompassHeading(e.webkitCompassHeading);
675             } else if (e.absolute && e.alpha) {
676                 // Android
677                 this._setCompassHeading(360 - e.alpha)
678             }
679         },
680
681         /**
682          * Calls deactivate and dispatches an error.
683          */
684         _onLocationError: function(err) {
685             // ignore time out error if the location is watched
686             if (err.code == 3 && this.options.locateOptions.watch) {
687                 return;
688             }
689
690             this.stop();
691             this.options.onLocationError(err, this);
692         },
693
694         /**
695          * Stores the received event and updates the marker.
696          */
697         _onLocationFound: function(e) {
698             // no need to do anything if the location has not changed
699             if (this._event &&
700                 (this._event.latlng.lat === e.latlng.lat &&
701                  this._event.latlng.lng === e.latlng.lng &&
702                      this._event.accuracy === e.accuracy)) {
703                 return;
704             }
705
706             if (!this._active) {
707                 // we may have a stray event
708                 return;
709             }
710
711             this._event = e;
712
713             this._drawMarker();
714             this._updateContainerStyle();
715
716             switch (this.options.setView) {
717                 case 'once':
718                     if (this._justClicked) {
719                         this.setView();
720                     }
721                     break;
722                 case 'untilPan':
723                     if (!this._userPanned) {
724                         this.setView();
725                     }
726                     break;
727                 case 'untilPanOrZoom':
728                     if (!this._userPanned && !this._userZoomed) {
729                         this.setView();
730                     }
731                     break;
732                 case 'always':
733                     this.setView();
734                     break;
735                 case false:
736                     // don't set the view
737                     break;
738             }
739
740             this._justClicked = false;
741         },
742
743         /**
744          * When the user drags. Need a separate event so we can bind and unbind event listeners.
745          */
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();
751                 this._drawMarker();
752             }
753         },
754
755         /**
756          * When the user zooms. Need a separate event so we can bind and unbind event listeners.
757          */
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();
763                 this._drawMarker();
764             }
765         },
766
767         /**
768          * After a zoom ends update the compass and handle sideways zooms
769          */
770         _onZoomEnd: function() {
771             if (this._event) {
772                 this._drawCompass();
773             }
774
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();
780                     this._drawMarker();
781                 }
782             }
783         },
784
785         /**
786          * Compute whether the map is following the user location with pan and zoom.
787          */
788         _isFollowing: function() {
789             if (!this._active) {
790                 return false;
791             }
792
793             if (this.options.setView === 'always') {
794                 return true;
795             } else if (this.options.setView === 'untilPan') {
796                 return !this._userPanned;
797             } else if (this.options.setView === 'untilPanOrZoom') {
798                 return !this._userPanned && !this._userZoomed;
799             }
800         },
801
802         /**
803          * Check if location is in map bounds
804          */
805         _isOutsideMapBounds: function() {
806             if (this._event === undefined) {
807                 return false;
808             }
809             return this._map.options.maxBounds &&
810                 !this._map.options.maxBounds.contains(this._event.latlng);
811         },
812
813         /**
814          * Toggles button class between following and active.
815          */
816         _updateContainerStyle: function() {
817             if (!this._container) {
818                 return;
819             }
820
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');
828             } else {
829                 this._cleanClasses();
830             }
831         },
832
833         /**
834          * Sets the CSS classes for the state.
835          */
836         _setClasses: function(state) {
837             if (state == 'requesting') {
838                 removeClasses(this._container, "active following");
839                 addClasses(this._container, "requesting");
840
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");
846
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");
852
853                 removeClasses(this._icon, this.options.iconLoading);
854                 addClasses(this._icon, this.options.icon);
855             }
856         },
857
858         /**
859          * Removes all classes from button.
860          */
861         _cleanClasses: function() {
862             L.DomUtil.removeClass(this._container, "requesting");
863             L.DomUtil.removeClass(this._container, "active");
864             L.DomUtil.removeClass(this._container, "following");
865
866             removeClasses(this._icon, this.options.iconLoading);
867             addClasses(this._icon, this.options.icon);
868         },
869
870         /**
871          * Reinitializes state variables.
872          */
873         _resetVariables: function() {
874             // whether locate is active or not
875             this._active = false;
876
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;
880
881             // true if the user has panned the map after clicking the control
882             this._userPanned = false;
883
884             // true if the user has zoomed the map after clicking the control
885             this._userZoomed = false;
886         }
887     });
888
889     L.control.locate = function (options) {
890         return new L.Control.Locate(options);
891     };
892
893     return LocateControl;
894 }, window));