]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/leaflet/leaflet.js
Update leaflet.locate (fixes #438)
[rails.git] / vendor / assets / leaflet / leaflet.js
1 /*
2  Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
3  (c) 2010-2013, Vladimir Agafonkin
4  (c) 2010-2011, CloudMade
5 */
6 (function (window, document, undefined) {
7 var oldL = window.L,
8     L = {};
9
10 L.version = '0.6.3';
11
12 // define Leaflet for Node module pattern loaders, including Browserify
13 if (typeof module === 'object' && typeof module.exports === 'object') {
14         module.exports = L;
15
16 // define Leaflet as an AMD module
17 } else if (typeof define === 'function' && define.amd) {
18         define(L);
19 }
20
21 // define Leaflet as a global L variable, saving the original L to restore later if needed
22
23 L.noConflict = function () {
24         window.L = oldL;
25         return this;
26 };
27
28 window.L = L;
29
30
31 /*
32  * L.Util contains various utility functions used throughout Leaflet code.
33  */
34
35 L.Util = {
36         extend: function (dest) { // (Object[, Object, ...]) ->
37                 var sources = Array.prototype.slice.call(arguments, 1),
38                     i, j, len, src;
39
40                 for (j = 0, len = sources.length; j < len; j++) {
41                         src = sources[j] || {};
42                         for (i in src) {
43                                 if (src.hasOwnProperty(i)) {
44                                         dest[i] = src[i];
45                                 }
46                         }
47                 }
48                 return dest;
49         },
50
51         bind: function (fn, obj) { // (Function, Object) -> Function
52                 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
53                 return function () {
54                         return fn.apply(obj, args || arguments);
55                 };
56         },
57
58         stamp: (function () {
59                 var lastId = 0,
60                     key = '_leaflet_id';
61                 return function (obj) {
62                         obj[key] = obj[key] || ++lastId;
63                         return obj[key];
64                 };
65         }()),
66
67         invokeEach: function (obj, method, context) {
68                 var i, args;
69
70                 if (typeof obj === 'object') {
71                         args = Array.prototype.slice.call(arguments, 3);
72
73                         for (i in obj) {
74                                 method.apply(context, [i, obj[i]].concat(args));
75                         }
76                         return true;
77                 }
78
79                 return false;
80         },
81
82         limitExecByInterval: function (fn, time, context) {
83                 var lock, execOnUnlock;
84
85                 return function wrapperFn() {
86                         var args = arguments;
87
88                         if (lock) {
89                                 execOnUnlock = true;
90                                 return;
91                         }
92
93                         lock = true;
94
95                         setTimeout(function () {
96                                 lock = false;
97
98                                 if (execOnUnlock) {
99                                         wrapperFn.apply(context, args);
100                                         execOnUnlock = false;
101                                 }
102                         }, time);
103
104                         fn.apply(context, args);
105                 };
106         },
107
108         falseFn: function () {
109                 return false;
110         },
111
112         formatNum: function (num, digits) {
113                 var pow = Math.pow(10, digits || 5);
114                 return Math.round(num * pow) / pow;
115         },
116
117         trim: function (str) {
118                 return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
119         },
120
121         splitWords: function (str) {
122                 return L.Util.trim(str).split(/\s+/);
123         },
124
125         setOptions: function (obj, options) {
126                 obj.options = L.extend({}, obj.options, options);
127                 return obj.options;
128         },
129
130         getParamString: function (obj, existingUrl, uppercase) {
131                 var params = [];
132                 for (var i in obj) {
133                         params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
134                 }
135                 return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
136         },
137
138         template: function (str, data) {
139                 return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
140                         var value = data[key];
141                         if (value === undefined) {
142                                 throw new Error('No value provided for variable ' + str);
143                         } else if (typeof value === 'function') {
144                                 value = value(data);
145                         }
146                         return value;
147                 });
148         },
149
150         isArray: function (obj) {
151                 return (Object.prototype.toString.call(obj) === '[object Array]');
152         },
153
154         emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
155 };
156
157 (function () {
158
159         // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
160
161         function getPrefixed(name) {
162                 var i, fn,
163                     prefixes = ['webkit', 'moz', 'o', 'ms'];
164
165                 for (i = 0; i < prefixes.length && !fn; i++) {
166                         fn = window[prefixes[i] + name];
167                 }
168
169                 return fn;
170         }
171
172         var lastTime = 0;
173
174         function timeoutDefer(fn) {
175                 var time = +new Date(),
176                     timeToCall = Math.max(0, 16 - (time - lastTime));
177
178                 lastTime = time + timeToCall;
179                 return window.setTimeout(fn, timeToCall);
180         }
181
182         var requestFn = window.requestAnimationFrame ||
183                 getPrefixed('RequestAnimationFrame') || timeoutDefer;
184
185         var cancelFn = window.cancelAnimationFrame ||
186                 getPrefixed('CancelAnimationFrame') ||
187                 getPrefixed('CancelRequestAnimationFrame') ||
188                 function (id) { window.clearTimeout(id); };
189
190
191         L.Util.requestAnimFrame = function (fn, context, immediate, element) {
192                 fn = L.bind(fn, context);
193
194                 if (immediate && requestFn === timeoutDefer) {
195                         fn();
196                 } else {
197                         return requestFn.call(window, fn, element);
198                 }
199         };
200
201         L.Util.cancelAnimFrame = function (id) {
202                 if (id) {
203                         cancelFn.call(window, id);
204                 }
205         };
206
207 }());
208
209 // shortcuts for most used utility functions
210 L.extend = L.Util.extend;
211 L.bind = L.Util.bind;
212 L.stamp = L.Util.stamp;
213 L.setOptions = L.Util.setOptions;
214
215
216 /*
217  * L.Class powers the OOP facilities of the library.
218  * Thanks to John Resig and Dean Edwards for inspiration!
219  */
220
221 L.Class = function () {};
222
223 L.Class.extend = function (props) {
224
225         // extended class with the new prototype
226         var NewClass = function () {
227
228                 // call the constructor
229                 if (this.initialize) {
230                         this.initialize.apply(this, arguments);
231                 }
232
233                 // call all constructor hooks
234                 if (this._initHooks) {
235                         this.callInitHooks();
236                 }
237         };
238
239         // instantiate class without calling constructor
240         var F = function () {};
241         F.prototype = this.prototype;
242
243         var proto = new F();
244         proto.constructor = NewClass;
245
246         NewClass.prototype = proto;
247
248         //inherit parent's statics
249         for (var i in this) {
250                 if (this.hasOwnProperty(i) && i !== 'prototype') {
251                         NewClass[i] = this[i];
252                 }
253         }
254
255         // mix static properties into the class
256         if (props.statics) {
257                 L.extend(NewClass, props.statics);
258                 delete props.statics;
259         }
260
261         // mix includes into the prototype
262         if (props.includes) {
263                 L.Util.extend.apply(null, [proto].concat(props.includes));
264                 delete props.includes;
265         }
266
267         // merge options
268         if (props.options && proto.options) {
269                 props.options = L.extend({}, proto.options, props.options);
270         }
271
272         // mix given properties into the prototype
273         L.extend(proto, props);
274
275         proto._initHooks = [];
276
277         var parent = this;
278         // jshint camelcase: false
279         NewClass.__super__ = parent.prototype;
280
281         // add method for calling all hooks
282         proto.callInitHooks = function () {
283
284                 if (this._initHooksCalled) { return; }
285
286                 if (parent.prototype.callInitHooks) {
287                         parent.prototype.callInitHooks.call(this);
288                 }
289
290                 this._initHooksCalled = true;
291
292                 for (var i = 0, len = proto._initHooks.length; i < len; i++) {
293                         proto._initHooks[i].call(this);
294                 }
295         };
296
297         return NewClass;
298 };
299
300
301 // method for adding properties to prototype
302 L.Class.include = function (props) {
303         L.extend(this.prototype, props);
304 };
305
306 // merge new default options to the Class
307 L.Class.mergeOptions = function (options) {
308         L.extend(this.prototype.options, options);
309 };
310
311 // add a constructor hook
312 L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
313         var args = Array.prototype.slice.call(arguments, 1);
314
315         var init = typeof fn === 'function' ? fn : function () {
316                 this[fn].apply(this, args);
317         };
318
319         this.prototype._initHooks = this.prototype._initHooks || [];
320         this.prototype._initHooks.push(init);
321 };
322
323
324 /*
325  * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
326  */
327
328 var eventsKey = '_leaflet_events';
329
330 L.Mixin = {};
331
332 L.Mixin.Events = {
333
334         addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
335
336                 // types can be a map of types/handlers
337                 if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
338
339                 var events = this[eventsKey] = this[eventsKey] || {},
340                     contextId = context && L.stamp(context),
341                     i, len, event, type, indexKey, indexLenKey, typeIndex;
342
343                 // types can be a string of space-separated words
344                 types = L.Util.splitWords(types);
345
346                 for (i = 0, len = types.length; i < len; i++) {
347                         event = {
348                                 action: fn,
349                                 context: context || this
350                         };
351                         type = types[i];
352
353                         if (context) {
354                                 // store listeners of a particular context in a separate hash (if it has an id)
355                                 // gives a major performance boost when removing thousands of map layers
356
357                                 indexKey = type + '_idx';
358                                 indexLenKey = indexKey + '_len';
359
360                                 typeIndex = events[indexKey] = events[indexKey] || {};
361
362                                 if (!typeIndex[contextId]) {
363                                         typeIndex[contextId] = [];
364
365                                         // keep track of the number of keys in the index to quickly check if it's empty
366                                         events[indexLenKey] = (events[indexLenKey] || 0) + 1;
367                                 }
368
369                                 typeIndex[contextId].push(event);
370
371
372                         } else {
373                                 events[type] = events[type] || [];
374                                 events[type].push(event);
375                         }
376                 }
377
378                 return this;
379         },
380
381         hasEventListeners: function (type) { // (String) -> Boolean
382                 var events = this[eventsKey];
383                 return !!events && ((type in events && events[type].length > 0) ||
384                                     (type + '_idx' in events && events[type + '_idx_len'] > 0));
385         },
386
387         removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
388
389                 if (!this[eventsKey]) {
390                         return this;
391                 }
392
393                 if (!types) {
394                         return this.clearAllEventListeners();
395                 }
396
397                 if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
398
399                 var events = this[eventsKey],
400                     contextId = context && L.stamp(context),
401                     i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
402
403                 types = L.Util.splitWords(types);
404
405                 for (i = 0, len = types.length; i < len; i++) {
406                         type = types[i];
407                         indexKey = type + '_idx';
408                         indexLenKey = indexKey + '_len';
409
410                         typeIndex = events[indexKey];
411
412                         if (!fn) {
413                                 // clear all listeners for a type if function isn't specified
414                                 delete events[type];
415                                 delete events[indexKey];
416
417                         } else {
418                                 listeners = context && typeIndex ? typeIndex[contextId] : events[type];
419
420                                 if (listeners) {
421                                         for (j = listeners.length - 1; j >= 0; j--) {
422                                                 if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
423                                                         removed = listeners.splice(j, 1);
424                                                         // set the old action to a no-op, because it is possible
425                                                         // that the listener is being iterated over as part of a dispatch
426                                                         removed[0].action = L.Util.falseFn;
427                                                 }
428                                         }
429
430                                         if (context && typeIndex && (listeners.length === 0)) {
431                                                 delete typeIndex[contextId];
432                                                 events[indexLenKey]--;
433                                         }
434                                 }
435                         }
436                 }
437
438                 return this;
439         },
440
441         clearAllEventListeners: function () {
442                 delete this[eventsKey];
443                 return this;
444         },
445
446         fireEvent: function (type, data) { // (String[, Object])
447                 if (!this.hasEventListeners(type)) {
448                         return this;
449                 }
450
451                 var event = L.Util.extend({}, data, { type: type, target: this });
452
453                 var events = this[eventsKey],
454                     listeners, i, len, typeIndex, contextId;
455
456                 if (events[type]) {
457                         // make sure adding/removing listeners inside other listeners won't cause infinite loop
458                         listeners = events[type].slice();
459
460                         for (i = 0, len = listeners.length; i < len; i++) {
461                                 listeners[i].action.call(listeners[i].context || this, event);
462                         }
463                 }
464
465                 // fire event for the context-indexed listeners as well
466                 typeIndex = events[type + '_idx'];
467
468                 for (contextId in typeIndex) {
469                         listeners = typeIndex[contextId].slice();
470
471                         if (listeners) {
472                                 for (i = 0, len = listeners.length; i < len; i++) {
473                                         listeners[i].action.call(listeners[i].context || this, event);
474                                 }
475                         }
476                 }
477
478                 return this;
479         },
480
481         addOneTimeEventListener: function (types, fn, context) {
482
483                 if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
484
485                 var handler = L.bind(function () {
486                         this
487                             .removeEventListener(types, fn, context)
488                             .removeEventListener(types, handler, context);
489                 }, this);
490
491                 return this
492                     .addEventListener(types, fn, context)
493                     .addEventListener(types, handler, context);
494         }
495 };
496
497 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
498 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
499 L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
500 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
501
502
503 /*
504  * L.Browser handles different browser and feature detections for internal Leaflet use.
505  */
506
507 (function () {
508
509         var ie = !!window.ActiveXObject,
510             ie6 = ie && !window.XMLHttpRequest,
511             ie7 = ie && !document.querySelector,
512                 ielt9 = ie && !document.addEventListener,
513
514             // terrible browser detection to work around Safari / iOS / Android browser bugs
515             ua = navigator.userAgent.toLowerCase(),
516             webkit = ua.indexOf('webkit') !== -1,
517             chrome = ua.indexOf('chrome') !== -1,
518             phantomjs = ua.indexOf('phantom') !== -1,
519             android = ua.indexOf('android') !== -1,
520             android23 = ua.search('android [23]') !== -1,
521
522             mobile = typeof orientation !== undefined + '',
523             msTouch = window.navigator && window.navigator.msPointerEnabled &&
524                       window.navigator.msMaxTouchPoints,
525             retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
526                      ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
527                       window.matchMedia('(min-resolution:144dpi)').matches),
528
529             doc = document.documentElement,
530             ie3d = ie && ('transition' in doc.style),
531             webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
532             gecko3d = 'MozPerspective' in doc.style,
533             opera3d = 'OTransition' in doc.style,
534             any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
535
536
537         // PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch.
538         // https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151
539
540         var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
541
542                 var startName = 'ontouchstart';
543
544                 // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.MsTouch) or WebKit, etc.
545                 if (msTouch || (startName in doc)) {
546                         return true;
547                 }
548
549                 // Firefox/Gecko
550                 var div = document.createElement('div'),
551                     supported = false;
552
553                 if (!div.setAttribute) {
554                         return false;
555                 }
556                 div.setAttribute(startName, 'return;');
557
558                 if (typeof div[startName] === 'function') {
559                         supported = true;
560                 }
561
562                 div.removeAttribute(startName);
563                 div = null;
564
565                 return supported;
566         }());
567
568
569         L.Browser = {
570                 ie: ie,
571                 ie6: ie6,
572                 ie7: ie7,
573                 ielt9: ielt9,
574                 webkit: webkit,
575
576                 android: android,
577                 android23: android23,
578
579                 chrome: chrome,
580
581                 ie3d: ie3d,
582                 webkit3d: webkit3d,
583                 gecko3d: gecko3d,
584                 opera3d: opera3d,
585                 any3d: any3d,
586
587                 mobile: mobile,
588                 mobileWebkit: mobile && webkit,
589                 mobileWebkit3d: mobile && webkit3d,
590                 mobileOpera: mobile && window.opera,
591
592                 touch: touch,
593                 msTouch: msTouch,
594
595                 retina: retina
596         };
597
598 }());
599
600
601 /*
602  * L.Point represents a point with x and y coordinates.
603  */
604
605 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
606         this.x = (round ? Math.round(x) : x);
607         this.y = (round ? Math.round(y) : y);
608 };
609
610 L.Point.prototype = {
611
612         clone: function () {
613                 return new L.Point(this.x, this.y);
614         },
615
616         // non-destructive, returns a new point
617         add: function (point) {
618                 return this.clone()._add(L.point(point));
619         },
620
621         // destructive, used directly for performance in situations where it's safe to modify existing point
622         _add: function (point) {
623                 this.x += point.x;
624                 this.y += point.y;
625                 return this;
626         },
627
628         subtract: function (point) {
629                 return this.clone()._subtract(L.point(point));
630         },
631
632         _subtract: function (point) {
633                 this.x -= point.x;
634                 this.y -= point.y;
635                 return this;
636         },
637
638         divideBy: function (num) {
639                 return this.clone()._divideBy(num);
640         },
641
642         _divideBy: function (num) {
643                 this.x /= num;
644                 this.y /= num;
645                 return this;
646         },
647
648         multiplyBy: function (num) {
649                 return this.clone()._multiplyBy(num);
650         },
651
652         _multiplyBy: function (num) {
653                 this.x *= num;
654                 this.y *= num;
655                 return this;
656         },
657
658         round: function () {
659                 return this.clone()._round();
660         },
661
662         _round: function () {
663                 this.x = Math.round(this.x);
664                 this.y = Math.round(this.y);
665                 return this;
666         },
667
668         floor: function () {
669                 return this.clone()._floor();
670         },
671
672         _floor: function () {
673                 this.x = Math.floor(this.x);
674                 this.y = Math.floor(this.y);
675                 return this;
676         },
677
678         distanceTo: function (point) {
679                 point = L.point(point);
680
681                 var x = point.x - this.x,
682                     y = point.y - this.y;
683
684                 return Math.sqrt(x * x + y * y);
685         },
686
687         equals: function (point) {
688                 point = L.point(point);
689
690                 return point.x === this.x &&
691                        point.y === this.y;
692         },
693
694         contains: function (point) {
695                 point = L.point(point);
696
697                 return Math.abs(point.x) <= Math.abs(this.x) &&
698                        Math.abs(point.y) <= Math.abs(this.y);
699         },
700
701         toString: function () {
702                 return 'Point(' +
703                         L.Util.formatNum(this.x) + ', ' +
704                         L.Util.formatNum(this.y) + ')';
705         }
706 };
707
708 L.point = function (x, y, round) {
709         if (x instanceof L.Point) {
710                 return x;
711         }
712         if (L.Util.isArray(x)) {
713                 return new L.Point(x[0], x[1]);
714         }
715         if (x === undefined || x === null) {
716                 return x;
717         }
718         return new L.Point(x, y, round);
719 };
720
721
722 /*
723  * L.Bounds represents a rectangular area on the screen in pixel coordinates.
724  */
725
726 L.Bounds = function (a, b) { //(Point, Point) or Point[]
727         if (!a) { return; }
728
729         var points = b ? [a, b] : a;
730
731         for (var i = 0, len = points.length; i < len; i++) {
732                 this.extend(points[i]);
733         }
734 };
735
736 L.Bounds.prototype = {
737         // extend the bounds to contain the given point
738         extend: function (point) { // (Point)
739                 point = L.point(point);
740
741                 if (!this.min && !this.max) {
742                         this.min = point.clone();
743                         this.max = point.clone();
744                 } else {
745                         this.min.x = Math.min(point.x, this.min.x);
746                         this.max.x = Math.max(point.x, this.max.x);
747                         this.min.y = Math.min(point.y, this.min.y);
748                         this.max.y = Math.max(point.y, this.max.y);
749                 }
750                 return this;
751         },
752
753         getCenter: function (round) { // (Boolean) -> Point
754                 return new L.Point(
755                         (this.min.x + this.max.x) / 2,
756                         (this.min.y + this.max.y) / 2, round);
757         },
758
759         getBottomLeft: function () { // -> Point
760                 return new L.Point(this.min.x, this.max.y);
761         },
762
763         getTopRight: function () { // -> Point
764                 return new L.Point(this.max.x, this.min.y);
765         },
766
767         getSize: function () {
768                 return this.max.subtract(this.min);
769         },
770
771         contains: function (obj) { // (Bounds) or (Point) -> Boolean
772                 var min, max;
773
774                 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
775                         obj = L.point(obj);
776                 } else {
777                         obj = L.bounds(obj);
778                 }
779
780                 if (obj instanceof L.Bounds) {
781                         min = obj.min;
782                         max = obj.max;
783                 } else {
784                         min = max = obj;
785                 }
786
787                 return (min.x >= this.min.x) &&
788                        (max.x <= this.max.x) &&
789                        (min.y >= this.min.y) &&
790                        (max.y <= this.max.y);
791         },
792
793         intersects: function (bounds) { // (Bounds) -> Boolean
794                 bounds = L.bounds(bounds);
795
796                 var min = this.min,
797                     max = this.max,
798                     min2 = bounds.min,
799                     max2 = bounds.max,
800                     xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
801                     yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
802
803                 return xIntersects && yIntersects;
804         },
805
806         isValid: function () {
807                 return !!(this.min && this.max);
808         }
809 };
810
811 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
812         if (!a || a instanceof L.Bounds) {
813                 return a;
814         }
815         return new L.Bounds(a, b);
816 };
817
818
819 /*
820  * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
821  */
822
823 L.Transformation = function (a, b, c, d) {
824         this._a = a;
825         this._b = b;
826         this._c = c;
827         this._d = d;
828 };
829
830 L.Transformation.prototype = {
831         transform: function (point, scale) { // (Point, Number) -> Point
832                 return this._transform(point.clone(), scale);
833         },
834
835         // destructive transform (faster)
836         _transform: function (point, scale) {
837                 scale = scale || 1;
838                 point.x = scale * (this._a * point.x + this._b);
839                 point.y = scale * (this._c * point.y + this._d);
840                 return point;
841         },
842
843         untransform: function (point, scale) {
844                 scale = scale || 1;
845                 return new L.Point(
846                         (point.x / scale - this._b) / this._a,
847                         (point.y / scale - this._d) / this._c);
848         }
849 };
850
851
852 /*
853  * L.DomUtil contains various utility functions for working with DOM.
854  */
855
856 L.DomUtil = {
857         get: function (id) {
858                 return (typeof id === 'string' ? document.getElementById(id) : id);
859         },
860
861         getStyle: function (el, style) {
862
863                 var value = el.style[style];
864
865                 if (!value && el.currentStyle) {
866                         value = el.currentStyle[style];
867                 }
868
869                 if ((!value || value === 'auto') && document.defaultView) {
870                         var css = document.defaultView.getComputedStyle(el, null);
871                         value = css ? css[style] : null;
872                 }
873
874                 return value === 'auto' ? null : value;
875         },
876
877         getViewportOffset: function (element) {
878
879                 var top = 0,
880                     left = 0,
881                     el = element,
882                     docBody = document.body,
883                     docEl = document.documentElement,
884                     pos,
885                     ie7 = L.Browser.ie7;
886
887                 do {
888                         top  += el.offsetTop  || 0;
889                         left += el.offsetLeft || 0;
890
891                         //add borders
892                         top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
893                         left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
894
895                         pos = L.DomUtil.getStyle(el, 'position');
896
897                         if (el.offsetParent === docBody && pos === 'absolute') { break; }
898
899                         if (pos === 'fixed') {
900                                 top  += docBody.scrollTop  || docEl.scrollTop  || 0;
901                                 left += docBody.scrollLeft || docEl.scrollLeft || 0;
902                                 break;
903                         }
904
905                         if (pos === 'relative' && !el.offsetLeft) {
906                                 var width = L.DomUtil.getStyle(el, 'width'),
907                                     maxWidth = L.DomUtil.getStyle(el, 'max-width'),
908                                     r = el.getBoundingClientRect();
909
910                                 if (width !== 'none' || maxWidth !== 'none') {
911                                         left += r.left + el.clientLeft;
912                                 }
913
914                                 //calculate full y offset since we're breaking out of the loop
915                                 top += r.top + (docBody.scrollTop  || docEl.scrollTop  || 0);
916
917                                 break;
918                         }
919
920                         el = el.offsetParent;
921
922                 } while (el);
923
924                 el = element;
925
926                 do {
927                         if (el === docBody) { break; }
928
929                         top  -= el.scrollTop  || 0;
930                         left -= el.scrollLeft || 0;
931
932                         // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
933                         // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
934                         if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
935                                 left += el.scrollWidth - el.clientWidth;
936
937                                 // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
938                                 // need to add it back in if it is visible; scrollbar is on the left as we are RTL
939                                 if (ie7 && L.DomUtil.getStyle(el, 'overflow-y') !== 'hidden' &&
940                                            L.DomUtil.getStyle(el, 'overflow') !== 'hidden') {
941                                         left += 17;
942                                 }
943                         }
944
945                         el = el.parentNode;
946                 } while (el);
947
948                 return new L.Point(left, top);
949         },
950
951         documentIsLtr: function () {
952                 if (!L.DomUtil._docIsLtrCached) {
953                         L.DomUtil._docIsLtrCached = true;
954                         L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
955                 }
956                 return L.DomUtil._docIsLtr;
957         },
958
959         create: function (tagName, className, container) {
960
961                 var el = document.createElement(tagName);
962                 el.className = className;
963
964                 if (container) {
965                         container.appendChild(el);
966                 }
967
968                 return el;
969         },
970
971         hasClass: function (el, name) {
972                 return (el.className.length > 0) &&
973                         new RegExp('(^|\\s)' + name + '(\\s|$)').test(el.className);
974         },
975
976         addClass: function (el, name) {
977                 if (!L.DomUtil.hasClass(el, name)) {
978                         el.className += (el.className ? ' ' : '') + name;
979                 }
980         },
981
982         removeClass: function (el, name) {
983                 el.className = L.Util.trim((' ' + el.className + ' ').replace(' ' + name + ' ', ' '));
984         },
985
986         setOpacity: function (el, value) {
987
988                 if ('opacity' in el.style) {
989                         el.style.opacity = value;
990
991                 } else if ('filter' in el.style) {
992
993                         var filter = false,
994                             filterName = 'DXImageTransform.Microsoft.Alpha';
995
996                         // filters collection throws an error if we try to retrieve a filter that doesn't exist
997                         try {
998                                 filter = el.filters.item(filterName);
999                         } catch (e) {
1000                                 // don't set opacity to 1 if we haven't already set an opacity,
1001                                 // it isn't needed and breaks transparent pngs.
1002                                 if (value === 1) { return; }
1003                         }
1004
1005                         value = Math.round(value * 100);
1006
1007                         if (filter) {
1008                                 filter.Enabled = (value !== 100);
1009                                 filter.Opacity = value;
1010                         } else {
1011                                 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
1012                         }
1013                 }
1014         },
1015
1016         testProp: function (props) {
1017
1018                 var style = document.documentElement.style;
1019
1020                 for (var i = 0; i < props.length; i++) {
1021                         if (props[i] in style) {
1022                                 return props[i];
1023                         }
1024                 }
1025                 return false;
1026         },
1027
1028         getTranslateString: function (point) {
1029                 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
1030                 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
1031                 // (same speed either way), Opera 12 doesn't support translate3d
1032
1033                 var is3d = L.Browser.webkit3d,
1034                     open = 'translate' + (is3d ? '3d' : '') + '(',
1035                     close = (is3d ? ',0' : '') + ')';
1036
1037                 return open + point.x + 'px,' + point.y + 'px' + close;
1038         },
1039
1040         getScaleString: function (scale, origin) {
1041
1042                 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
1043                     scaleStr = ' scale(' + scale + ') ';
1044
1045                 return preTranslateStr + scaleStr;
1046         },
1047
1048         setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
1049
1050                 // jshint camelcase: false
1051                 el._leaflet_pos = point;
1052
1053                 if (!disable3D && L.Browser.any3d) {
1054                         el.style[L.DomUtil.TRANSFORM] =  L.DomUtil.getTranslateString(point);
1055
1056                         // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
1057                         if (L.Browser.mobileWebkit3d) {
1058                                 el.style.WebkitBackfaceVisibility = 'hidden';
1059                         }
1060                 } else {
1061                         el.style.left = point.x + 'px';
1062                         el.style.top = point.y + 'px';
1063                 }
1064         },
1065
1066         getPosition: function (el) {
1067                 // this method is only used for elements previously positioned using setPosition,
1068                 // so it's safe to cache the position for performance
1069
1070                 // jshint camelcase: false
1071                 return el._leaflet_pos;
1072         }
1073 };
1074
1075
1076 // prefix style property names
1077
1078 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
1079         ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
1080
1081 // webkitTransition comes first because some browser versions that drop vendor prefix don't do
1082 // the same for the transitionend event, in particular the Android 4.1 stock browser
1083
1084 L.DomUtil.TRANSITION = L.DomUtil.testProp(
1085         ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
1086
1087 L.DomUtil.TRANSITION_END =
1088         L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
1089         L.DomUtil.TRANSITION + 'End' : 'transitionend';
1090
1091 (function () {
1092         var userSelectProperty = L.DomUtil.testProp(
1093                 ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
1094
1095         L.extend(L.DomUtil, {
1096                 disableTextSelection: function () {
1097                         L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
1098                         if (userSelectProperty) {
1099                                 var style = document.documentElement.style;
1100                                 this._userSelect = style[userSelectProperty];
1101                                 style[userSelectProperty] = 'none';
1102                         }
1103                 },
1104
1105                 enableTextSelection: function () {
1106                         L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
1107                         if (userSelectProperty) {
1108                                 document.documentElement.style[userSelectProperty] = this._userSelect;
1109                                 delete this._userSelect;
1110                         }
1111                 },
1112
1113                 disableImageDrag: function () {
1114                         L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
1115                 },
1116
1117                 enableImageDrag: function () {
1118                         L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
1119                 }
1120         });
1121 })();
1122
1123
1124 /*
1125  * L.LatLng represents a geographical point with latitude and longitude coordinates.
1126  */
1127
1128 L.LatLng = function (rawLat, rawLng) { // (Number, Number)
1129         var lat = parseFloat(rawLat),
1130             lng = parseFloat(rawLng);
1131
1132         if (isNaN(lat) || isNaN(lng)) {
1133                 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
1134         }
1135
1136         this.lat = lat;
1137         this.lng = lng;
1138 };
1139
1140 L.extend(L.LatLng, {
1141         DEG_TO_RAD: Math.PI / 180,
1142         RAD_TO_DEG: 180 / Math.PI,
1143         MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
1144 });
1145
1146 L.LatLng.prototype = {
1147         equals: function (obj) { // (LatLng) -> Boolean
1148                 if (!obj) { return false; }
1149
1150                 obj = L.latLng(obj);
1151
1152                 var margin = Math.max(
1153                         Math.abs(this.lat - obj.lat),
1154                         Math.abs(this.lng - obj.lng));
1155
1156                 return margin <= L.LatLng.MAX_MARGIN;
1157         },
1158
1159         toString: function (precision) { // (Number) -> String
1160                 return 'LatLng(' +
1161                         L.Util.formatNum(this.lat, precision) + ', ' +
1162                         L.Util.formatNum(this.lng, precision) + ')';
1163         },
1164
1165         // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1166         // TODO move to projection code, LatLng shouldn't know about Earth
1167         distanceTo: function (other) { // (LatLng) -> Number
1168                 other = L.latLng(other);
1169
1170                 var R = 6378137, // earth radius in meters
1171                     d2r = L.LatLng.DEG_TO_RAD,
1172                     dLat = (other.lat - this.lat) * d2r,
1173                     dLon = (other.lng - this.lng) * d2r,
1174                     lat1 = this.lat * d2r,
1175                     lat2 = other.lat * d2r,
1176                     sin1 = Math.sin(dLat / 2),
1177                     sin2 = Math.sin(dLon / 2);
1178
1179                 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1180
1181                 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1182         },
1183
1184         wrap: function (a, b) { // (Number, Number) -> LatLng
1185                 var lng = this.lng;
1186
1187                 a = a || -180;
1188                 b = b ||  180;
1189
1190                 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1191
1192                 return new L.LatLng(this.lat, lng);
1193         }
1194 };
1195
1196 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1197         if (a instanceof L.LatLng) {
1198                 return a;
1199         }
1200         if (L.Util.isArray(a)) {
1201                 return new L.LatLng(a[0], a[1]);
1202         }
1203         if (a === undefined || a === null) {
1204                 return a;
1205         }
1206         if (typeof a === 'object' && 'lat' in a) {
1207                 return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
1208         }
1209         return new L.LatLng(a, b);
1210 };
1211
1212
1213
1214 /*
1215  * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1216  */
1217
1218 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1219         if (!southWest) { return; }
1220
1221         var latlngs = northEast ? [southWest, northEast] : southWest;
1222
1223         for (var i = 0, len = latlngs.length; i < len; i++) {
1224                 this.extend(latlngs[i]);
1225         }
1226 };
1227
1228 L.LatLngBounds.prototype = {
1229         // extend the bounds to contain the given point or bounds
1230         extend: function (obj) { // (LatLng) or (LatLngBounds)
1231                 if (!obj) { return this; }
1232
1233                 if (typeof obj[0] === 'number' || typeof obj[0] === 'string' || obj instanceof L.LatLng) {
1234                         obj = L.latLng(obj);
1235                 } else {
1236                         obj = L.latLngBounds(obj);
1237                 }
1238
1239                 if (obj instanceof L.LatLng) {
1240                         if (!this._southWest && !this._northEast) {
1241                                 this._southWest = new L.LatLng(obj.lat, obj.lng);
1242                                 this._northEast = new L.LatLng(obj.lat, obj.lng);
1243                         } else {
1244                                 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1245                                 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1246
1247                                 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1248                                 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1249                         }
1250                 } else if (obj instanceof L.LatLngBounds) {
1251                         this.extend(obj._southWest);
1252                         this.extend(obj._northEast);
1253                 }
1254                 return this;
1255         },
1256
1257         // extend the bounds by a percentage
1258         pad: function (bufferRatio) { // (Number) -> LatLngBounds
1259                 var sw = this._southWest,
1260                     ne = this._northEast,
1261                     heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1262                     widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1263
1264                 return new L.LatLngBounds(
1265                         new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1266                         new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1267         },
1268
1269         getCenter: function () { // -> LatLng
1270                 return new L.LatLng(
1271                         (this._southWest.lat + this._northEast.lat) / 2,
1272                         (this._southWest.lng + this._northEast.lng) / 2);
1273         },
1274
1275         getSouthWest: function () {
1276                 return this._southWest;
1277         },
1278
1279         getNorthEast: function () {
1280                 return this._northEast;
1281         },
1282
1283         getNorthWest: function () {
1284                 return new L.LatLng(this.getNorth(), this.getWest());
1285         },
1286
1287         getSouthEast: function () {
1288                 return new L.LatLng(this.getSouth(), this.getEast());
1289         },
1290
1291         getWest: function () {
1292                 return this._southWest.lng;
1293         },
1294
1295         getSouth: function () {
1296                 return this._southWest.lat;
1297         },
1298
1299         getEast: function () {
1300                 return this._northEast.lng;
1301         },
1302
1303         getNorth: function () {
1304                 return this._northEast.lat;
1305         },
1306
1307         contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1308                 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1309                         obj = L.latLng(obj);
1310                 } else {
1311                         obj = L.latLngBounds(obj);
1312                 }
1313
1314                 var sw = this._southWest,
1315                     ne = this._northEast,
1316                     sw2, ne2;
1317
1318                 if (obj instanceof L.LatLngBounds) {
1319                         sw2 = obj.getSouthWest();
1320                         ne2 = obj.getNorthEast();
1321                 } else {
1322                         sw2 = ne2 = obj;
1323                 }
1324
1325                 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1326                        (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1327         },
1328
1329         intersects: function (bounds) { // (LatLngBounds)
1330                 bounds = L.latLngBounds(bounds);
1331
1332                 var sw = this._southWest,
1333                     ne = this._northEast,
1334                     sw2 = bounds.getSouthWest(),
1335                     ne2 = bounds.getNorthEast(),
1336
1337                     latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1338                     lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1339
1340                 return latIntersects && lngIntersects;
1341         },
1342
1343         toBBoxString: function () {
1344                 return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
1345         },
1346
1347         equals: function (bounds) { // (LatLngBounds)
1348                 if (!bounds) { return false; }
1349
1350                 bounds = L.latLngBounds(bounds);
1351
1352                 return this._southWest.equals(bounds.getSouthWest()) &&
1353                        this._northEast.equals(bounds.getNorthEast());
1354         },
1355
1356         isValid: function () {
1357                 return !!(this._southWest && this._northEast);
1358         }
1359 };
1360
1361 //TODO International date line?
1362
1363 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1364         if (!a || a instanceof L.LatLngBounds) {
1365                 return a;
1366         }
1367         return new L.LatLngBounds(a, b);
1368 };
1369
1370
1371 /*
1372  * L.Projection contains various geographical projections used by CRS classes.
1373  */
1374
1375 L.Projection = {};
1376
1377
1378 /*
1379  * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1380  */
1381
1382 L.Projection.SphericalMercator = {
1383         MAX_LATITUDE: 85.0511287798,
1384
1385         project: function (latlng) { // (LatLng) -> Point
1386                 var d = L.LatLng.DEG_TO_RAD,
1387                     max = this.MAX_LATITUDE,
1388                     lat = Math.max(Math.min(max, latlng.lat), -max),
1389                     x = latlng.lng * d,
1390                     y = lat * d;
1391
1392                 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1393
1394                 return new L.Point(x, y);
1395         },
1396
1397         unproject: function (point) { // (Point, Boolean) -> LatLng
1398                 var d = L.LatLng.RAD_TO_DEG,
1399                     lng = point.x * d,
1400                     lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1401
1402                 return new L.LatLng(lat, lng);
1403         }
1404 };
1405
1406
1407 /*
1408  * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1409  */
1410
1411 L.Projection.LonLat = {
1412         project: function (latlng) {
1413                 return new L.Point(latlng.lng, latlng.lat);
1414         },
1415
1416         unproject: function (point) {
1417                 return new L.LatLng(point.y, point.x);
1418         }
1419 };
1420
1421
1422 /*
1423  * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1424  */
1425
1426 L.CRS = {
1427         latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1428                 var projectedPoint = this.projection.project(latlng),
1429                     scale = this.scale(zoom);
1430
1431                 return this.transformation._transform(projectedPoint, scale);
1432         },
1433
1434         pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1435                 var scale = this.scale(zoom),
1436                     untransformedPoint = this.transformation.untransform(point, scale);
1437
1438                 return this.projection.unproject(untransformedPoint);
1439         },
1440
1441         project: function (latlng) {
1442                 return this.projection.project(latlng);
1443         },
1444
1445         scale: function (zoom) {
1446                 return 256 * Math.pow(2, zoom);
1447         }
1448 };
1449
1450
1451 /*
1452  * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1453  */
1454
1455 L.CRS.Simple = L.extend({}, L.CRS, {
1456         projection: L.Projection.LonLat,
1457         transformation: new L.Transformation(1, 0, -1, 0),
1458
1459         scale: function (zoom) {
1460                 return Math.pow(2, zoom);
1461         }
1462 });
1463
1464
1465 /*
1466  * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1467  * and is used by Leaflet by default.
1468  */
1469
1470 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1471         code: 'EPSG:3857',
1472
1473         projection: L.Projection.SphericalMercator,
1474         transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1475
1476         project: function (latlng) { // (LatLng) -> Point
1477                 var projectedPoint = this.projection.project(latlng),
1478                     earthRadius = 6378137;
1479                 return projectedPoint.multiplyBy(earthRadius);
1480         }
1481 });
1482
1483 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1484         code: 'EPSG:900913'
1485 });
1486
1487
1488 /*
1489  * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1490  */
1491
1492 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1493         code: 'EPSG:4326',
1494
1495         projection: L.Projection.LonLat,
1496         transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1497 });
1498
1499
1500 /*
1501  * L.Map is the central class of the API - it is used to create a map.
1502  */
1503
1504 L.Map = L.Class.extend({
1505
1506         includes: L.Mixin.Events,
1507
1508         options: {
1509                 crs: L.CRS.EPSG3857,
1510
1511                 /*
1512                 center: LatLng,
1513                 zoom: Number,
1514                 layers: Array,
1515                 */
1516
1517                 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1518                 trackResize: true,
1519                 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1520         },
1521
1522         initialize: function (id, options) { // (HTMLElement or String, Object)
1523                 options = L.setOptions(this, options);
1524
1525                 this._initContainer(id);
1526                 this._initLayout();
1527                 this._initEvents();
1528
1529                 if (options.maxBounds) {
1530                         this.setMaxBounds(options.maxBounds);
1531                 }
1532
1533                 if (options.center && options.zoom !== undefined) {
1534                         this.setView(L.latLng(options.center), options.zoom, {reset: true});
1535                 }
1536
1537                 this._handlers = [];
1538
1539                 this._layers = {};
1540                 this._zoomBoundLayers = {};
1541                 this._tileLayersNum = 0;
1542
1543                 this.callInitHooks();
1544
1545                 this._addLayers(options.layers);
1546         },
1547
1548
1549         // public methods that modify map state
1550
1551         // replaced by animation-powered implementation in Map.PanAnimation.js
1552         setView: function (center, zoom) {
1553                 this._resetView(L.latLng(center), this._limitZoom(zoom));
1554                 return this;
1555         },
1556
1557         setZoom: function (zoom, options) {
1558                 return this.setView(this.getCenter(), zoom, {zoom: options});
1559         },
1560
1561         zoomIn: function (delta, options) {
1562                 return this.setZoom(this._zoom + (delta || 1), options);
1563         },
1564
1565         zoomOut: function (delta, options) {
1566                 return this.setZoom(this._zoom - (delta || 1), options);
1567         },
1568
1569         setZoomAround: function (latlng, zoom, options) {
1570                 var scale = this.getZoomScale(zoom),
1571                     viewHalf = this.getSize().divideBy(2),
1572                     containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
1573
1574                     centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
1575                     newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
1576
1577                 return this.setView(newCenter, zoom, {zoom: options});
1578         },
1579
1580         fitBounds: function (bounds, options) {
1581
1582                 options = options || {};
1583                 bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
1584
1585                 var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
1586                     paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
1587
1588                     zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
1589                     paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
1590
1591                     swPoint = this.project(bounds.getSouthWest(), zoom),
1592                     nePoint = this.project(bounds.getNorthEast(), zoom),
1593                     center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
1594
1595                 return this.setView(center, zoom, options);
1596         },
1597
1598         fitWorld: function (options) {
1599                 return this.fitBounds([[-90, -180], [90, 180]], options);
1600         },
1601
1602         panTo: function (center, options) { // (LatLng)
1603                 return this.setView(center, this._zoom, {pan: options});
1604         },
1605
1606         panBy: function (offset) { // (Point)
1607                 // replaced with animated panBy in Map.Animation.js
1608                 this.fire('movestart');
1609
1610                 this._rawPanBy(L.point(offset));
1611
1612                 this.fire('move');
1613                 return this.fire('moveend');
1614         },
1615
1616         setMaxBounds: function (bounds, options) {
1617                 bounds = L.latLngBounds(bounds);
1618
1619                 this.options.maxBounds = bounds;
1620
1621                 if (!bounds) {
1622                         this._boundsMinZoom = null;
1623                         this.off('moveend', this._panInsideMaxBounds, this);
1624                         return this;
1625                 }
1626
1627                 var minZoom = this.getBoundsZoom(bounds, true);
1628
1629                 this._boundsMinZoom = minZoom;
1630
1631                 if (this._loaded) {
1632                         if (this._zoom < minZoom) {
1633                                 this.setView(bounds.getCenter(), minZoom, options);
1634                         } else {
1635                                 this.panInsideBounds(bounds);
1636                         }
1637                 }
1638
1639                 this.on('moveend', this._panInsideMaxBounds, this);
1640
1641                 return this;
1642         },
1643
1644         panInsideBounds: function (bounds) {
1645                 bounds = L.latLngBounds(bounds);
1646
1647                 var viewBounds = this.getPixelBounds(),
1648                     viewSw = viewBounds.getBottomLeft(),
1649                     viewNe = viewBounds.getTopRight(),
1650                     sw = this.project(bounds.getSouthWest()),
1651                     ne = this.project(bounds.getNorthEast()),
1652                     dx = 0,
1653                     dy = 0;
1654
1655                 if (viewNe.y < ne.y) { // north
1656                         dy = Math.ceil(ne.y - viewNe.y);
1657                 }
1658                 if (viewNe.x > ne.x) { // east
1659                         dx = Math.floor(ne.x - viewNe.x);
1660                 }
1661                 if (viewSw.y > sw.y) { // south
1662                         dy = Math.floor(sw.y - viewSw.y);
1663                 }
1664                 if (viewSw.x < sw.x) { // west
1665                         dx = Math.ceil(sw.x - viewSw.x);
1666                 }
1667
1668                 if (dx || dy) {
1669                         return this.panBy([dx, dy]);
1670                 }
1671
1672                 return this;
1673         },
1674
1675         addLayer: function (layer) {
1676                 // TODO method is too big, refactor
1677
1678                 var id = L.stamp(layer);
1679
1680                 if (this._layers[id]) { return this; }
1681
1682                 this._layers[id] = layer;
1683
1684                 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1685                 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1686                         this._zoomBoundLayers[id] = layer;
1687                         this._updateZoomLevels();
1688                 }
1689
1690                 // TODO looks ugly, refactor!!!
1691                 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1692                         this._tileLayersNum++;
1693                         this._tileLayersToLoad++;
1694                         layer.on('load', this._onTileLayerLoad, this);
1695                 }
1696
1697                 if (this._loaded) {
1698                         this._layerAdd(layer);
1699                 }
1700
1701                 return this;
1702         },
1703
1704         removeLayer: function (layer) {
1705                 var id = L.stamp(layer);
1706
1707                 if (!this._layers[id]) { return; }
1708
1709                 if (this._loaded) {
1710                         layer.onRemove(this);
1711                 }
1712
1713                 delete this._layers[id];
1714
1715                 if (this._loaded) {
1716                         this.fire('layerremove', {layer: layer});
1717                 }
1718
1719                 if (this._zoomBoundLayers[id]) {
1720                         delete this._zoomBoundLayers[id];
1721                         this._updateZoomLevels();
1722                 }
1723
1724                 // TODO looks ugly, refactor
1725                 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1726                         this._tileLayersNum--;
1727                         this._tileLayersToLoad--;
1728                         layer.off('load', this._onTileLayerLoad, this);
1729                 }
1730
1731                 return this;
1732         },
1733
1734         hasLayer: function (layer) {
1735                 if (!layer) { return false; }
1736
1737                 return (L.stamp(layer) in this._layers);
1738         },
1739
1740         eachLayer: function (method, context) {
1741                 for (var i in this._layers) {
1742                         method.call(context, this._layers[i]);
1743                 }
1744                 return this;
1745         },
1746
1747         invalidateSize: function (options) {
1748                 options = L.extend({
1749                         animate: false,
1750                         pan: true
1751                 }, options === true ? {animate: true} : options);
1752
1753                 var oldSize = this.getSize();
1754                 this._sizeChanged = true;
1755                 this._initialCenter = null;
1756
1757                 if (this.options.maxBounds) {
1758                         this.setMaxBounds(this.options.maxBounds);
1759                 }
1760
1761                 if (!this._loaded) { return this; }
1762
1763                 var newSize = this.getSize(),
1764                     offset = oldSize.subtract(newSize).divideBy(2).round();
1765
1766                 if (!offset.x && !offset.y) { return this; }
1767
1768                 if (options.animate && options.pan) {
1769                         this.panBy(offset);
1770
1771                 } else {
1772                         if (options.pan) {
1773                                 this._rawPanBy(offset);
1774                         }
1775
1776                         this.fire('move');
1777
1778                         // make sure moveend is not fired too often on resize
1779                         clearTimeout(this._sizeTimer);
1780                         this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1781                 }
1782
1783                 return this.fire('resize', {
1784                         oldSize: oldSize,
1785                         newSize: newSize
1786                 });
1787         },
1788
1789         // TODO handler.addTo
1790         addHandler: function (name, HandlerClass) {
1791                 if (!HandlerClass) { return; }
1792
1793                 var handler = this[name] = new HandlerClass(this);
1794
1795                 this._handlers.push(handler);
1796
1797                 if (this.options[name]) {
1798                         handler.enable();
1799                 }
1800
1801                 return this;
1802         },
1803
1804         remove: function () {
1805                 if (this._loaded) {
1806                         this.fire('unload');
1807                 }
1808
1809                 this._initEvents('off');
1810
1811                 delete this._container._leaflet;
1812
1813                 this._clearPanes();
1814                 if (this._clearControlPos) {
1815                         this._clearControlPos();
1816                 }
1817
1818                 this._clearHandlers();
1819
1820                 return this;
1821         },
1822
1823
1824         // public methods for getting map state
1825
1826         getCenter: function () { // (Boolean) -> LatLng
1827                 this._checkIfLoaded();
1828
1829                 if (this._initialCenter && !this._moved()) {
1830                         return this._initialCenter;
1831                 }
1832                 return this.layerPointToLatLng(this._getCenterLayerPoint());
1833         },
1834
1835         getZoom: function () {
1836                 return this._zoom;
1837         },
1838
1839         getBounds: function () {
1840                 var bounds = this.getPixelBounds(),
1841                     sw = this.unproject(bounds.getBottomLeft()),
1842                     ne = this.unproject(bounds.getTopRight());
1843
1844                 return new L.LatLngBounds(sw, ne);
1845         },
1846
1847         getMinZoom: function () {
1848                 var z1 = this._layersMinZoom === undefined ? -Infinity : this._layersMinZoom,
1849                     z2 = this._boundsMinZoom === undefined ? -Infinity : this._boundsMinZoom;
1850                 return this.options.minZoom === undefined ? Math.max(z1, z2) : this.options.minZoom;
1851         },
1852
1853         getMaxZoom: function () {
1854                 return this.options.maxZoom === undefined ?
1855                         (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
1856                         this.options.maxZoom;
1857         },
1858
1859         getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1860                 bounds = L.latLngBounds(bounds);
1861
1862                 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1863                     maxZoom = this.getMaxZoom(),
1864                     size = this.getSize(),
1865
1866                     nw = bounds.getNorthWest(),
1867                     se = bounds.getSouthEast(),
1868
1869                     zoomNotFound = true,
1870                     boundsSize;
1871
1872                 padding = L.point(padding || [0, 0]);
1873
1874                 do {
1875                         zoom++;
1876                         boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1877                         zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1878
1879                 } while (zoomNotFound && zoom <= maxZoom);
1880
1881                 if (zoomNotFound && inside) {
1882                         return null;
1883                 }
1884
1885                 return inside ? zoom : zoom - 1;
1886         },
1887
1888         getSize: function () {
1889                 if (!this._size || this._sizeChanged) {
1890                         this._size = new L.Point(
1891                                 this._container.clientWidth,
1892                                 this._container.clientHeight);
1893
1894                         this._sizeChanged = false;
1895                 }
1896                 return this._size.clone();
1897         },
1898
1899         getPixelBounds: function () {
1900                 var topLeftPoint = this._getTopLeftPoint();
1901                 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1902         },
1903
1904         getPixelOrigin: function () {
1905                 this._checkIfLoaded();
1906                 return this._initialTopLeftPoint;
1907         },
1908
1909         getPanes: function () {
1910                 return this._panes;
1911         },
1912
1913         getContainer: function () {
1914                 return this._container;
1915         },
1916
1917
1918         // TODO replace with universal implementation after refactoring projections
1919
1920         getZoomScale: function (toZoom) {
1921                 var crs = this.options.crs;
1922                 return crs.scale(toZoom) / crs.scale(this._zoom);
1923         },
1924
1925         getScaleZoom: function (scale) {
1926                 return this._zoom + (Math.log(scale) / Math.LN2);
1927         },
1928
1929
1930         // conversion methods
1931
1932         project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1933                 zoom = zoom === undefined ? this._zoom : zoom;
1934                 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1935         },
1936
1937         unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1938                 zoom = zoom === undefined ? this._zoom : zoom;
1939                 return this.options.crs.pointToLatLng(L.point(point), zoom);
1940         },
1941
1942         layerPointToLatLng: function (point) { // (Point)
1943                 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1944                 return this.unproject(projectedPoint);
1945         },
1946
1947         latLngToLayerPoint: function (latlng) { // (LatLng)
1948                 var projectedPoint = this.project(L.latLng(latlng))._round();
1949                 return projectedPoint._subtract(this.getPixelOrigin());
1950         },
1951
1952         containerPointToLayerPoint: function (point) { // (Point)
1953                 return L.point(point).subtract(this._getMapPanePos());
1954         },
1955
1956         layerPointToContainerPoint: function (point) { // (Point)
1957                 return L.point(point).add(this._getMapPanePos());
1958         },
1959
1960         containerPointToLatLng: function (point) {
1961                 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1962                 return this.layerPointToLatLng(layerPoint);
1963         },
1964
1965         latLngToContainerPoint: function (latlng) {
1966                 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1967         },
1968
1969         mouseEventToContainerPoint: function (e) { // (MouseEvent)
1970                 return L.DomEvent.getMousePosition(e, this._container);
1971         },
1972
1973         mouseEventToLayerPoint: function (e) { // (MouseEvent)
1974                 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1975         },
1976
1977         mouseEventToLatLng: function (e) { // (MouseEvent)
1978                 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1979         },
1980
1981
1982         // map initialization methods
1983
1984         _initContainer: function (id) {
1985                 var container = this._container = L.DomUtil.get(id);
1986
1987                 if (!container) {
1988                         throw new Error('Map container not found.');
1989                 } else if (container._leaflet) {
1990                         throw new Error('Map container is already initialized.');
1991                 }
1992
1993                 container._leaflet = true;
1994         },
1995
1996         _initLayout: function () {
1997                 var container = this._container;
1998
1999                 L.DomUtil.addClass(container, 'leaflet-container' +
2000                         (L.Browser.touch ? ' leaflet-touch' : '') +
2001                         (L.Browser.retina ? ' leaflet-retina' : '') +
2002                         (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
2003
2004                 var position = L.DomUtil.getStyle(container, 'position');
2005
2006                 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
2007                         container.style.position = 'relative';
2008                 }
2009
2010                 this._initPanes();
2011
2012                 if (this._initControlPos) {
2013                         this._initControlPos();
2014                 }
2015         },
2016
2017         _initPanes: function () {
2018                 var panes = this._panes = {};
2019
2020                 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2021
2022                 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2023                 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2024                 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2025                 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2026                 panes.markerPane = this._createPane('leaflet-marker-pane');
2027                 panes.popupPane = this._createPane('leaflet-popup-pane');
2028
2029                 var zoomHide = ' leaflet-zoom-hide';
2030
2031                 if (!this.options.markerZoomAnimation) {
2032                         L.DomUtil.addClass(panes.markerPane, zoomHide);
2033                         L.DomUtil.addClass(panes.shadowPane, zoomHide);
2034                         L.DomUtil.addClass(panes.popupPane, zoomHide);
2035                 }
2036         },
2037
2038         _createPane: function (className, container) {
2039                 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2040         },
2041
2042         _clearPanes: function () {
2043                 this._container.removeChild(this._mapPane);
2044         },
2045
2046         _addLayers: function (layers) {
2047                 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2048
2049                 for (var i = 0, len = layers.length; i < len; i++) {
2050                         this.addLayer(layers[i]);
2051                 }
2052         },
2053
2054
2055         // private methods that modify map state
2056
2057         _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2058
2059                 var zoomChanged = (this._zoom !== zoom);
2060
2061                 if (!afterZoomAnim) {
2062                         this.fire('movestart');
2063
2064                         if (zoomChanged) {
2065                                 this.fire('zoomstart');
2066                         }
2067                 }
2068
2069                 this._zoom = zoom;
2070                 this._initialCenter = center;
2071
2072                 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2073
2074                 if (!preserveMapOffset) {
2075                         L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2076                 } else {
2077                         this._initialTopLeftPoint._add(this._getMapPanePos());
2078                 }
2079
2080                 this._tileLayersToLoad = this._tileLayersNum;
2081
2082                 var loading = !this._loaded;
2083                 this._loaded = true;
2084
2085                 if (loading) {
2086                         this.fire('load');
2087                         this.eachLayer(this._layerAdd, this);
2088                 }
2089
2090                 this.fire('viewreset', {hard: !preserveMapOffset});
2091
2092                 this.fire('move');
2093
2094                 if (zoomChanged || afterZoomAnim) {
2095                         this.fire('zoomend');
2096                 }
2097
2098                 this.fire('moveend', {hard: !preserveMapOffset});
2099         },
2100
2101         _rawPanBy: function (offset) {
2102                 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2103         },
2104
2105         _getZoomSpan: function () {
2106                 return this.getMaxZoom() - this.getMinZoom();
2107         },
2108
2109         _updateZoomLevels: function () {
2110                 var i,
2111                         minZoom = Infinity,
2112                         maxZoom = -Infinity,
2113                         oldZoomSpan = this._getZoomSpan();
2114
2115                 for (i in this._zoomBoundLayers) {
2116                         var layer = this._zoomBoundLayers[i];
2117                         if (!isNaN(layer.options.minZoom)) {
2118                                 minZoom = Math.min(minZoom, layer.options.minZoom);
2119                         }
2120                         if (!isNaN(layer.options.maxZoom)) {
2121                                 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2122                         }
2123                 }
2124
2125                 if (i === undefined) { // we have no tilelayers
2126                         this._layersMaxZoom = this._layersMinZoom = undefined;
2127                 } else {
2128                         this._layersMaxZoom = maxZoom;
2129                         this._layersMinZoom = minZoom;
2130                 }
2131
2132                 if (oldZoomSpan !== this._getZoomSpan()) {
2133                         this.fire('zoomlevelschange');
2134                 }
2135         },
2136
2137         _panInsideMaxBounds: function () {
2138                 this.panInsideBounds(this.options.maxBounds);
2139         },
2140
2141         _checkIfLoaded: function () {
2142                 if (!this._loaded) {
2143                         throw new Error('Set map center and zoom first.');
2144                 }
2145         },
2146
2147         // map events
2148
2149         _initEvents: function (onOff) {
2150                 if (!L.DomEvent) { return; }
2151
2152                 onOff = onOff || 'on';
2153
2154                 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2155
2156                 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2157                               'mouseleave', 'mousemove', 'contextmenu'],
2158                     i, len;
2159
2160                 for (i = 0, len = events.length; i < len; i++) {
2161                         L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2162                 }
2163
2164                 if (this.options.trackResize) {
2165                         L.DomEvent[onOff](window, 'resize', this._onResize, this);
2166                 }
2167         },
2168
2169         _onResize: function () {
2170                 L.Util.cancelAnimFrame(this._resizeRequest);
2171                 this._resizeRequest = L.Util.requestAnimFrame(
2172                         this.invalidateSize, this, false, this._container);
2173         },
2174
2175         _onMouseClick: function (e) {
2176                 if (!this._loaded || (!e._simulated && this.dragging && this.dragging.moved()) ||
2177                         L.DomEvent._skipped(e)) { return; }
2178
2179                 this.fire('preclick');
2180                 this._fireMouseEvent(e);
2181         },
2182
2183         _fireMouseEvent: function (e) {
2184                 if (!this._loaded || L.DomEvent._skipped(e)) { return; }
2185
2186                 var type = e.type;
2187
2188                 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2189
2190                 if (!this.hasEventListeners(type)) { return; }
2191
2192                 if (type === 'contextmenu') {
2193                         L.DomEvent.preventDefault(e);
2194                 }
2195
2196                 var containerPoint = this.mouseEventToContainerPoint(e),
2197                     layerPoint = this.containerPointToLayerPoint(containerPoint),
2198                     latlng = this.layerPointToLatLng(layerPoint);
2199
2200                 this.fire(type, {
2201                         latlng: latlng,
2202                         layerPoint: layerPoint,
2203                         containerPoint: containerPoint,
2204                         originalEvent: e
2205                 });
2206         },
2207
2208         _onTileLayerLoad: function () {
2209                 this._tileLayersToLoad--;
2210                 if (this._tileLayersNum && !this._tileLayersToLoad) {
2211                         this.fire('tilelayersload');
2212                 }
2213         },
2214
2215         _clearHandlers: function () {
2216                 for (var i = 0, len = this._handlers.length; i < len; i++) {
2217                         this._handlers[i].disable();
2218                 }
2219         },
2220
2221         whenReady: function (callback, context) {
2222                 if (this._loaded) {
2223                         callback.call(context || this, this);
2224                 } else {
2225                         this.on('load', callback, context);
2226                 }
2227                 return this;
2228         },
2229
2230         _layerAdd: function (layer) {
2231                 layer.onAdd(this);
2232                 this.fire('layeradd', {layer: layer});
2233         },
2234
2235
2236         // private methods for getting map state
2237
2238         _getMapPanePos: function () {
2239                 return L.DomUtil.getPosition(this._mapPane);
2240         },
2241
2242         _moved: function () {
2243                 var pos = this._getMapPanePos();
2244                 return pos && !pos.equals([0, 0]);
2245         },
2246
2247         _getTopLeftPoint: function () {
2248                 return this.getPixelOrigin().subtract(this._getMapPanePos());
2249         },
2250
2251         _getNewTopLeftPoint: function (center, zoom) {
2252                 var viewHalf = this.getSize()._divideBy(2);
2253                 // TODO round on display, not calculation to increase precision?
2254                 return this.project(center, zoom)._subtract(viewHalf)._round();
2255         },
2256
2257         _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2258                 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2259                 return this.project(latlng, newZoom)._subtract(topLeft);
2260         },
2261
2262         // layer point of the current center
2263         _getCenterLayerPoint: function () {
2264                 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2265         },
2266
2267         // offset of the specified place to the current center in pixels
2268         _getCenterOffset: function (latlng) {
2269                 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2270         },
2271
2272         _limitZoom: function (zoom) {
2273                 var min = this.getMinZoom(),
2274                     max = this.getMaxZoom();
2275
2276                 return Math.max(min, Math.min(max, zoom));
2277         }
2278 });
2279
2280 L.map = function (id, options) {
2281         return new L.Map(id, options);
2282 };
2283
2284
2285 /*
2286  * Mercator projection that takes into account that the Earth is not a perfect sphere.
2287  * Less popular than spherical mercator; used by projections like EPSG:3395.
2288  */
2289
2290 L.Projection.Mercator = {
2291         MAX_LATITUDE: 85.0840591556,
2292
2293         R_MINOR: 6356752.314245179,
2294         R_MAJOR: 6378137,
2295
2296         project: function (latlng) { // (LatLng) -> Point
2297                 var d = L.LatLng.DEG_TO_RAD,
2298                     max = this.MAX_LATITUDE,
2299                     lat = Math.max(Math.min(max, latlng.lat), -max),
2300                     r = this.R_MAJOR,
2301                     r2 = this.R_MINOR,
2302                     x = latlng.lng * d * r,
2303                     y = lat * d,
2304                     tmp = r2 / r,
2305                     eccent = Math.sqrt(1.0 - tmp * tmp),
2306                     con = eccent * Math.sin(y);
2307
2308                 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2309
2310                 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2311                 y = -r * Math.log(ts);
2312
2313                 return new L.Point(x, y);
2314         },
2315
2316         unproject: function (point) { // (Point, Boolean) -> LatLng
2317                 var d = L.LatLng.RAD_TO_DEG,
2318                     r = this.R_MAJOR,
2319                     r2 = this.R_MINOR,
2320                     lng = point.x * d / r,
2321                     tmp = r2 / r,
2322                     eccent = Math.sqrt(1 - (tmp * tmp)),
2323                     ts = Math.exp(- point.y / r),
2324                     phi = (Math.PI / 2) - 2 * Math.atan(ts),
2325                     numIter = 15,
2326                     tol = 1e-7,
2327                     i = numIter,
2328                     dphi = 0.1,
2329                     con;
2330
2331                 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2332                         con = eccent * Math.sin(phi);
2333                         dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2334                                     Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2335                         phi += dphi;
2336                 }
2337
2338                 return new L.LatLng(phi * d, lng);
2339         }
2340 };
2341
2342
2343
2344 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2345         code: 'EPSG:3395',
2346
2347         projection: L.Projection.Mercator,
2348
2349         transformation: (function () {
2350                 var m = L.Projection.Mercator,
2351                     r = m.R_MAJOR,
2352                     r2 = m.R_MINOR;
2353
2354                 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
2355         }())
2356 });
2357
2358
2359 /*
2360  * L.TileLayer is used for standard xyz-numbered tile layers.
2361  */
2362
2363 L.TileLayer = L.Class.extend({
2364         includes: L.Mixin.Events,
2365
2366         options: {
2367                 minZoom: 0,
2368                 maxZoom: 18,
2369                 tileSize: 256,
2370                 subdomains: 'abc',
2371                 errorTileUrl: '',
2372                 attribution: '',
2373                 zoomOffset: 0,
2374                 opacity: 1,
2375                 /* (undefined works too)
2376                 zIndex: null,
2377                 tms: false,
2378                 continuousWorld: false,
2379                 noWrap: false,
2380                 zoomReverse: false,
2381                 detectRetina: false,
2382                 reuseTiles: false,
2383                 bounds: false,
2384                 */
2385                 unloadInvisibleTiles: L.Browser.mobile,
2386                 updateWhenIdle: L.Browser.mobile
2387         },
2388
2389         initialize: function (url, options) {
2390                 options = L.setOptions(this, options);
2391
2392                 // detecting retina displays, adjusting tileSize and zoom levels
2393                 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2394
2395                         options.tileSize = Math.floor(options.tileSize / 2);
2396                         options.zoomOffset++;
2397
2398                         if (options.minZoom > 0) {
2399                                 options.minZoom--;
2400                         }
2401                         this.options.maxZoom--;
2402                 }
2403
2404                 if (options.bounds) {
2405                         options.bounds = L.latLngBounds(options.bounds);
2406                 }
2407
2408                 this._url = url;
2409
2410                 var subdomains = this.options.subdomains;
2411
2412                 if (typeof subdomains === 'string') {
2413                         this.options.subdomains = subdomains.split('');
2414                 }
2415         },
2416
2417         onAdd: function (map) {
2418                 this._map = map;
2419                 this._animated = map._zoomAnimated;
2420
2421                 // create a container div for tiles
2422                 this._initContainer();
2423
2424                 // create an image to clone for tiles
2425                 this._createTileProto();
2426
2427                 // set up events
2428                 map.on({
2429                         'viewreset': this._reset,
2430                         'moveend': this._update
2431                 }, this);
2432
2433                 if (this._animated) {
2434                         map.on({
2435                                 'zoomanim': this._animateZoom,
2436                                 'zoomend': this._endZoomAnim
2437                         }, this);
2438                 }
2439
2440                 if (!this.options.updateWhenIdle) {
2441                         this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2442                         map.on('move', this._limitedUpdate, this);
2443                 }
2444
2445                 this._reset();
2446                 this._update();
2447         },
2448
2449         addTo: function (map) {
2450                 map.addLayer(this);
2451                 return this;
2452         },
2453
2454         onRemove: function (map) {
2455                 this._container.parentNode.removeChild(this._container);
2456
2457                 map.off({
2458                         'viewreset': this._reset,
2459                         'moveend': this._update
2460                 }, this);
2461
2462                 if (this._animated) {
2463                         map.off({
2464                                 'zoomanim': this._animateZoom,
2465                                 'zoomend': this._endZoomAnim
2466                         }, this);
2467                 }
2468
2469                 if (!this.options.updateWhenIdle) {
2470                         map.off('move', this._limitedUpdate, this);
2471                 }
2472
2473                 this._container = null;
2474                 this._map = null;
2475         },
2476
2477         bringToFront: function () {
2478                 var pane = this._map._panes.tilePane;
2479
2480                 if (this._container) {
2481                         pane.appendChild(this._container);
2482                         this._setAutoZIndex(pane, Math.max);
2483                 }
2484
2485                 return this;
2486         },
2487
2488         bringToBack: function () {
2489                 var pane = this._map._panes.tilePane;
2490
2491                 if (this._container) {
2492                         pane.insertBefore(this._container, pane.firstChild);
2493                         this._setAutoZIndex(pane, Math.min);
2494                 }
2495
2496                 return this;
2497         },
2498
2499         getAttribution: function () {
2500                 return this.options.attribution;
2501         },
2502
2503         getContainer: function () {
2504                 return this._container;
2505         },
2506
2507         setOpacity: function (opacity) {
2508                 this.options.opacity = opacity;
2509
2510                 if (this._map) {
2511                         this._updateOpacity();
2512                 }
2513
2514                 return this;
2515         },
2516
2517         setZIndex: function (zIndex) {
2518                 this.options.zIndex = zIndex;
2519                 this._updateZIndex();
2520
2521                 return this;
2522         },
2523
2524         setUrl: function (url, noRedraw) {
2525                 this._url = url;
2526
2527                 if (!noRedraw) {
2528                         this.redraw();
2529                 }
2530
2531                 return this;
2532         },
2533
2534         redraw: function () {
2535                 if (this._map) {
2536                         this._reset({hard: true});
2537                         this._update();
2538                 }
2539                 return this;
2540         },
2541
2542         _updateZIndex: function () {
2543                 if (this._container && this.options.zIndex !== undefined) {
2544                         this._container.style.zIndex = this.options.zIndex;
2545                 }
2546         },
2547
2548         _setAutoZIndex: function (pane, compare) {
2549
2550                 var layers = pane.children,
2551                     edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2552                     zIndex, i, len;
2553
2554                 for (i = 0, len = layers.length; i < len; i++) {
2555
2556                         if (layers[i] !== this._container) {
2557                                 zIndex = parseInt(layers[i].style.zIndex, 10);
2558
2559                                 if (!isNaN(zIndex)) {
2560                                         edgeZIndex = compare(edgeZIndex, zIndex);
2561                                 }
2562                         }
2563                 }
2564
2565                 this.options.zIndex = this._container.style.zIndex =
2566                         (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2567         },
2568
2569         _updateOpacity: function () {
2570                 var i,
2571                     tiles = this._tiles;
2572
2573                 if (L.Browser.ielt9) {
2574                         for (i in tiles) {
2575                                 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2576                         }
2577                 } else {
2578                         L.DomUtil.setOpacity(this._container, this.options.opacity);
2579                 }
2580         },
2581
2582         _initContainer: function () {
2583                 var tilePane = this._map._panes.tilePane;
2584
2585                 if (!this._container) {
2586                         this._container = L.DomUtil.create('div', 'leaflet-layer');
2587
2588                         this._updateZIndex();
2589
2590                         if (this._animated) {
2591                                 var className = 'leaflet-tile-container leaflet-zoom-animated';
2592
2593                                 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2594                                 this._tileContainer = L.DomUtil.create('div', className, this._container);
2595
2596                         } else {
2597                                 this._tileContainer = this._container;
2598                         }
2599
2600                         tilePane.appendChild(this._container);
2601
2602                         if (this.options.opacity < 1) {
2603                                 this._updateOpacity();
2604                         }
2605                 }
2606         },
2607
2608         _reset: function (e) {
2609                 for (var key in this._tiles) {
2610                         this.fire('tileunload', {tile: this._tiles[key]});
2611                 }
2612
2613                 this._tiles = {};
2614                 this._tilesToLoad = 0;
2615
2616                 if (this.options.reuseTiles) {
2617                         this._unusedTiles = [];
2618                 }
2619
2620                 this._tileContainer.innerHTML = '';
2621
2622                 if (this._animated && e && e.hard) {
2623                         this._clearBgBuffer();
2624                 }
2625
2626                 this._initContainer();
2627         },
2628
2629         _update: function () {
2630
2631                 if (!this._map) { return; }
2632
2633                 var bounds = this._map.getPixelBounds(),
2634                     zoom = this._map.getZoom(),
2635                     tileSize = this.options.tileSize;
2636
2637                 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2638                         return;
2639                 }
2640
2641                 var tileBounds = L.bounds(
2642                         bounds.min.divideBy(tileSize)._floor(),
2643                         bounds.max.divideBy(tileSize)._floor());
2644
2645                 this._addTilesFromCenterOut(tileBounds);
2646
2647                 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2648                         this._removeOtherTiles(tileBounds);
2649                 }
2650         },
2651
2652         _addTilesFromCenterOut: function (bounds) {
2653                 var queue = [],
2654                     center = bounds.getCenter();
2655
2656                 var j, i, point;
2657
2658                 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2659                         for (i = bounds.min.x; i <= bounds.max.x; i++) {
2660                                 point = new L.Point(i, j);
2661
2662                                 if (this._tileShouldBeLoaded(point)) {
2663                                         queue.push(point);
2664                                 }
2665                         }
2666                 }
2667
2668                 var tilesToLoad = queue.length;
2669
2670                 if (tilesToLoad === 0) { return; }
2671
2672                 // load tiles in order of their distance to center
2673                 queue.sort(function (a, b) {
2674                         return a.distanceTo(center) - b.distanceTo(center);
2675                 });
2676
2677                 var fragment = document.createDocumentFragment();
2678
2679                 // if its the first batch of tiles to load
2680                 if (!this._tilesToLoad) {
2681                         this.fire('loading');
2682                 }
2683
2684                 this._tilesToLoad += tilesToLoad;
2685
2686                 for (i = 0; i < tilesToLoad; i++) {
2687                         this._addTile(queue[i], fragment);
2688                 }
2689
2690                 this._tileContainer.appendChild(fragment);
2691         },
2692
2693         _tileShouldBeLoaded: function (tilePoint) {
2694                 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2695                         return false; // already loaded
2696                 }
2697
2698                 var options = this.options;
2699
2700                 if (!options.continuousWorld) {
2701                         var limit = this._getWrapTileNum();
2702
2703                         // don't load if exceeds world bounds
2704                         if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit)) ||
2705                                 tilePoint.y < 0 || tilePoint.y >= limit) { return false; }
2706                 }
2707
2708                 if (options.bounds) {
2709                         var tileSize = options.tileSize,
2710                             nwPoint = tilePoint.multiplyBy(tileSize),
2711                             sePoint = nwPoint.add([tileSize, tileSize]),
2712                             nw = this._map.unproject(nwPoint),
2713                             se = this._map.unproject(sePoint);
2714
2715                         // TODO temporary hack, will be removed after refactoring projections
2716                         // https://github.com/Leaflet/Leaflet/issues/1618
2717                         if (!options.continuousWorld && !options.noWrap) {
2718                                 nw = nw.wrap();
2719                                 se = se.wrap();
2720                         }
2721
2722                         if (!options.bounds.intersects([nw, se])) { return false; }
2723                 }
2724
2725                 return true;
2726         },
2727
2728         _removeOtherTiles: function (bounds) {
2729                 var kArr, x, y, key;
2730
2731                 for (key in this._tiles) {
2732                         kArr = key.split(':');
2733                         x = parseInt(kArr[0], 10);
2734                         y = parseInt(kArr[1], 10);
2735
2736                         // remove tile if it's out of bounds
2737                         if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2738                                 this._removeTile(key);
2739                         }
2740                 }
2741         },
2742
2743         _removeTile: function (key) {
2744                 var tile = this._tiles[key];
2745
2746                 this.fire('tileunload', {tile: tile, url: tile.src});
2747
2748                 if (this.options.reuseTiles) {
2749                         L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2750                         this._unusedTiles.push(tile);
2751
2752                 } else if (tile.parentNode === this._tileContainer) {
2753                         this._tileContainer.removeChild(tile);
2754                 }
2755
2756                 // for https://github.com/CloudMade/Leaflet/issues/137
2757                 if (!L.Browser.android) {
2758                         tile.onload = null;
2759                         tile.src = L.Util.emptyImageUrl;
2760                 }
2761
2762                 delete this._tiles[key];
2763         },
2764
2765         _addTile: function (tilePoint, container) {
2766                 var tilePos = this._getTilePos(tilePoint);
2767
2768                 // get unused tile - or create a new tile
2769                 var tile = this._getTile();
2770
2771                 /*
2772                 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2773                 Android 4 browser has display issues with top/left and requires transform instead
2774                 Android 2 browser requires top/left or tiles disappear on load or first drag
2775                 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2776                 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2777                 */
2778                 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2779
2780                 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2781
2782                 this._loadTile(tile, tilePoint);
2783
2784                 if (tile.parentNode !== this._tileContainer) {
2785                         container.appendChild(tile);
2786                 }
2787         },
2788
2789         _getZoomForUrl: function () {
2790
2791                 var options = this.options,
2792                     zoom = this._map.getZoom();
2793
2794                 if (options.zoomReverse) {
2795                         zoom = options.maxZoom - zoom;
2796                 }
2797
2798                 return zoom + options.zoomOffset;
2799         },
2800
2801         _getTilePos: function (tilePoint) {
2802                 var origin = this._map.getPixelOrigin(),
2803                     tileSize = this.options.tileSize;
2804
2805                 return tilePoint.multiplyBy(tileSize).subtract(origin);
2806         },
2807
2808         // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2809
2810         getTileUrl: function (tilePoint) {
2811                 return L.Util.template(this._url, L.extend({
2812                         s: this._getSubdomain(tilePoint),
2813                         z: tilePoint.z,
2814                         x: tilePoint.x,
2815                         y: tilePoint.y
2816                 }, this.options));
2817         },
2818
2819         _getWrapTileNum: function () {
2820                 // TODO refactor, limit is not valid for non-standard projections
2821                 return Math.pow(2, this._getZoomForUrl());
2822         },
2823
2824         _adjustTilePoint: function (tilePoint) {
2825
2826                 var limit = this._getWrapTileNum();
2827
2828                 // wrap tile coordinates
2829                 if (!this.options.continuousWorld && !this.options.noWrap) {
2830                         tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2831                 }
2832
2833                 if (this.options.tms) {
2834                         tilePoint.y = limit - tilePoint.y - 1;
2835                 }
2836
2837                 tilePoint.z = this._getZoomForUrl();
2838         },
2839
2840         _getSubdomain: function (tilePoint) {
2841                 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2842                 return this.options.subdomains[index];
2843         },
2844
2845         _createTileProto: function () {
2846                 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2847                 img.style.width = img.style.height = this.options.tileSize + 'px';
2848                 img.galleryimg = 'no';
2849         },
2850
2851         _getTile: function () {
2852                 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2853                         var tile = this._unusedTiles.pop();
2854                         this._resetTile(tile);
2855                         return tile;
2856                 }
2857                 return this._createTile();
2858         },
2859
2860         // Override if data stored on a tile needs to be cleaned up before reuse
2861         _resetTile: function (/*tile*/) {},
2862
2863         _createTile: function () {
2864                 var tile = this._tileImg.cloneNode(false);
2865                 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2866
2867                 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2868                         L.DomUtil.setOpacity(tile, this.options.opacity);
2869                 }
2870                 return tile;
2871         },
2872
2873         _loadTile: function (tile, tilePoint) {
2874                 tile._layer  = this;
2875                 tile.onload  = this._tileOnLoad;
2876                 tile.onerror = this._tileOnError;
2877
2878                 this._adjustTilePoint(tilePoint);
2879                 tile.src     = this.getTileUrl(tilePoint);
2880         },
2881
2882         _tileLoaded: function () {
2883                 this._tilesToLoad--;
2884                 if (!this._tilesToLoad) {
2885                         this.fire('load');
2886
2887                         if (this._animated) {
2888                                 // clear scaled tiles after all new tiles are loaded (for performance)
2889                                 clearTimeout(this._clearBgBufferTimer);
2890                                 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2891                         }
2892                 }
2893         },
2894
2895         _tileOnLoad: function () {
2896                 var layer = this._layer;
2897
2898                 //Only if we are loading an actual image
2899                 if (this.src !== L.Util.emptyImageUrl) {
2900                         L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2901
2902                         layer.fire('tileload', {
2903                                 tile: this,
2904                                 url: this.src
2905                         });
2906                 }
2907
2908                 layer._tileLoaded();
2909         },
2910
2911         _tileOnError: function () {
2912                 var layer = this._layer;
2913
2914                 layer.fire('tileerror', {
2915                         tile: this,
2916                         url: this.src
2917                 });
2918
2919                 var newUrl = layer.options.errorTileUrl;
2920                 if (newUrl) {
2921                         this.src = newUrl;
2922                 }
2923
2924                 layer._tileLoaded();
2925         }
2926 });
2927
2928 L.tileLayer = function (url, options) {
2929         return new L.TileLayer(url, options);
2930 };
2931
2932
2933 /*
2934  * L.TileLayer.WMS is used for putting WMS tile layers on the map.
2935  */
2936
2937 L.TileLayer.WMS = L.TileLayer.extend({
2938
2939         defaultWmsParams: {
2940                 service: 'WMS',
2941                 request: 'GetMap',
2942                 version: '1.1.1',
2943                 layers: '',
2944                 styles: '',
2945                 format: 'image/jpeg',
2946                 transparent: false
2947         },
2948
2949         initialize: function (url, options) { // (String, Object)
2950
2951                 this._url = url;
2952
2953                 var wmsParams = L.extend({}, this.defaultWmsParams),
2954                     tileSize = options.tileSize || this.options.tileSize;
2955
2956                 if (options.detectRetina && L.Browser.retina) {
2957                         wmsParams.width = wmsParams.height = tileSize * 2;
2958                 } else {
2959                         wmsParams.width = wmsParams.height = tileSize;
2960                 }
2961
2962                 for (var i in options) {
2963                         // all keys that are not TileLayer options go to WMS params
2964                         if (!this.options.hasOwnProperty(i) && i !== 'crs') {
2965                                 wmsParams[i] = options[i];
2966                         }
2967                 }
2968
2969                 this.wmsParams = wmsParams;
2970
2971                 L.setOptions(this, options);
2972         },
2973
2974         onAdd: function (map) {
2975
2976                 this._crs = this.options.crs || map.options.crs;
2977
2978                 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2979                 this.wmsParams[projectionKey] = this._crs.code;
2980
2981                 L.TileLayer.prototype.onAdd.call(this, map);
2982         },
2983
2984         getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
2985
2986                 var map = this._map,
2987                     tileSize = this.options.tileSize,
2988
2989                     nwPoint = tilePoint.multiplyBy(tileSize),
2990                     sePoint = nwPoint.add([tileSize, tileSize]),
2991
2992                     nw = this._crs.project(map.unproject(nwPoint, zoom)),
2993                     se = this._crs.project(map.unproject(sePoint, zoom)),
2994
2995                     bbox = [nw.x, se.y, se.x, nw.y].join(','),
2996
2997                     url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
2998
2999                 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
3000         },
3001
3002         setParams: function (params, noRedraw) {
3003
3004                 L.extend(this.wmsParams, params);
3005
3006                 if (!noRedraw) {
3007                         this.redraw();
3008                 }
3009
3010                 return this;
3011         }
3012 });
3013
3014 L.tileLayer.wms = function (url, options) {
3015         return new L.TileLayer.WMS(url, options);
3016 };
3017
3018
3019 /*
3020  * L.TileLayer.Canvas is a class that you can use as a base for creating
3021  * dynamically drawn Canvas-based tile layers.
3022  */
3023
3024 L.TileLayer.Canvas = L.TileLayer.extend({
3025         options: {
3026                 async: false
3027         },
3028
3029         initialize: function (options) {
3030                 L.setOptions(this, options);
3031         },
3032
3033         redraw: function () {
3034                 if (this._map) {
3035                         this._reset({hard: true});
3036                         this._update();
3037                 }
3038                 
3039                 for (var i in this._tiles) {
3040                         this._redrawTile(this._tiles[i]);
3041                 }
3042                 return this;
3043         },
3044
3045         _redrawTile: function (tile) {
3046                 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3047         },
3048
3049         _createTileProto: function () {
3050                 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
3051                 proto.width = proto.height = this.options.tileSize;
3052         },
3053
3054         _createTile: function () {
3055                 var tile = this._canvasProto.cloneNode(false);
3056                 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3057                 return tile;
3058         },
3059
3060         _loadTile: function (tile, tilePoint) {
3061                 tile._layer = this;
3062                 tile._tilePoint = tilePoint;
3063
3064                 this._redrawTile(tile);
3065
3066                 if (!this.options.async) {
3067                         this.tileDrawn(tile);
3068                 }
3069         },
3070
3071         drawTile: function (/*tile, tilePoint*/) {
3072                 // override with rendering code
3073         },
3074
3075         tileDrawn: function (tile) {
3076                 this._tileOnLoad.call(tile);
3077         }
3078 });
3079
3080
3081 L.tileLayer.canvas = function (options) {
3082         return new L.TileLayer.Canvas(options);
3083 };
3084
3085
3086 /*
3087  * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3088  */
3089
3090 L.ImageOverlay = L.Class.extend({
3091         includes: L.Mixin.Events,
3092
3093         options: {
3094                 opacity: 1
3095         },
3096
3097         initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3098                 this._url = url;
3099                 this._bounds = L.latLngBounds(bounds);
3100
3101                 L.setOptions(this, options);
3102         },
3103
3104         onAdd: function (map) {
3105                 this._map = map;
3106
3107                 if (!this._image) {
3108                         this._initImage();
3109                 }
3110
3111                 map._panes.overlayPane.appendChild(this._image);
3112
3113                 map.on('viewreset', this._reset, this);
3114
3115                 if (map.options.zoomAnimation && L.Browser.any3d) {
3116                         map.on('zoomanim', this._animateZoom, this);
3117                 }
3118
3119                 this._reset();
3120         },
3121
3122         onRemove: function (map) {
3123                 map.getPanes().overlayPane.removeChild(this._image);
3124
3125                 map.off('viewreset', this._reset, this);
3126
3127                 if (map.options.zoomAnimation) {
3128                         map.off('zoomanim', this._animateZoom, this);
3129                 }
3130         },
3131
3132         addTo: function (map) {
3133                 map.addLayer(this);
3134                 return this;
3135         },
3136
3137         setOpacity: function (opacity) {
3138                 this.options.opacity = opacity;
3139                 this._updateOpacity();
3140                 return this;
3141         },
3142
3143         // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3144         bringToFront: function () {
3145                 if (this._image) {
3146                         this._map._panes.overlayPane.appendChild(this._image);
3147                 }
3148                 return this;
3149         },
3150
3151         bringToBack: function () {
3152                 var pane = this._map._panes.overlayPane;
3153                 if (this._image) {
3154                         pane.insertBefore(this._image, pane.firstChild);
3155                 }
3156                 return this;
3157         },
3158
3159         _initImage: function () {
3160                 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3161
3162                 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3163                         L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3164                 } else {
3165                         L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3166                 }
3167
3168                 this._updateOpacity();
3169
3170                 //TODO createImage util method to remove duplication
3171                 L.extend(this._image, {
3172                         galleryimg: 'no',
3173                         onselectstart: L.Util.falseFn,
3174                         onmousemove: L.Util.falseFn,
3175                         onload: L.bind(this._onImageLoad, this),
3176                         src: this._url
3177                 });
3178         },
3179
3180         _animateZoom: function (e) {
3181                 var map = this._map,
3182                     image = this._image,
3183                     scale = map.getZoomScale(e.zoom),
3184                     nw = this._bounds.getNorthWest(),
3185                     se = this._bounds.getSouthEast(),
3186
3187                     topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3188                     size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3189                     origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3190
3191                 image.style[L.DomUtil.TRANSFORM] =
3192                         L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3193         },
3194
3195         _reset: function () {
3196                 var image   = this._image,
3197                     topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3198                     size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3199
3200                 L.DomUtil.setPosition(image, topLeft);
3201
3202                 image.style.width  = size.x + 'px';
3203                 image.style.height = size.y + 'px';
3204         },
3205
3206         _onImageLoad: function () {
3207                 this.fire('load');
3208         },
3209
3210         _updateOpacity: function () {
3211                 L.DomUtil.setOpacity(this._image, this.options.opacity);
3212         }
3213 });
3214
3215 L.imageOverlay = function (url, bounds, options) {
3216         return new L.ImageOverlay(url, bounds, options);
3217 };
3218
3219
3220 /*
3221  * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3222  */
3223
3224 L.Icon = L.Class.extend({
3225         options: {
3226                 /*
3227                 iconUrl: (String) (required)
3228                 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3229                 iconSize: (Point) (can be set through CSS)
3230                 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3231                 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3232                 shadowUrl: (String) (no shadow by default)
3233                 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3234                 shadowSize: (Point)
3235                 shadowAnchor: (Point)
3236                 */
3237                 className: ''
3238         },
3239
3240         initialize: function (options) {
3241                 L.setOptions(this, options);
3242         },
3243
3244         createIcon: function (oldIcon) {
3245                 return this._createIcon('icon', oldIcon);
3246         },
3247
3248         createShadow: function (oldIcon) {
3249                 return this._createIcon('shadow', oldIcon);
3250         },
3251
3252         _createIcon: function (name, oldIcon) {
3253                 var src = this._getIconUrl(name);
3254
3255                 if (!src) {
3256                         if (name === 'icon') {
3257                                 throw new Error('iconUrl not set in Icon options (see the docs).');
3258                         }
3259                         return null;
3260                 }
3261
3262                 var img;
3263                 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3264                         img = this._createImg(src);
3265                 } else {
3266                         img = this._createImg(src, oldIcon);
3267                 }
3268                 this._setIconStyles(img, name);
3269
3270                 return img;
3271         },
3272
3273         _setIconStyles: function (img, name) {
3274                 var options = this.options,
3275                     size = L.point(options[name + 'Size']),
3276                     anchor;
3277
3278                 if (name === 'shadow') {
3279                         anchor = L.point(options.shadowAnchor || options.iconAnchor);
3280                 } else {
3281                         anchor = L.point(options.iconAnchor);
3282                 }
3283
3284                 if (!anchor && size) {
3285                         anchor = size.divideBy(2, true);
3286                 }
3287
3288                 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3289
3290                 if (anchor) {
3291                         img.style.marginLeft = (-anchor.x) + 'px';
3292                         img.style.marginTop  = (-anchor.y) + 'px';
3293                 }
3294
3295                 if (size) {
3296                         img.style.width  = size.x + 'px';
3297                         img.style.height = size.y + 'px';
3298                 }
3299         },
3300
3301         _createImg: function (src, el) {
3302
3303                 if (!L.Browser.ie6) {
3304                         if (!el) {
3305                                 el = document.createElement('img');
3306                         }
3307                         el.src = src;
3308                 } else {
3309                         if (!el) {
3310                                 el = document.createElement('div');
3311                         }
3312                         el.style.filter =
3313                                 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
3314                 }
3315                 return el;
3316         },
3317
3318         _getIconUrl: function (name) {
3319                 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3320                         return this.options[name + 'RetinaUrl'];
3321                 }
3322                 return this.options[name + 'Url'];
3323         }
3324 });
3325
3326 L.icon = function (options) {
3327         return new L.Icon(options);
3328 };
3329
3330
3331 /*
3332  * L.Icon.Default is the blue marker icon used by default in Leaflet.
3333  */
3334
3335 L.Icon.Default = L.Icon.extend({
3336
3337         options: {
3338                 iconSize: [25, 41],
3339                 iconAnchor: [12, 41],
3340                 popupAnchor: [1, -34],
3341
3342                 shadowSize: [41, 41]
3343         },
3344
3345         _getIconUrl: function (name) {
3346                 var key = name + 'Url';
3347
3348                 if (this.options[key]) {
3349                         return this.options[key];
3350                 }
3351
3352                 if (L.Browser.retina && name === 'icon') {
3353                         name += '-2x';
3354                 }
3355
3356                 var path = L.Icon.Default.imagePath;
3357
3358                 if (!path) {
3359                         throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3360                 }
3361
3362                 return path + '/marker-' + name + '.png';
3363         }
3364 });
3365
3366 L.Icon.Default.imagePath = (function () {
3367         var scripts = document.getElementsByTagName('script'),
3368             leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3369
3370         var i, len, src, matches, path;
3371
3372         for (i = 0, len = scripts.length; i < len; i++) {
3373                 src = scripts[i].src;
3374                 matches = src.match(leafletRe);
3375
3376                 if (matches) {
3377                         path = src.split(leafletRe)[0];
3378                         return (path ? path + '/' : '') + 'images';
3379                 }
3380         }
3381 }());
3382
3383
3384 /*
3385  * L.Marker is used to display clickable/draggable icons on the map.
3386  */
3387
3388 L.Marker = L.Class.extend({
3389
3390         includes: L.Mixin.Events,
3391
3392         options: {
3393                 icon: new L.Icon.Default(),
3394                 title: '',
3395                 clickable: true,
3396                 draggable: false,
3397                 keyboard: true,
3398                 zIndexOffset: 0,
3399                 opacity: 1,
3400                 riseOnHover: false,
3401                 riseOffset: 250
3402         },
3403
3404         initialize: function (latlng, options) {
3405                 L.setOptions(this, options);
3406                 this._latlng = L.latLng(latlng);
3407         },
3408
3409         onAdd: function (map) {
3410                 this._map = map;
3411
3412                 map.on('viewreset', this.update, this);
3413
3414                 this._initIcon();
3415                 this.update();
3416
3417                 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3418                         map.on('zoomanim', this._animateZoom, this);
3419                 }
3420         },
3421
3422         addTo: function (map) {
3423                 map.addLayer(this);
3424                 return this;
3425         },
3426
3427         onRemove: function (map) {
3428                 if (this.dragging) {
3429                         this.dragging.disable();
3430                 }
3431
3432                 this._removeIcon();
3433                 this._removeShadow();
3434
3435                 this.fire('remove');
3436
3437                 map.off({
3438                         'viewreset': this.update,
3439                         'zoomanim': this._animateZoom
3440                 }, this);
3441
3442                 this._map = null;
3443         },
3444
3445         getLatLng: function () {
3446                 return this._latlng;
3447         },
3448
3449         setLatLng: function (latlng) {
3450                 this._latlng = L.latLng(latlng);
3451
3452                 this.update();
3453
3454                 return this.fire('move', { latlng: this._latlng });
3455         },
3456
3457         setZIndexOffset: function (offset) {
3458                 this.options.zIndexOffset = offset;
3459                 this.update();
3460
3461                 return this;
3462         },
3463
3464         setIcon: function (icon) {
3465
3466                 this.options.icon = icon;
3467
3468                 if (this._map) {
3469                         this._initIcon();
3470                         this.update();
3471                 }
3472
3473                 return this;
3474         },
3475
3476         update: function () {
3477                 if (this._icon) {
3478                         var pos = this._map.latLngToLayerPoint(this._latlng).round();
3479                         this._setPos(pos);
3480                 }
3481
3482                 return this;
3483         },
3484
3485         _initIcon: function () {
3486                 var options = this.options,
3487                     map = this._map,
3488                     animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3489                     classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3490
3491                 var icon = options.icon.createIcon(this._icon),
3492                         addIcon = false;
3493
3494                 // if we're not reusing the icon, remove the old one and init new one
3495                 if (icon !== this._icon) {
3496                         if (this._icon) {
3497                                 this._removeIcon();
3498                         }
3499                         addIcon = true;
3500
3501                         if (options.title) {
3502                                 icon.title = options.title;
3503                         }
3504                 }
3505
3506                 L.DomUtil.addClass(icon, classToAdd);
3507
3508                 if (options.keyboard) {
3509                         icon.tabIndex = '0';
3510                 }
3511
3512                 this._icon = icon;
3513
3514                 this._initInteraction();
3515
3516                 if (options.riseOnHover) {
3517                         L.DomEvent
3518                                 .on(icon, 'mouseover', this._bringToFront, this)
3519                                 .on(icon, 'mouseout', this._resetZIndex, this);
3520                 }
3521
3522                 var newShadow = options.icon.createShadow(this._shadow),
3523                         addShadow = false;
3524
3525                 if (newShadow !== this._shadow) {
3526                         this._removeShadow();
3527                         addShadow = true;
3528                 }
3529
3530                 if (newShadow) {
3531                         L.DomUtil.addClass(newShadow, classToAdd);
3532                 }
3533                 this._shadow = newShadow;
3534
3535
3536                 if (options.opacity < 1) {
3537                         this._updateOpacity();
3538                 }
3539
3540
3541                 var panes = this._map._panes;
3542
3543                 if (addIcon) {
3544                         panes.markerPane.appendChild(this._icon);
3545                 }
3546
3547                 if (newShadow && addShadow) {
3548                         panes.shadowPane.appendChild(this._shadow);
3549                 }
3550         },
3551
3552         _removeIcon: function () {
3553                 if (this.options.riseOnHover) {
3554                         L.DomEvent
3555                             .off(this._icon, 'mouseover', this._bringToFront)
3556                             .off(this._icon, 'mouseout', this._resetZIndex);
3557                 }
3558
3559                 this._map._panes.markerPane.removeChild(this._icon);
3560
3561                 this._icon = null;
3562         },
3563
3564         _removeShadow: function () {
3565                 if (this._shadow) {
3566                         this._map._panes.shadowPane.removeChild(this._shadow);
3567                 }
3568                 this._shadow = null;
3569         },
3570
3571         _setPos: function (pos) {
3572                 L.DomUtil.setPosition(this._icon, pos);
3573
3574                 if (this._shadow) {
3575                         L.DomUtil.setPosition(this._shadow, pos);
3576                 }
3577
3578                 this._zIndex = pos.y + this.options.zIndexOffset;
3579
3580                 this._resetZIndex();
3581         },
3582
3583         _updateZIndex: function (offset) {
3584                 this._icon.style.zIndex = this._zIndex + offset;
3585         },
3586
3587         _animateZoom: function (opt) {
3588                 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3589
3590                 this._setPos(pos);
3591         },
3592
3593         _initInteraction: function () {
3594
3595                 if (!this.options.clickable) { return; }
3596
3597                 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3598
3599                 var icon = this._icon,
3600                     events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3601
3602                 L.DomUtil.addClass(icon, 'leaflet-clickable');
3603                 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3604                 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3605
3606                 for (var i = 0; i < events.length; i++) {
3607                         L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3608                 }
3609
3610                 if (L.Handler.MarkerDrag) {
3611                         this.dragging = new L.Handler.MarkerDrag(this);
3612
3613                         if (this.options.draggable) {
3614                                 this.dragging.enable();
3615                         }
3616                 }
3617         },
3618
3619         _onMouseClick: function (e) {
3620                 var wasDragged = this.dragging && this.dragging.moved();
3621
3622                 if (this.hasEventListeners(e.type) || wasDragged) {
3623                         L.DomEvent.stopPropagation(e);
3624                 }
3625
3626                 if (wasDragged) { return; }
3627
3628                 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3629
3630                 this.fire(e.type, {
3631                         originalEvent: e,
3632                         latlng: this._latlng
3633                 });
3634         },
3635
3636         _onKeyPress: function (e) {
3637                 if (e.keyCode === 13) {
3638                         this.fire('click', {
3639                                 originalEvent: e,
3640                                 latlng: this._latlng
3641                         });
3642                 }
3643         },
3644
3645         _fireMouseEvent: function (e) {
3646
3647                 this.fire(e.type, {
3648                         originalEvent: e,
3649                         latlng: this._latlng
3650                 });
3651
3652                 // TODO proper custom event propagation
3653                 // this line will always be called if marker is in a FeatureGroup
3654                 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3655                         L.DomEvent.preventDefault(e);
3656                 }
3657                 if (e.type !== 'mousedown') {
3658                         L.DomEvent.stopPropagation(e);
3659                 } else {
3660                         L.DomEvent.preventDefault(e);
3661                 }
3662         },
3663
3664         setOpacity: function (opacity) {
3665                 this.options.opacity = opacity;
3666                 if (this._map) {
3667                         this._updateOpacity();
3668                 }
3669                 
3670                 return this;
3671         },
3672
3673         _updateOpacity: function () {
3674                 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3675                 if (this._shadow) {
3676                         L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3677                 }
3678         },
3679
3680         _bringToFront: function () {
3681                 this._updateZIndex(this.options.riseOffset);
3682         },
3683
3684         _resetZIndex: function () {
3685                 this._updateZIndex(0);
3686         }
3687 });
3688
3689 L.marker = function (latlng, options) {
3690         return new L.Marker(latlng, options);
3691 };
3692
3693
3694 /*
3695  * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3696  * to use with L.Marker.
3697  */
3698
3699 L.DivIcon = L.Icon.extend({
3700         options: {
3701                 iconSize: [12, 12], // also can be set through CSS
3702                 /*
3703                 iconAnchor: (Point)
3704                 popupAnchor: (Point)
3705                 html: (String)
3706                 bgPos: (Point)
3707                 */
3708                 className: 'leaflet-div-icon',
3709                 html: false
3710         },
3711
3712         createIcon: function (oldIcon) {
3713                 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3714                     options = this.options;
3715
3716                 if (options.html !== false) {
3717                         div.innerHTML = options.html;
3718                 } else {
3719                         div.innerHTML = '';
3720                 }
3721
3722                 if (options.bgPos) {
3723                         div.style.backgroundPosition =
3724                                 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3725                 }
3726
3727                 this._setIconStyles(div, 'icon');
3728                 return div;
3729         },
3730
3731         createShadow: function () {
3732                 return null;
3733         }
3734 });
3735
3736 L.divIcon = function (options) {
3737         return new L.DivIcon(options);
3738 };
3739
3740
3741 /*
3742  * L.Popup is used for displaying popups on the map.
3743  */
3744
3745 L.Map.mergeOptions({
3746         closePopupOnClick: true
3747 });
3748
3749 L.Popup = L.Class.extend({
3750         includes: L.Mixin.Events,
3751
3752         options: {
3753                 minWidth: 50,
3754                 maxWidth: 300,
3755                 maxHeight: null,
3756                 autoPan: true,
3757                 closeButton: true,
3758                 offset: [0, 7],
3759                 autoPanPadding: [5, 5],
3760                 keepInView: false,
3761                 className: '',
3762                 zoomAnimation: true
3763         },
3764
3765         initialize: function (options, source) {
3766                 L.setOptions(this, options);
3767
3768                 this._source = source;
3769                 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3770                 this._isOpen = false;
3771         },
3772
3773         onAdd: function (map) {
3774                 this._map = map;
3775
3776                 if (!this._container) {
3777                         this._initLayout();
3778                 }
3779                 this._updateContent();
3780
3781                 var animFade = map.options.fadeAnimation;
3782
3783                 if (animFade) {
3784                         L.DomUtil.setOpacity(this._container, 0);
3785                 }
3786                 map._panes.popupPane.appendChild(this._container);
3787
3788                 map.on(this._getEvents(), this);
3789
3790                 this._update();
3791
3792                 if (animFade) {
3793                         L.DomUtil.setOpacity(this._container, 1);
3794                 }
3795
3796                 this.fire('open');
3797
3798                 map.fire('popupopen', {popup: this});
3799
3800                 if (this._source) {
3801                         this._source.fire('popupopen', {popup: this});
3802                 }
3803         },
3804
3805         addTo: function (map) {
3806                 map.addLayer(this);
3807                 return this;
3808         },
3809
3810         openOn: function (map) {
3811                 map.openPopup(this);
3812                 return this;
3813         },
3814
3815         onRemove: function (map) {
3816                 map._panes.popupPane.removeChild(this._container);
3817
3818                 L.Util.falseFn(this._container.offsetWidth); // force reflow
3819
3820                 map.off(this._getEvents(), this);
3821
3822                 if (map.options.fadeAnimation) {
3823                         L.DomUtil.setOpacity(this._container, 0);
3824                 }
3825
3826                 this._map = null;
3827
3828                 this.fire('close');
3829
3830                 map.fire('popupclose', {popup: this});
3831
3832                 if (this._source) {
3833                         this._source.fire('popupclose', {popup: this});
3834                 }
3835         },
3836
3837         setLatLng: function (latlng) {
3838                 this._latlng = L.latLng(latlng);
3839                 this._update();
3840                 return this;
3841         },
3842
3843         setContent: function (content) {
3844                 this._content = content;
3845                 this._update();
3846                 return this;
3847         },
3848
3849         _getEvents: function () {
3850                 var events = {
3851                         viewreset: this._updatePosition
3852                 };
3853
3854                 if (this._animated) {
3855                         events.zoomanim = this._zoomAnimation;
3856                 }
3857                 if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
3858                         events.preclick = this._close;
3859                 }
3860                 if (this.options.keepInView) {
3861                         events.moveend = this._adjustPan;
3862                 }
3863
3864                 return events;
3865         },
3866
3867         _close: function () {
3868                 if (this._map) {
3869                         this._map.closePopup(this);
3870                 }
3871         },
3872
3873         _initLayout: function () {
3874                 var prefix = 'leaflet-popup',
3875                         containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
3876                                 (this._animated ? 'animated' : 'hide'),
3877                         container = this._container = L.DomUtil.create('div', containerClass),
3878                         closeButton;
3879
3880                 if (this.options.closeButton) {
3881                         closeButton = this._closeButton =
3882                                 L.DomUtil.create('a', prefix + '-close-button', container);
3883                         closeButton.href = '#close';
3884                         closeButton.innerHTML = '&#215;';
3885                         L.DomEvent.disableClickPropagation(closeButton);
3886
3887                         L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3888                 }
3889
3890                 var wrapper = this._wrapper =
3891                         L.DomUtil.create('div', prefix + '-content-wrapper', container);
3892                 L.DomEvent.disableClickPropagation(wrapper);
3893
3894                 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3895                 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
3896                 L.DomEvent.on(this._contentNode, 'MozMousePixelScroll', L.DomEvent.stopPropagation);
3897                 L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
3898                 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3899                 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3900         },
3901
3902         _update: function () {
3903                 if (!this._map) { return; }
3904
3905                 this._container.style.visibility = 'hidden';
3906
3907                 this._updateContent();
3908                 this._updateLayout();
3909                 this._updatePosition();
3910
3911                 this._container.style.visibility = '';
3912
3913                 this._adjustPan();
3914         },
3915
3916         _updateContent: function () {
3917                 if (!this._content) { return; }
3918
3919                 if (typeof this._content === 'string') {
3920                         this._contentNode.innerHTML = this._content;
3921                 } else {
3922                         while (this._contentNode.hasChildNodes()) {
3923                                 this._contentNode.removeChild(this._contentNode.firstChild);
3924                         }
3925                         this._contentNode.appendChild(this._content);
3926                 }
3927                 this.fire('contentupdate');
3928         },
3929
3930         _updateLayout: function () {
3931                 var container = this._contentNode,
3932                     style = container.style;
3933
3934                 style.width = '';
3935                 style.whiteSpace = 'nowrap';
3936
3937                 var width = container.offsetWidth;
3938                 width = Math.min(width, this.options.maxWidth);
3939                 width = Math.max(width, this.options.minWidth);
3940
3941                 style.width = (width + 1) + 'px';
3942                 style.whiteSpace = '';
3943
3944                 style.height = '';
3945
3946                 var height = container.offsetHeight,
3947                     maxHeight = this.options.maxHeight,
3948                     scrolledClass = 'leaflet-popup-scrolled';
3949
3950                 if (maxHeight && height > maxHeight) {
3951                         style.height = maxHeight + 'px';
3952                         L.DomUtil.addClass(container, scrolledClass);
3953                 } else {
3954                         L.DomUtil.removeClass(container, scrolledClass);
3955                 }
3956
3957                 this._containerWidth = this._container.offsetWidth;
3958         },
3959
3960         _updatePosition: function () {
3961                 if (!this._map) { return; }
3962
3963                 var pos = this._map.latLngToLayerPoint(this._latlng),
3964                     animated = this._animated,
3965                     offset = L.point(this.options.offset);
3966
3967                 if (animated) {
3968                         L.DomUtil.setPosition(this._container, pos);
3969                 }
3970
3971                 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
3972                 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
3973
3974                 // bottom position the popup in case the height of the popup changes (images loading etc)
3975                 this._container.style.bottom = this._containerBottom + 'px';
3976                 this._container.style.left = this._containerLeft + 'px';
3977         },
3978
3979         _zoomAnimation: function (opt) {
3980                 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3981
3982                 L.DomUtil.setPosition(this._container, pos);
3983         },
3984
3985         _adjustPan: function () {
3986                 if (!this.options.autoPan) { return; }
3987
3988                 var map = this._map,
3989                     containerHeight = this._container.offsetHeight,
3990                     containerWidth = this._containerWidth,
3991
3992                     layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
3993
3994                 if (this._animated) {
3995                         layerPos._add(L.DomUtil.getPosition(this._container));
3996                 }
3997
3998                 var containerPos = map.layerPointToContainerPoint(layerPos),
3999                     padding = L.point(this.options.autoPanPadding),
4000                     size = map.getSize(),
4001                     dx = 0,
4002                     dy = 0;
4003
4004                 if (containerPos.x + containerWidth > size.x) { // right
4005                         dx = containerPos.x + containerWidth - size.x + padding.x;
4006                 }
4007                 if (containerPos.x - dx < 0) { // left
4008                         dx = containerPos.x - padding.x;
4009                 }
4010                 if (containerPos.y + containerHeight > size.y) { // bottom
4011                         dy = containerPos.y + containerHeight - size.y + padding.y;
4012                 }
4013                 if (containerPos.y - dy < 0) { // top
4014                         dy = containerPos.y - padding.y;
4015                 }
4016
4017                 if (dx || dy) {
4018                         map
4019                             .fire('autopanstart')
4020                             .panBy([dx, dy]);
4021                 }
4022         },
4023
4024         _onCloseButtonClick: function (e) {
4025                 this._close();
4026                 L.DomEvent.stop(e);
4027         }
4028 });
4029
4030 L.popup = function (options, source) {
4031         return new L.Popup(options, source);
4032 };
4033
4034
4035 L.Map.include({
4036         openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
4037                 this.closePopup();
4038
4039                 if (!(popup instanceof L.Popup)) {
4040                         var content = popup;
4041
4042                         popup = new L.Popup(options)
4043                             .setLatLng(latlng)
4044                             .setContent(content);
4045                 }
4046                 popup._isOpen = true;
4047
4048                 this._popup = popup;
4049                 return this.addLayer(popup);
4050         },
4051
4052         closePopup: function (popup) {
4053                 if (!popup || popup === this._popup) {
4054                         popup = this._popup;
4055                         this._popup = null;
4056                 }
4057                 if (popup) {
4058                         this.removeLayer(popup);
4059                         popup._isOpen = false;
4060                 }
4061                 return this;
4062         }
4063 });
4064
4065
4066 /*
4067  * Popup extension to L.Marker, adding popup-related methods.
4068  */
4069
4070 L.Marker.include({
4071         openPopup: function () {
4072                 if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
4073                         this._popup.setLatLng(this._latlng);
4074                         this._map.openPopup(this._popup);
4075                 }
4076
4077                 return this;
4078         },
4079
4080         closePopup: function () {
4081                 if (this._popup) {
4082                         this._popup._close();
4083                 }
4084                 return this;
4085         },
4086
4087         togglePopup: function () {
4088                 if (this._popup) {
4089                         if (this._popup._isOpen) {
4090                                 this.closePopup();
4091                         } else {
4092                                 this.openPopup();
4093                         }
4094                 }
4095                 return this;
4096         },
4097
4098         bindPopup: function (content, options) {
4099                 var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
4100
4101                 anchor = anchor.add(L.Popup.prototype.options.offset);
4102
4103                 if (options && options.offset) {
4104                         anchor = anchor.add(options.offset);
4105                 }
4106
4107                 options = L.extend({offset: anchor}, options);
4108
4109                 if (!this._popup) {
4110                         this
4111                             .on('click', this.togglePopup, this)
4112                             .on('remove', this.closePopup, this)
4113                             .on('move', this._movePopup, this);
4114                 }
4115
4116                 if (content instanceof L.Popup) {
4117                         L.setOptions(content, options);
4118                         this._popup = content;
4119                 } else {
4120                         this._popup = new L.Popup(options, this)
4121                                 .setContent(content);
4122                 }
4123
4124                 return this;
4125         },
4126
4127         setPopupContent: function (content) {
4128                 if (this._popup) {
4129                         this._popup.setContent(content);
4130                 }
4131                 return this;
4132         },
4133
4134         unbindPopup: function () {
4135                 if (this._popup) {
4136                         this._popup = null;
4137                         this
4138                             .off('click', this.togglePopup)
4139                             .off('remove', this.closePopup)
4140                             .off('move', this._movePopup);
4141                 }
4142                 return this;
4143         },
4144
4145         _movePopup: function (e) {
4146                 this._popup.setLatLng(e.latlng);
4147         }
4148 });
4149
4150
4151 /*
4152  * L.LayerGroup is a class to combine several layers into one so that
4153  * you can manipulate the group (e.g. add/remove it) as one layer.
4154  */
4155
4156 L.LayerGroup = L.Class.extend({
4157         initialize: function (layers) {
4158                 this._layers = {};
4159
4160                 var i, len;
4161
4162                 if (layers) {
4163                         for (i = 0, len = layers.length; i < len; i++) {
4164                                 this.addLayer(layers[i]);
4165                         }
4166                 }
4167         },
4168
4169         addLayer: function (layer) {
4170                 var id = this.getLayerId(layer);
4171
4172                 this._layers[id] = layer;
4173
4174                 if (this._map) {
4175                         this._map.addLayer(layer);
4176                 }
4177
4178                 return this;
4179         },
4180
4181         removeLayer: function (layer) {
4182                 var id = layer in this._layers ? layer : this.getLayerId(layer);
4183
4184                 if (this._map && this._layers[id]) {
4185                         this._map.removeLayer(this._layers[id]);
4186                 }
4187
4188                 delete this._layers[id];
4189
4190                 return this;
4191         },
4192
4193         hasLayer: function (layer) {
4194                 if (!layer) { return false; }
4195
4196                 return (layer in this._layers || this.getLayerId(layer) in this._layers);
4197         },
4198
4199         clearLayers: function () {
4200                 this.eachLayer(this.removeLayer, this);
4201                 return this;
4202         },
4203
4204         invoke: function (methodName) {
4205                 var args = Array.prototype.slice.call(arguments, 1),
4206                     i, layer;
4207
4208                 for (i in this._layers) {
4209                         layer = this._layers[i];
4210
4211                         if (layer[methodName]) {
4212                                 layer[methodName].apply(layer, args);
4213                         }
4214                 }
4215
4216                 return this;
4217         },
4218
4219         onAdd: function (map) {
4220                 this._map = map;
4221                 this.eachLayer(map.addLayer, map);
4222         },
4223
4224         onRemove: function (map) {
4225                 this.eachLayer(map.removeLayer, map);
4226                 this._map = null;
4227         },
4228
4229         addTo: function (map) {
4230                 map.addLayer(this);
4231                 return this;
4232         },
4233
4234         eachLayer: function (method, context) {
4235                 for (var i in this._layers) {
4236                         method.call(context, this._layers[i]);
4237                 }
4238                 return this;
4239         },
4240
4241         getLayer: function (id) {
4242                 return this._layers[id];
4243         },
4244
4245         getLayers: function () {
4246                 var layers = [];
4247
4248                 for (var i in this._layers) {
4249                         layers.push(this._layers[i]);
4250                 }
4251                 return layers;
4252         },
4253
4254         setZIndex: function (zIndex) {
4255                 return this.invoke('setZIndex', zIndex);
4256         },
4257
4258         getLayerId: function (layer) {
4259                 return L.stamp(layer);
4260         }
4261 });
4262
4263 L.layerGroup = function (layers) {
4264         return new L.LayerGroup(layers);
4265 };
4266
4267
4268 /*
4269  * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
4270  * shared between a group of interactive layers (like vectors or markers).
4271  */
4272
4273 L.FeatureGroup = L.LayerGroup.extend({
4274         includes: L.Mixin.Events,
4275
4276         statics: {
4277                 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
4278         },
4279
4280         addLayer: function (layer) {
4281                 if (this.hasLayer(layer)) {
4282                         return this;
4283                 }
4284
4285                 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4286
4287                 L.LayerGroup.prototype.addLayer.call(this, layer);
4288
4289                 if (this._popupContent && layer.bindPopup) {
4290                         layer.bindPopup(this._popupContent, this._popupOptions);
4291                 }
4292
4293                 return this.fire('layeradd', {layer: layer});
4294         },
4295
4296         removeLayer: function (layer) {
4297                 if (!this.hasLayer(layer)) {
4298                         return this;
4299                 }
4300                 if (layer in this._layers) {
4301                         layer = this._layers[layer];
4302                 }
4303
4304                 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4305
4306                 L.LayerGroup.prototype.removeLayer.call(this, layer);
4307
4308                 if (this._popupContent) {
4309                         this.invoke('unbindPopup');
4310                 }
4311
4312                 return this.fire('layerremove', {layer: layer});
4313         },
4314
4315         bindPopup: function (content, options) {
4316                 this._popupContent = content;
4317                 this._popupOptions = options;
4318                 return this.invoke('bindPopup', content, options);
4319         },
4320
4321         setStyle: function (style) {
4322                 return this.invoke('setStyle', style);
4323         },
4324
4325         bringToFront: function () {
4326                 return this.invoke('bringToFront');
4327         },
4328
4329         bringToBack: function () {
4330                 return this.invoke('bringToBack');
4331         },
4332
4333         getBounds: function () {
4334                 var bounds = new L.LatLngBounds();
4335
4336                 this.eachLayer(function (layer) {
4337                         bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
4338                 });
4339
4340                 return bounds;
4341         },
4342
4343         _propagateEvent: function (e) {
4344                 if (!e.layer) {
4345                         e.layer = e.target;
4346                 }
4347                 e.target = this;
4348
4349                 this.fire(e.type, e);
4350         }
4351 });
4352
4353 L.featureGroup = function (layers) {
4354         return new L.FeatureGroup(layers);
4355 };
4356
4357
4358 /*
4359  * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
4360  */
4361
4362 L.Path = L.Class.extend({
4363         includes: [L.Mixin.Events],
4364
4365         statics: {
4366                 // how much to extend the clip area around the map view
4367                 // (relative to its size, e.g. 0.5 is half the screen in each direction)
4368                 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
4369                 CLIP_PADDING: (function () {
4370                         var max = L.Browser.mobile ? 1280 : 2000,
4371                             target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
4372                         return Math.max(0, Math.min(0.5, target));
4373                 })()
4374         },
4375
4376         options: {
4377                 stroke: true,
4378                 color: '#0033ff',
4379                 dashArray: null,
4380                 weight: 5,
4381                 opacity: 0.5,
4382
4383                 fill: false,
4384                 fillColor: null, //same as color by default
4385                 fillOpacity: 0.2,
4386
4387                 clickable: true
4388         },
4389
4390         initialize: function (options) {
4391                 L.setOptions(this, options);
4392         },
4393
4394         onAdd: function (map) {
4395                 this._map = map;
4396
4397                 if (!this._container) {
4398                         this._initElements();
4399                         this._initEvents();
4400                 }
4401
4402                 this.projectLatlngs();
4403                 this._updatePath();
4404
4405                 if (this._container) {
4406                         this._map._pathRoot.appendChild(this._container);
4407                 }
4408
4409                 this.fire('add');
4410
4411                 map.on({
4412                         'viewreset': this.projectLatlngs,
4413                         'moveend': this._updatePath
4414                 }, this);
4415         },
4416
4417         addTo: function (map) {
4418                 map.addLayer(this);
4419                 return this;
4420         },
4421
4422         onRemove: function (map) {
4423                 map._pathRoot.removeChild(this._container);
4424
4425                 // Need to fire remove event before we set _map to null as the event hooks might need the object
4426                 this.fire('remove');
4427                 this._map = null;
4428
4429                 if (L.Browser.vml) {
4430                         this._container = null;
4431                         this._stroke = null;
4432                         this._fill = null;
4433                 }
4434
4435                 map.off({
4436                         'viewreset': this.projectLatlngs,
4437                         'moveend': this._updatePath
4438                 }, this);
4439         },
4440
4441         projectLatlngs: function () {
4442                 // do all projection stuff here
4443         },
4444
4445         setStyle: function (style) {
4446                 L.setOptions(this, style);
4447
4448                 if (this._container) {
4449                         this._updateStyle();
4450                 }
4451
4452                 return this;
4453         },
4454
4455         redraw: function () {
4456                 if (this._map) {
4457                         this.projectLatlngs();
4458                         this._updatePath();
4459                 }
4460                 return this;
4461         }
4462 });
4463
4464 L.Map.include({
4465         _updatePathViewport: function () {
4466                 var p = L.Path.CLIP_PADDING,
4467                     size = this.getSize(),
4468                     panePos = L.DomUtil.getPosition(this._mapPane),
4469                     min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4470                     max = min.add(size.multiplyBy(1 + p * 2)._round());
4471
4472                 this._pathViewport = new L.Bounds(min, max);
4473         }
4474 });
4475
4476
4477 /*
4478  * Extends L.Path with SVG-specific rendering code.
4479  */
4480
4481 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4482
4483 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4484
4485 L.Path = L.Path.extend({
4486         statics: {
4487                 SVG: L.Browser.svg
4488         },
4489
4490         bringToFront: function () {
4491                 var root = this._map._pathRoot,
4492                     path = this._container;
4493
4494                 if (path && root.lastChild !== path) {
4495                         root.appendChild(path);
4496                 }
4497                 return this;
4498         },
4499
4500         bringToBack: function () {
4501                 var root = this._map._pathRoot,
4502                     path = this._container,
4503                     first = root.firstChild;
4504
4505                 if (path && first !== path) {
4506                         root.insertBefore(path, first);
4507                 }
4508                 return this;
4509         },
4510
4511         getPathString: function () {
4512                 // form path string here
4513         },
4514
4515         _createElement: function (name) {
4516                 return document.createElementNS(L.Path.SVG_NS, name);
4517         },
4518
4519         _initElements: function () {
4520                 this._map._initPathRoot();
4521                 this._initPath();
4522                 this._initStyle();
4523         },
4524
4525         _initPath: function () {
4526                 this._container = this._createElement('g');
4527
4528                 this._path = this._createElement('path');
4529                 this._container.appendChild(this._path);
4530         },
4531
4532         _initStyle: function () {
4533                 if (this.options.stroke) {
4534                         this._path.setAttribute('stroke-linejoin', 'round');
4535                         this._path.setAttribute('stroke-linecap', 'round');
4536                 }
4537                 if (this.options.fill) {
4538                         this._path.setAttribute('fill-rule', 'evenodd');
4539                 }
4540                 if (this.options.pointerEvents) {
4541                         this._path.setAttribute('pointer-events', this.options.pointerEvents);
4542                 }
4543                 if (!this.options.clickable && !this.options.pointerEvents) {
4544                         this._path.setAttribute('pointer-events', 'none');
4545                 }
4546                 this._updateStyle();
4547         },
4548
4549         _updateStyle: function () {
4550                 if (this.options.stroke) {
4551                         this._path.setAttribute('stroke', this.options.color);
4552                         this._path.setAttribute('stroke-opacity', this.options.opacity);
4553                         this._path.setAttribute('stroke-width', this.options.weight);
4554                         if (this.options.dashArray) {
4555                                 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4556                         } else {
4557                                 this._path.removeAttribute('stroke-dasharray');
4558                         }
4559                 } else {
4560                         this._path.setAttribute('stroke', 'none');
4561                 }
4562                 if (this.options.fill) {
4563                         this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4564                         this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4565                 } else {
4566                         this._path.setAttribute('fill', 'none');
4567                 }
4568         },
4569
4570         _updatePath: function () {
4571                 var str = this.getPathString();
4572                 if (!str) {
4573                         // fix webkit empty string parsing bug
4574                         str = 'M0 0';
4575                 }
4576                 this._path.setAttribute('d', str);
4577         },
4578
4579         // TODO remove duplication with L.Map
4580         _initEvents: function () {
4581                 if (this.options.clickable) {
4582                         if (L.Browser.svg || !L.Browser.vml) {
4583                                 this._path.setAttribute('class', 'leaflet-clickable');
4584                         }
4585
4586                         L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4587
4588                         var events = ['dblclick', 'mousedown', 'mouseover',
4589                                       'mouseout', 'mousemove', 'contextmenu'];
4590                         for (var i = 0; i < events.length; i++) {
4591                                 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4592                         }
4593                 }
4594         },
4595
4596         _onMouseClick: function (e) {
4597                 if (this._map.dragging && this._map.dragging.moved()) { return; }
4598
4599                 this._fireMouseEvent(e);
4600         },
4601
4602         _fireMouseEvent: function (e) {
4603                 if (!this.hasEventListeners(e.type)) { return; }
4604
4605                 var map = this._map,
4606                     containerPoint = map.mouseEventToContainerPoint(e),
4607                     layerPoint = map.containerPointToLayerPoint(containerPoint),
4608                     latlng = map.layerPointToLatLng(layerPoint);
4609
4610                 this.fire(e.type, {
4611                         latlng: latlng,
4612                         layerPoint: layerPoint,
4613                         containerPoint: containerPoint,
4614                         originalEvent: e
4615                 });
4616
4617                 if (e.type === 'contextmenu') {
4618                         L.DomEvent.preventDefault(e);
4619                 }
4620                 if (e.type !== 'mousemove') {
4621                         L.DomEvent.stopPropagation(e);
4622                 }
4623         }
4624 });
4625
4626 L.Map.include({
4627         _initPathRoot: function () {
4628                 if (!this._pathRoot) {
4629                         this._pathRoot = L.Path.prototype._createElement('svg');
4630                         this._panes.overlayPane.appendChild(this._pathRoot);
4631
4632                         if (this.options.zoomAnimation && L.Browser.any3d) {
4633                                 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
4634
4635                                 this.on({
4636                                         'zoomanim': this._animatePathZoom,
4637                                         'zoomend': this._endPathZoom
4638                                 });
4639                         } else {
4640                                 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
4641                         }
4642
4643                         this.on('moveend', this._updateSvgViewport);
4644                         this._updateSvgViewport();
4645                 }
4646         },
4647
4648         _animatePathZoom: function (e) {
4649                 var scale = this.getZoomScale(e.zoom),
4650                     offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4651
4652                 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4653                         L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4654
4655                 this._pathZooming = true;
4656         },
4657
4658         _endPathZoom: function () {
4659                 this._pathZooming = false;
4660         },
4661
4662         _updateSvgViewport: function () {
4663
4664                 if (this._pathZooming) {
4665                         // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4666                         // When the zoom animation ends we will be updated again anyway
4667                         // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4668                         return;
4669                 }
4670
4671                 this._updatePathViewport();
4672
4673                 var vp = this._pathViewport,
4674                     min = vp.min,
4675                     max = vp.max,
4676                     width = max.x - min.x,
4677                     height = max.y - min.y,
4678                     root = this._pathRoot,
4679                     pane = this._panes.overlayPane;
4680
4681                 // Hack to make flicker on drag end on mobile webkit less irritating
4682                 if (L.Browser.mobileWebkit) {
4683                         pane.removeChild(root);
4684                 }
4685
4686                 L.DomUtil.setPosition(root, min);
4687                 root.setAttribute('width', width);
4688                 root.setAttribute('height', height);
4689                 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4690
4691                 if (L.Browser.mobileWebkit) {
4692                         pane.appendChild(root);
4693                 }
4694         }
4695 });
4696
4697
4698 /*
4699  * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4700  */
4701
4702 L.Path.include({
4703
4704         bindPopup: function (content, options) {
4705
4706                 if (content instanceof L.Popup) {
4707                         this._popup = content;
4708                 } else {
4709                         if (!this._popup || options) {
4710                                 this._popup = new L.Popup(options, this);
4711                         }
4712                         this._popup.setContent(content);
4713                 }
4714
4715                 if (!this._popupHandlersAdded) {
4716                         this
4717                             .on('click', this._openPopup, this)
4718                             .on('remove', this.closePopup, this);
4719
4720                         this._popupHandlersAdded = true;
4721                 }
4722
4723                 return this;
4724         },
4725
4726         unbindPopup: function () {
4727                 if (this._popup) {
4728                         this._popup = null;
4729                         this
4730                             .off('click', this._openPopup)
4731                             .off('remove', this.closePopup);
4732
4733                         this._popupHandlersAdded = false;
4734                 }
4735                 return this;
4736         },
4737
4738         openPopup: function (latlng) {
4739
4740                 if (this._popup) {
4741                         // open the popup from one of the path's points if not specified
4742                         latlng = latlng || this._latlng ||
4743                                  this._latlngs[Math.floor(this._latlngs.length / 2)];
4744
4745                         this._openPopup({latlng: latlng});
4746                 }
4747
4748                 return this;
4749         },
4750
4751         closePopup: function () {
4752                 if (this._popup) {
4753                         this._popup._close();
4754                 }
4755                 return this;
4756         },
4757
4758         _openPopup: function (e) {
4759                 this._popup.setLatLng(e.latlng);
4760                 this._map.openPopup(this._popup);
4761         }
4762 });
4763
4764
4765 /*
4766  * Vector rendering for IE6-8 through VML.
4767  * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4768  */
4769
4770 L.Browser.vml = !L.Browser.svg && (function () {
4771         try {
4772                 var div = document.createElement('div');
4773                 div.innerHTML = '<v:shape adj="1"/>';
4774
4775                 var shape = div.firstChild;
4776                 shape.style.behavior = 'url(#default#VML)';
4777
4778                 return shape && (typeof shape.adj === 'object');
4779
4780         } catch (e) {
4781                 return false;
4782         }
4783 }());
4784
4785 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4786         statics: {
4787                 VML: true,
4788                 CLIP_PADDING: 0.02
4789         },
4790
4791         _createElement: (function () {
4792                 try {
4793                         document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4794                         return function (name) {
4795                                 return document.createElement('<lvml:' + name + ' class="lvml">');
4796                         };
4797                 } catch (e) {
4798                         return function (name) {
4799                                 return document.createElement(
4800                                         '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4801                         };
4802                 }
4803         }()),
4804
4805         _initPath: function () {
4806                 var container = this._container = this._createElement('shape');
4807                 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4808                 if (this.options.clickable) {
4809                         L.DomUtil.addClass(container, 'leaflet-clickable');
4810                 }
4811                 container.coordsize = '1 1';
4812
4813                 this._path = this._createElement('path');
4814                 container.appendChild(this._path);
4815
4816                 this._map._pathRoot.appendChild(container);
4817         },
4818
4819         _initStyle: function () {
4820                 this._updateStyle();
4821         },
4822
4823         _updateStyle: function () {
4824                 var stroke = this._stroke,
4825                     fill = this._fill,
4826                     options = this.options,
4827                     container = this._container;
4828
4829                 container.stroked = options.stroke;
4830                 container.filled = options.fill;
4831
4832                 if (options.stroke) {
4833                         if (!stroke) {
4834                                 stroke = this._stroke = this._createElement('stroke');
4835                                 stroke.endcap = 'round';
4836                                 container.appendChild(stroke);
4837                         }
4838                         stroke.weight = options.weight + 'px';
4839                         stroke.color = options.color;
4840                         stroke.opacity = options.opacity;
4841
4842                         if (options.dashArray) {
4843                                 stroke.dashStyle = options.dashArray instanceof Array ?
4844                                     options.dashArray.join(' ') :
4845                                     options.dashArray.replace(/( *, *)/g, ' ');
4846                         } else {
4847                                 stroke.dashStyle = '';
4848                         }
4849
4850                 } else if (stroke) {
4851                         container.removeChild(stroke);
4852                         this._stroke = null;
4853                 }
4854
4855                 if (options.fill) {
4856                         if (!fill) {
4857                                 fill = this._fill = this._createElement('fill');
4858                                 container.appendChild(fill);
4859                         }
4860                         fill.color = options.fillColor || options.color;
4861                         fill.opacity = options.fillOpacity;
4862
4863                 } else if (fill) {
4864                         container.removeChild(fill);
4865                         this._fill = null;
4866                 }
4867         },
4868
4869         _updatePath: function () {
4870                 var style = this._container.style;
4871
4872                 style.display = 'none';
4873                 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4874                 style.display = '';
4875         }
4876 });
4877
4878 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4879         _initPathRoot: function () {
4880                 if (this._pathRoot) { return; }
4881
4882                 var root = this._pathRoot = document.createElement('div');
4883                 root.className = 'leaflet-vml-container';
4884                 this._panes.overlayPane.appendChild(root);
4885
4886                 this.on('moveend', this._updatePathViewport);
4887                 this._updatePathViewport();
4888         }
4889 });
4890
4891
4892 /*
4893  * Vector rendering for all browsers that support canvas.
4894  */
4895
4896 L.Browser.canvas = (function () {
4897         return !!document.createElement('canvas').getContext;
4898 }());
4899
4900 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4901         statics: {
4902                 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4903                 CANVAS: true,
4904                 SVG: false
4905         },
4906
4907         redraw: function () {
4908                 if (this._map) {
4909                         this.projectLatlngs();
4910                         this._requestUpdate();
4911                 }
4912                 return this;
4913         },
4914
4915         setStyle: function (style) {
4916                 L.setOptions(this, style);
4917
4918                 if (this._map) {
4919                         this._updateStyle();
4920                         this._requestUpdate();
4921                 }
4922                 return this;
4923         },
4924
4925         onRemove: function (map) {
4926                 map
4927                     .off('viewreset', this.projectLatlngs, this)
4928                     .off('moveend', this._updatePath, this);
4929
4930                 if (this.options.clickable) {
4931                         this._map.off('click', this._onClick, this);
4932                         this._map.off('mousemove', this._onMouseMove, this);
4933                 }
4934
4935                 this._requestUpdate();
4936
4937                 this._map = null;
4938         },
4939
4940         _requestUpdate: function () {
4941                 if (this._map && !L.Path._updateRequest) {
4942                         L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4943                 }
4944         },
4945
4946         _fireMapMoveEnd: function () {
4947                 L.Path._updateRequest = null;
4948                 this.fire('moveend');
4949         },
4950
4951         _initElements: function () {
4952                 this._map._initPathRoot();
4953                 this._ctx = this._map._canvasCtx;
4954         },
4955
4956         _updateStyle: function () {
4957                 var options = this.options;
4958
4959                 if (options.stroke) {
4960                         this._ctx.lineWidth = options.weight;
4961                         this._ctx.strokeStyle = options.color;
4962                 }
4963                 if (options.fill) {
4964                         this._ctx.fillStyle = options.fillColor || options.color;
4965                 }
4966         },
4967
4968         _drawPath: function () {
4969                 var i, j, len, len2, point, drawMethod;
4970
4971                 this._ctx.beginPath();
4972
4973                 for (i = 0, len = this._parts.length; i < len; i++) {
4974                         for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4975                                 point = this._parts[i][j];
4976                                 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4977
4978                                 this._ctx[drawMethod](point.x, point.y);
4979                         }
4980                         // TODO refactor ugly hack
4981                         if (this instanceof L.Polygon) {
4982                                 this._ctx.closePath();
4983                         }
4984                 }
4985         },
4986
4987         _checkIfEmpty: function () {
4988                 return !this._parts.length;
4989         },
4990
4991         _updatePath: function () {
4992                 if (this._checkIfEmpty()) { return; }
4993
4994                 var ctx = this._ctx,
4995                     options = this.options;
4996
4997                 this._drawPath();
4998                 ctx.save();
4999                 this._updateStyle();
5000
5001                 if (options.fill) {
5002                         ctx.globalAlpha = options.fillOpacity;
5003                         ctx.fill();
5004                 }
5005
5006                 if (options.stroke) {
5007                         ctx.globalAlpha = options.opacity;
5008                         ctx.stroke();
5009                 }
5010
5011                 ctx.restore();
5012
5013                 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
5014         },
5015
5016         _initEvents: function () {
5017                 if (this.options.clickable) {
5018                         // TODO dblclick
5019                         this._map.on('mousemove', this._onMouseMove, this);
5020                         this._map.on('click', this._onClick, this);
5021                 }
5022         },
5023
5024         _onClick: function (e) {
5025                 if (this._containsPoint(e.layerPoint)) {
5026                         this.fire('click', e);
5027                 }
5028         },
5029
5030         _onMouseMove: function (e) {
5031                 if (!this._map || this._map._animatingZoom) { return; }
5032
5033                 // TODO don't do on each move
5034                 if (this._containsPoint(e.layerPoint)) {
5035                         this._ctx.canvas.style.cursor = 'pointer';
5036                         this._mouseInside = true;
5037                         this.fire('mouseover', e);
5038
5039                 } else if (this._mouseInside) {
5040                         this._ctx.canvas.style.cursor = '';
5041                         this._mouseInside = false;
5042                         this.fire('mouseout', e);
5043                 }
5044         }
5045 });
5046
5047 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
5048         _initPathRoot: function () {
5049                 var root = this._pathRoot,
5050                     ctx;
5051
5052                 if (!root) {
5053                         root = this._pathRoot = document.createElement('canvas');
5054                         root.style.position = 'absolute';
5055                         ctx = this._canvasCtx = root.getContext('2d');
5056
5057                         ctx.lineCap = 'round';
5058                         ctx.lineJoin = 'round';
5059
5060                         this._panes.overlayPane.appendChild(root);
5061
5062                         if (this.options.zoomAnimation) {
5063                                 this._pathRoot.className = 'leaflet-zoom-animated';
5064                                 this.on('zoomanim', this._animatePathZoom);
5065                                 this.on('zoomend', this._endPathZoom);
5066                         }
5067                         this.on('moveend', this._updateCanvasViewport);
5068                         this._updateCanvasViewport();
5069                 }
5070         },
5071
5072         _updateCanvasViewport: function () {
5073                 // don't redraw while zooming. See _updateSvgViewport for more details
5074                 if (this._pathZooming) { return; }
5075                 this._updatePathViewport();
5076
5077                 var vp = this._pathViewport,
5078                     min = vp.min,
5079                     size = vp.max.subtract(min),
5080                     root = this._pathRoot;
5081
5082                 //TODO check if this works properly on mobile webkit
5083                 L.DomUtil.setPosition(root, min);
5084                 root.width = size.x;
5085                 root.height = size.y;
5086                 root.getContext('2d').translate(-min.x, -min.y);
5087         }
5088 });
5089
5090
5091 /*
5092  * L.LineUtil contains different utility functions for line segments
5093  * and polylines (clipping, simplification, distances, etc.)
5094  */
5095
5096 /*jshint bitwise:false */ // allow bitwise oprations for this file
5097
5098 L.LineUtil = {
5099
5100         // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
5101         // Improves rendering performance dramatically by lessening the number of points to draw.
5102
5103         simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
5104                 if (!tolerance || !points.length) {
5105                         return points.slice();
5106                 }
5107
5108                 var sqTolerance = tolerance * tolerance;
5109
5110                 // stage 1: vertex reduction
5111                 points = this._reducePoints(points, sqTolerance);
5112
5113                 // stage 2: Douglas-Peucker simplification
5114                 points = this._simplifyDP(points, sqTolerance);
5115
5116                 return points;
5117         },
5118
5119         // distance from a point to a segment between two points
5120         pointToSegmentDistance:  function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5121                 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
5122         },
5123
5124         closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5125                 return this._sqClosestPointOnSegment(p, p1, p2);
5126         },
5127
5128         // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
5129         _simplifyDP: function (points, sqTolerance) {
5130
5131                 var len = points.length,
5132                     ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
5133                     markers = new ArrayConstructor(len);
5134
5135                 markers[0] = markers[len - 1] = 1;
5136
5137                 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
5138
5139                 var i,
5140                     newPoints = [];
5141
5142                 for (i = 0; i < len; i++) {
5143                         if (markers[i]) {
5144                                 newPoints.push(points[i]);
5145                         }
5146                 }
5147
5148                 return newPoints;
5149         },
5150
5151         _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
5152
5153                 var maxSqDist = 0,
5154                     index, i, sqDist;
5155
5156                 for (i = first + 1; i <= last - 1; i++) {
5157                         sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
5158
5159                         if (sqDist > maxSqDist) {
5160                                 index = i;
5161                                 maxSqDist = sqDist;
5162                         }
5163                 }
5164
5165                 if (maxSqDist > sqTolerance) {
5166                         markers[index] = 1;
5167
5168                         this._simplifyDPStep(points, markers, sqTolerance, first, index);
5169                         this._simplifyDPStep(points, markers, sqTolerance, index, last);
5170                 }
5171         },
5172
5173         // reduce points that are too close to each other to a single point
5174         _reducePoints: function (points, sqTolerance) {
5175                 var reducedPoints = [points[0]];
5176
5177                 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
5178                         if (this._sqDist(points[i], points[prev]) > sqTolerance) {
5179                                 reducedPoints.push(points[i]);
5180                                 prev = i;
5181                         }
5182                 }
5183                 if (prev < len - 1) {
5184                         reducedPoints.push(points[len - 1]);
5185                 }
5186                 return reducedPoints;
5187         },
5188
5189         // Cohen-Sutherland line clipping algorithm.
5190         // Used to avoid rendering parts of a polyline that are not currently visible.
5191
5192         clipSegment: function (a, b, bounds, useLastCode) {
5193                 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
5194                     codeB = this._getBitCode(b, bounds),
5195
5196                     codeOut, p, newCode;
5197
5198                 // save 2nd code to avoid calculating it on the next segment
5199                 this._lastCode = codeB;
5200
5201                 while (true) {
5202                         // if a,b is inside the clip window (trivial accept)
5203                         if (!(codeA | codeB)) {
5204                                 return [a, b];
5205                         // if a,b is outside the clip window (trivial reject)
5206                         } else if (codeA & codeB) {
5207                                 return false;
5208                         // other cases
5209                         } else {
5210                                 codeOut = codeA || codeB;
5211                                 p = this._getEdgeIntersection(a, b, codeOut, bounds);
5212                                 newCode = this._getBitCode(p, bounds);
5213
5214                                 if (codeOut === codeA) {
5215                                         a = p;
5216                                         codeA = newCode;
5217                                 } else {
5218                                         b = p;
5219                                         codeB = newCode;
5220                                 }
5221                         }
5222                 }
5223         },
5224
5225         _getEdgeIntersection: function (a, b, code, bounds) {
5226                 var dx = b.x - a.x,
5227                     dy = b.y - a.y,
5228                     min = bounds.min,
5229                     max = bounds.max;
5230
5231                 if (code & 8) { // top
5232                         return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
5233                 } else if (code & 4) { // bottom
5234                         return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
5235                 } else if (code & 2) { // right
5236                         return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
5237                 } else if (code & 1) { // left
5238                         return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
5239                 }
5240         },
5241
5242         _getBitCode: function (/*Point*/ p, bounds) {
5243                 var code = 0;
5244
5245                 if (p.x < bounds.min.x) { // left
5246                         code |= 1;
5247                 } else if (p.x > bounds.max.x) { // right
5248                         code |= 2;
5249                 }
5250                 if (p.y < bounds.min.y) { // bottom
5251                         code |= 4;
5252                 } else if (p.y > bounds.max.y) { // top
5253                         code |= 8;
5254                 }
5255
5256                 return code;
5257         },
5258
5259         // square distance (to avoid unnecessary Math.sqrt calls)
5260         _sqDist: function (p1, p2) {
5261                 var dx = p2.x - p1.x,
5262                     dy = p2.y - p1.y;
5263                 return dx * dx + dy * dy;
5264         },
5265
5266         // return closest point on segment or distance to that point
5267         _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
5268                 var x = p1.x,
5269                     y = p1.y,
5270                     dx = p2.x - x,
5271                     dy = p2.y - y,
5272                     dot = dx * dx + dy * dy,
5273                     t;
5274
5275                 if (dot > 0) {
5276                         t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
5277
5278                         if (t > 1) {
5279                                 x = p2.x;
5280                                 y = p2.y;
5281                         } else if (t > 0) {
5282                                 x += dx * t;
5283                                 y += dy * t;
5284                         }
5285                 }
5286
5287                 dx = p.x - x;
5288                 dy = p.y - y;
5289
5290                 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
5291         }
5292 };
5293
5294
5295 /*
5296  * L.Polyline is used to display polylines on a map.
5297  */
5298
5299 L.Polyline = L.Path.extend({
5300         initialize: function (latlngs, options) {
5301                 L.Path.prototype.initialize.call(this, options);
5302
5303                 this._latlngs = this._convertLatLngs(latlngs);
5304         },
5305
5306         options: {
5307                 // how much to simplify the polyline on each zoom level
5308                 // more = better performance and smoother look, less = more accurate
5309                 smoothFactor: 1.0,
5310                 noClip: false
5311         },
5312
5313         projectLatlngs: function () {
5314                 this._originalPoints = [];
5315
5316                 for (var i = 0, len = this._latlngs.length; i < len; i++) {
5317                         this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
5318                 }
5319         },
5320
5321         getPathString: function () {
5322                 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
5323                         str += this._getPathPartStr(this._parts[i]);
5324                 }
5325                 return str;
5326         },
5327
5328         getLatLngs: function () {
5329                 return this._latlngs;
5330         },
5331
5332         setLatLngs: function (latlngs) {
5333                 this._latlngs = this._convertLatLngs(latlngs);
5334                 return this.redraw();
5335         },
5336
5337         addLatLng: function (latlng) {
5338                 this._latlngs.push(L.latLng(latlng));
5339                 return this.redraw();
5340         },
5341
5342         spliceLatLngs: function () { // (Number index, Number howMany)
5343                 var removed = [].splice.apply(this._latlngs, arguments);
5344                 this._convertLatLngs(this._latlngs, true);
5345                 this.redraw();
5346                 return removed;
5347         },
5348
5349         closestLayerPoint: function (p) {
5350                 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
5351
5352                 for (var j = 0, jLen = parts.length; j < jLen; j++) {
5353                         var points = parts[j];
5354                         for (var i = 1, len = points.length; i < len; i++) {
5355                                 p1 = points[i - 1];
5356                                 p2 = points[i];
5357                                 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
5358                                 if (sqDist < minDistance) {
5359                                         minDistance = sqDist;
5360                                         minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
5361                                 }
5362                         }
5363                 }
5364                 if (minPoint) {
5365                         minPoint.distance = Math.sqrt(minDistance);
5366                 }
5367                 return minPoint;
5368         },
5369
5370         getBounds: function () {
5371                 return new L.LatLngBounds(this.getLatLngs());
5372         },
5373
5374         _convertLatLngs: function (latlngs, overwrite) {
5375                 var i, len, target = overwrite ? latlngs : [];
5376
5377                 for (i = 0, len = latlngs.length; i < len; i++) {
5378                         if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
5379                                 return;
5380                         }
5381                         target[i] = L.latLng(latlngs[i]);
5382                 }
5383                 return target;
5384         },
5385
5386         _initEvents: function () {
5387                 L.Path.prototype._initEvents.call(this);
5388         },
5389
5390         _getPathPartStr: function (points) {
5391                 var round = L.Path.VML;
5392
5393                 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
5394                         p = points[j];
5395                         if (round) {
5396                                 p._round();
5397                         }
5398                         str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
5399                 }
5400                 return str;
5401         },
5402
5403         _clipPoints: function () {
5404                 var points = this._originalPoints,
5405                     len = points.length,
5406                     i, k, segment;
5407
5408                 if (this.options.noClip) {
5409                         this._parts = [points];
5410                         return;
5411                 }
5412
5413                 this._parts = [];
5414
5415                 var parts = this._parts,
5416                     vp = this._map._pathViewport,
5417                     lu = L.LineUtil;
5418
5419                 for (i = 0, k = 0; i < len - 1; i++) {
5420                         segment = lu.clipSegment(points[i], points[i + 1], vp, i);
5421                         if (!segment) {
5422                                 continue;
5423                         }
5424
5425                         parts[k] = parts[k] || [];
5426                         parts[k].push(segment[0]);
5427
5428                         // if segment goes out of screen, or it's the last one, it's the end of the line part
5429                         if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
5430                                 parts[k].push(segment[1]);
5431                                 k++;
5432                         }
5433                 }
5434         },
5435
5436         // simplify each clipped part of the polyline
5437         _simplifyPoints: function () {
5438                 var parts = this._parts,
5439                     lu = L.LineUtil;
5440
5441                 for (var i = 0, len = parts.length; i < len; i++) {
5442                         parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
5443                 }
5444         },
5445
5446         _updatePath: function () {
5447                 if (!this._map) { return; }
5448
5449                 this._clipPoints();
5450                 this._simplifyPoints();
5451
5452                 L.Path.prototype._updatePath.call(this);
5453         }
5454 });
5455
5456 L.polyline = function (latlngs, options) {
5457         return new L.Polyline(latlngs, options);
5458 };
5459
5460
5461 /*
5462  * L.PolyUtil contains utility functions for polygons (clipping, etc.).
5463  */
5464
5465 /*jshint bitwise:false */ // allow bitwise operations here
5466
5467 L.PolyUtil = {};
5468
5469 /*
5470  * Sutherland-Hodgeman polygon clipping algorithm.
5471  * Used to avoid rendering parts of a polygon that are not currently visible.
5472  */
5473 L.PolyUtil.clipPolygon = function (points, bounds) {
5474         var clippedPoints,
5475             edges = [1, 4, 2, 8],
5476             i, j, k,
5477             a, b,
5478             len, edge, p,
5479             lu = L.LineUtil;
5480
5481         for (i = 0, len = points.length; i < len; i++) {
5482                 points[i]._code = lu._getBitCode(points[i], bounds);
5483         }
5484
5485         // for each edge (left, bottom, right, top)
5486         for (k = 0; k < 4; k++) {
5487                 edge = edges[k];
5488                 clippedPoints = [];
5489
5490                 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5491                         a = points[i];
5492                         b = points[j];
5493
5494                         // if a is inside the clip window
5495                         if (!(a._code & edge)) {
5496                                 // if b is outside the clip window (a->b goes out of screen)
5497                                 if (b._code & edge) {
5498                                         p = lu._getEdgeIntersection(b, a, edge, bounds);
5499                                         p._code = lu._getBitCode(p, bounds);
5500                                         clippedPoints.push(p);
5501                                 }
5502                                 clippedPoints.push(a);
5503
5504                         // else if b is inside the clip window (a->b enters the screen)
5505                         } else if (!(b._code & edge)) {
5506                                 p = lu._getEdgeIntersection(b, a, edge, bounds);
5507                                 p._code = lu._getBitCode(p, bounds);
5508                                 clippedPoints.push(p);
5509                         }
5510                 }
5511                 points = clippedPoints;
5512         }
5513
5514         return points;
5515 };
5516
5517
5518 /*
5519  * L.Polygon is used to display polygons on a map.
5520  */
5521
5522 L.Polygon = L.Polyline.extend({
5523         options: {
5524                 fill: true
5525         },
5526
5527         initialize: function (latlngs, options) {
5528                 var i, len, hole;
5529
5530                 L.Polyline.prototype.initialize.call(this, latlngs, options);
5531
5532                 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5533                         this._latlngs = this._convertLatLngs(latlngs[0]);
5534                         this._holes = latlngs.slice(1);
5535
5536                         for (i = 0, len = this._holes.length; i < len; i++) {
5537                                 hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
5538                                 if (hole[0].equals(hole[hole.length - 1])) {
5539                                         hole.pop();
5540                                 }
5541                         }
5542                 }
5543
5544                 // filter out last point if its equal to the first one
5545                 latlngs = this._latlngs;
5546
5547                 if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
5548                         latlngs.pop();
5549                 }
5550         },
5551
5552         projectLatlngs: function () {
5553                 L.Polyline.prototype.projectLatlngs.call(this);
5554
5555                 // project polygon holes points
5556                 // TODO move this logic to Polyline to get rid of duplication
5557                 this._holePoints = [];
5558
5559                 if (!this._holes) { return; }
5560
5561                 var i, j, len, len2;
5562
5563                 for (i = 0, len = this._holes.length; i < len; i++) {
5564                         this._holePoints[i] = [];
5565
5566                         for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5567                                 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5568                         }
5569                 }
5570         },
5571
5572         _clipPoints: function () {
5573                 var points = this._originalPoints,
5574                     newParts = [];
5575
5576                 this._parts = [points].concat(this._holePoints);
5577
5578                 if (this.options.noClip) { return; }
5579
5580                 for (var i = 0, len = this._parts.length; i < len; i++) {
5581                         var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5582                         if (clipped.length) {
5583                                 newParts.push(clipped);
5584                         }
5585                 }
5586
5587                 this._parts = newParts;
5588         },
5589
5590         _getPathPartStr: function (points) {
5591                 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5592                 return str + (L.Browser.svg ? 'z' : 'x');
5593         }
5594 });
5595
5596 L.polygon = function (latlngs, options) {
5597         return new L.Polygon(latlngs, options);
5598 };
5599
5600
5601 /*
5602  * Contains L.MultiPolyline and L.MultiPolygon layers.
5603  */
5604
5605 (function () {
5606         function createMulti(Klass) {
5607
5608                 return L.FeatureGroup.extend({
5609
5610                         initialize: function (latlngs, options) {
5611                                 this._layers = {};
5612                                 this._options = options;
5613                                 this.setLatLngs(latlngs);
5614                         },
5615
5616                         setLatLngs: function (latlngs) {
5617                                 var i = 0,
5618                                     len = latlngs.length;
5619
5620                                 this.eachLayer(function (layer) {
5621                                         if (i < len) {
5622                                                 layer.setLatLngs(latlngs[i++]);
5623                                         } else {
5624                                                 this.removeLayer(layer);
5625                                         }
5626                                 }, this);
5627
5628                                 while (i < len) {
5629                                         this.addLayer(new Klass(latlngs[i++], this._options));
5630                                 }
5631
5632                                 return this;
5633                         },
5634
5635                         getLatLngs: function () {
5636                                 var latlngs = [];
5637
5638                                 this.eachLayer(function (layer) {
5639                                         latlngs.push(layer.getLatLngs());
5640                                 });
5641
5642                                 return latlngs;
5643                         }
5644                 });
5645         }
5646
5647         L.MultiPolyline = createMulti(L.Polyline);
5648         L.MultiPolygon = createMulti(L.Polygon);
5649
5650         L.multiPolyline = function (latlngs, options) {
5651                 return new L.MultiPolyline(latlngs, options);
5652         };
5653
5654         L.multiPolygon = function (latlngs, options) {
5655                 return new L.MultiPolygon(latlngs, options);
5656         };
5657 }());
5658
5659
5660 /*
5661  * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5662  */
5663
5664 L.Rectangle = L.Polygon.extend({
5665         initialize: function (latLngBounds, options) {
5666                 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5667         },
5668
5669         setBounds: function (latLngBounds) {
5670                 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5671         },
5672
5673         _boundsToLatLngs: function (latLngBounds) {
5674                 latLngBounds = L.latLngBounds(latLngBounds);
5675                 return [
5676                         latLngBounds.getSouthWest(),
5677                         latLngBounds.getNorthWest(),
5678                         latLngBounds.getNorthEast(),
5679                         latLngBounds.getSouthEast()
5680                 ];
5681         }
5682 });
5683
5684 L.rectangle = function (latLngBounds, options) {
5685         return new L.Rectangle(latLngBounds, options);
5686 };
5687
5688
5689 /*
5690  * L.Circle is a circle overlay (with a certain radius in meters).
5691  */
5692
5693 L.Circle = L.Path.extend({
5694         initialize: function (latlng, radius, options) {
5695                 L.Path.prototype.initialize.call(this, options);
5696
5697                 this._latlng = L.latLng(latlng);
5698                 this._mRadius = radius;
5699         },
5700
5701         options: {
5702                 fill: true
5703         },
5704
5705         setLatLng: function (latlng) {
5706                 this._latlng = L.latLng(latlng);
5707                 return this.redraw();
5708         },
5709
5710         setRadius: function (radius) {
5711                 this._mRadius = radius;
5712                 return this.redraw();
5713         },
5714
5715         projectLatlngs: function () {
5716                 var lngRadius = this._getLngRadius(),
5717                     latlng = this._latlng,
5718                     pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
5719
5720                 this._point = this._map.latLngToLayerPoint(latlng);
5721                 this._radius = Math.max(this._point.x - pointLeft.x, 1);
5722         },
5723
5724         getBounds: function () {
5725                 var lngRadius = this._getLngRadius(),
5726                     latRadius = (this._mRadius / 40075017) * 360,
5727                     latlng = this._latlng;
5728
5729                 return new L.LatLngBounds(
5730                         [latlng.lat - latRadius, latlng.lng - lngRadius],
5731                         [latlng.lat + latRadius, latlng.lng + lngRadius]);
5732         },
5733
5734         getLatLng: function () {
5735                 return this._latlng;
5736         },
5737
5738         getPathString: function () {
5739                 var p = this._point,
5740                     r = this._radius;
5741
5742                 if (this._checkIfEmpty()) {
5743                         return '';
5744                 }
5745
5746                 if (L.Browser.svg) {
5747                         return 'M' + p.x + ',' + (p.y - r) +
5748                                'A' + r + ',' + r + ',0,1,1,' +
5749                                (p.x - 0.1) + ',' + (p.y - r) + ' z';
5750                 } else {
5751                         p._round();
5752                         r = Math.round(r);
5753                         return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
5754                 }
5755         },
5756
5757         getRadius: function () {
5758                 return this._mRadius;
5759         },
5760
5761         // TODO Earth hardcoded, move into projection code!
5762
5763         _getLatRadius: function () {
5764                 return (this._mRadius / 40075017) * 360;
5765         },
5766
5767         _getLngRadius: function () {
5768                 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5769         },
5770
5771         _checkIfEmpty: function () {
5772                 if (!this._map) {
5773                         return false;
5774                 }
5775                 var vp = this._map._pathViewport,
5776                     r = this._radius,
5777                     p = this._point;
5778
5779                 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5780                        p.x + r < vp.min.x || p.y + r < vp.min.y;
5781         }
5782 });
5783
5784 L.circle = function (latlng, radius, options) {
5785         return new L.Circle(latlng, radius, options);
5786 };
5787
5788
5789 /*
5790  * L.CircleMarker is a circle overlay with a permanent pixel radius.
5791  */
5792
5793 L.CircleMarker = L.Circle.extend({
5794         options: {
5795                 radius: 10,
5796                 weight: 2
5797         },
5798
5799         initialize: function (latlng, options) {
5800                 L.Circle.prototype.initialize.call(this, latlng, null, options);
5801                 this._radius = this.options.radius;
5802         },
5803
5804         projectLatlngs: function () {
5805                 this._point = this._map.latLngToLayerPoint(this._latlng);
5806         },
5807
5808         _updateStyle : function () {
5809                 L.Circle.prototype._updateStyle.call(this);
5810                 this.setRadius(this.options.radius);
5811         },
5812
5813         setRadius: function (radius) {
5814                 this.options.radius = this._radius = radius;
5815                 return this.redraw();
5816         }
5817 });
5818
5819 L.circleMarker = function (latlng, options) {
5820         return new L.CircleMarker(latlng, options);
5821 };
5822
5823
5824 /*
5825  * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
5826  */
5827
5828 L.Polyline.include(!L.Path.CANVAS ? {} : {
5829         _containsPoint: function (p, closed) {
5830                 var i, j, k, len, len2, dist, part,
5831                     w = this.options.weight / 2;
5832
5833                 if (L.Browser.touch) {
5834                         w += 10; // polyline click tolerance on touch devices
5835                 }
5836
5837                 for (i = 0, len = this._parts.length; i < len; i++) {
5838                         part = this._parts[i];
5839                         for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5840                                 if (!closed && (j === 0)) {
5841                                         continue;
5842                                 }
5843
5844                                 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5845
5846                                 if (dist <= w) {
5847                                         return true;
5848                                 }
5849                         }
5850                 }
5851                 return false;
5852         }
5853 });
5854
5855
5856 /*
5857  * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
5858  */
5859
5860 L.Polygon.include(!L.Path.CANVAS ? {} : {
5861         _containsPoint: function (p) {
5862                 var inside = false,
5863                     part, p1, p2,
5864                     i, j, k,
5865                     len, len2;
5866
5867                 // TODO optimization: check if within bounds first
5868
5869                 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5870                         // click on polygon border
5871                         return true;
5872                 }
5873
5874                 // ray casting algorithm for detecting if point is in polygon
5875
5876                 for (i = 0, len = this._parts.length; i < len; i++) {
5877                         part = this._parts[i];
5878
5879                         for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5880                                 p1 = part[j];
5881                                 p2 = part[k];
5882
5883                                 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5884                                                 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5885                                         inside = !inside;
5886                                 }
5887                         }
5888                 }
5889
5890                 return inside;
5891         }
5892 });
5893
5894
5895 /*
5896  * Extends L.Circle with Canvas-specific code.
5897  */
5898
5899 L.Circle.include(!L.Path.CANVAS ? {} : {
5900         _drawPath: function () {
5901                 var p = this._point;
5902                 this._ctx.beginPath();
5903                 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5904         },
5905
5906         _containsPoint: function (p) {
5907                 var center = this._point,
5908                     w2 = this.options.stroke ? this.options.weight / 2 : 0;
5909
5910                 return (p.distanceTo(center) <= this._radius + w2);
5911         }
5912 });
5913
5914
5915 /*
5916  * CircleMarker canvas specific drawing parts.
5917  */
5918
5919 L.CircleMarker.include(!L.Path.CANVAS ? {} : {
5920         _updateStyle: function () {
5921                 L.Path.prototype._updateStyle.call(this);
5922         }
5923 });
5924
5925
5926 /*
5927  * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
5928  */
5929
5930 L.GeoJSON = L.FeatureGroup.extend({
5931
5932         initialize: function (geojson, options) {
5933                 L.setOptions(this, options);
5934
5935                 this._layers = {};
5936
5937                 if (geojson) {
5938                         this.addData(geojson);
5939                 }
5940         },
5941
5942         addData: function (geojson) {
5943                 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
5944                     i, len, feature;
5945
5946                 if (features) {
5947                         for (i = 0, len = features.length; i < len; i++) {
5948                                 // Only add this if geometry or geometries are set and not null
5949                                 feature = features[i];
5950                                 if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
5951                                         this.addData(features[i]);
5952                                 }
5953                         }
5954                         return this;
5955                 }
5956
5957                 var options = this.options;
5958
5959                 if (options.filter && !options.filter(geojson)) { return; }
5960
5961                 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng);
5962                 layer.feature = L.GeoJSON.asFeature(geojson);
5963
5964                 layer.defaultOptions = layer.options;
5965                 this.resetStyle(layer);
5966
5967                 if (options.onEachFeature) {
5968                         options.onEachFeature(geojson, layer);
5969                 }
5970
5971                 return this.addLayer(layer);
5972         },
5973
5974         resetStyle: function (layer) {
5975                 var style = this.options.style;
5976                 if (style) {
5977                         // reset any custom styles
5978                         L.Util.extend(layer.options, layer.defaultOptions);
5979
5980                         this._setLayerStyle(layer, style);
5981                 }
5982         },
5983
5984         setStyle: function (style) {
5985                 this.eachLayer(function (layer) {
5986                         this._setLayerStyle(layer, style);
5987                 }, this);
5988         },
5989
5990         _setLayerStyle: function (layer, style) {
5991                 if (typeof style === 'function') {
5992                         style = style(layer.feature);
5993                 }
5994                 if (layer.setStyle) {
5995                         layer.setStyle(style);
5996                 }
5997         }
5998 });
5999
6000 L.extend(L.GeoJSON, {
6001         geometryToLayer: function (geojson, pointToLayer, coordsToLatLng) {
6002                 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
6003                     coords = geometry.coordinates,
6004                     layers = [],
6005                     latlng, latlngs, i, len, layer;
6006
6007                 coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
6008
6009                 switch (geometry.type) {
6010                 case 'Point':
6011                         latlng = coordsToLatLng(coords);
6012                         return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6013
6014                 case 'MultiPoint':
6015                         for (i = 0, len = coords.length; i < len; i++) {
6016                                 latlng = coordsToLatLng(coords[i]);
6017                                 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6018                                 layers.push(layer);
6019                         }
6020                         return new L.FeatureGroup(layers);
6021
6022                 case 'LineString':
6023                         latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
6024                         return new L.Polyline(latlngs);
6025
6026                 case 'Polygon':
6027                         latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6028                         return new L.Polygon(latlngs);
6029
6030                 case 'MultiLineString':
6031                         latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6032                         return new L.MultiPolyline(latlngs);
6033
6034                 case 'MultiPolygon':
6035                         latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
6036                         return new L.MultiPolygon(latlngs);
6037
6038                 case 'GeometryCollection':
6039                         for (i = 0, len = geometry.geometries.length; i < len; i++) {
6040
6041                                 layer = this.geometryToLayer({
6042                                         geometry: geometry.geometries[i],
6043                                         type: 'Feature',
6044                                         properties: geojson.properties
6045                                 }, pointToLayer, coordsToLatLng);
6046
6047                                 layers.push(layer);
6048                         }
6049                         return new L.FeatureGroup(layers);
6050
6051                 default:
6052                         throw new Error('Invalid GeoJSON object.');
6053                 }
6054         },
6055
6056         coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
6057                 return new L.LatLng(coords[1], coords[0]);
6058         },
6059
6060         coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
6061                 var latlng, i, len,
6062                     latlngs = [];
6063
6064                 for (i = 0, len = coords.length; i < len; i++) {
6065                         latlng = levelsDeep ?
6066                                 this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
6067                                 (coordsToLatLng || this.coordsToLatLng)(coords[i]);
6068
6069                         latlngs.push(latlng);
6070                 }
6071
6072                 return latlngs;
6073         },
6074
6075         latLngToCoords: function (latLng) {
6076                 return [latLng.lng, latLng.lat];
6077         },
6078
6079         latLngsToCoords: function (latLngs) {
6080                 var coords = [];
6081
6082                 for (var i = 0, len = latLngs.length; i < len; i++) {
6083                         coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
6084                 }
6085
6086                 return coords;
6087         },
6088
6089         getFeature: function (layer, newGeometry) {
6090                 return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
6091         },
6092
6093         asFeature: function (geoJSON) {
6094                 if (geoJSON.type === 'Feature') {
6095                         return geoJSON;
6096                 }
6097
6098                 return {
6099                         type: 'Feature',
6100                         properties: {},
6101                         geometry: geoJSON
6102                 };
6103         }
6104 });
6105
6106 var PointToGeoJSON = {
6107         toGeoJSON: function () {
6108                 return L.GeoJSON.getFeature(this, {
6109                         type: 'Point',
6110                         coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
6111                 });
6112         }
6113 };
6114
6115 L.Marker.include(PointToGeoJSON);
6116 L.Circle.include(PointToGeoJSON);
6117 L.CircleMarker.include(PointToGeoJSON);
6118
6119 L.Polyline.include({
6120         toGeoJSON: function () {
6121                 return L.GeoJSON.getFeature(this, {
6122                         type: 'LineString',
6123                         coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
6124                 });
6125         }
6126 });
6127
6128 L.Polygon.include({
6129         toGeoJSON: function () {
6130                 var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
6131                     i, len, hole;
6132
6133                 coords[0].push(coords[0][0]);
6134
6135                 if (this._holes) {
6136                         for (i = 0, len = this._holes.length; i < len; i++) {
6137                                 hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
6138                                 hole.push(hole[0]);
6139                                 coords.push(hole);
6140                         }
6141                 }
6142
6143                 return L.GeoJSON.getFeature(this, {
6144                         type: 'Polygon',
6145                         coordinates: coords
6146                 });
6147         }
6148 });
6149
6150 (function () {
6151         function includeMulti(Klass, type) {
6152                 Klass.include({
6153                         toGeoJSON: function () {
6154                                 var coords = [];
6155
6156                                 this.eachLayer(function (layer) {
6157                                         coords.push(layer.toGeoJSON().geometry.coordinates);
6158                                 });
6159
6160                                 return L.GeoJSON.getFeature(this, {
6161                                         type: type,
6162                                         coordinates: coords
6163                                 });
6164                         }
6165                 });
6166         }
6167
6168         includeMulti(L.MultiPolyline, 'MultiLineString');
6169         includeMulti(L.MultiPolygon, 'MultiPolygon');
6170 }());
6171
6172 L.LayerGroup.include({
6173         toGeoJSON: function () {
6174                 var features = [];
6175
6176                 this.eachLayer(function (layer) {
6177                         if (layer.toGeoJSON) {
6178                                 features.push(L.GeoJSON.asFeature(layer.toGeoJSON()));
6179                         }
6180                 });
6181
6182                 return {
6183                         type: 'FeatureCollection',
6184                         features: features
6185                 };
6186         }
6187 });
6188
6189 L.geoJson = function (geojson, options) {
6190         return new L.GeoJSON(geojson, options);
6191 };
6192
6193
6194 /*
6195  * L.DomEvent contains functions for working with DOM events.
6196  */
6197
6198 L.DomEvent = {
6199         /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
6200         addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
6201
6202                 var id = L.stamp(fn),
6203                     key = '_leaflet_' + type + id,
6204                     handler, originalHandler, newType;
6205
6206                 if (obj[key]) { return this; }
6207
6208                 handler = function (e) {
6209                         return fn.call(context || obj, e || L.DomEvent._getEvent());
6210                 };
6211
6212                 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6213                         return this.addMsTouchListener(obj, type, handler, id);
6214                 }
6215                 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
6216                         this.addDoubleTapListener(obj, handler, id);
6217                 }
6218
6219                 if ('addEventListener' in obj) {
6220
6221                         if (type === 'mousewheel') {
6222                                 obj.addEventListener('DOMMouseScroll', handler, false);
6223                                 obj.addEventListener(type, handler, false);
6224
6225                         } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6226
6227                                 originalHandler = handler;
6228                                 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
6229
6230                                 handler = function (e) {
6231                                         if (!L.DomEvent._checkMouse(obj, e)) { return; }
6232                                         return originalHandler(e);
6233                                 };
6234
6235                                 obj.addEventListener(newType, handler, false);
6236
6237                         } else if (type === 'click' && L.Browser.android) {
6238                                 originalHandler = handler;
6239                                 handler = function (e) {
6240                                         return L.DomEvent._filterClick(e, originalHandler);
6241                                 };
6242
6243                                 obj.addEventListener(type, handler, false);
6244                         } else {
6245                                 obj.addEventListener(type, handler, false);
6246                         }
6247
6248                 } else if ('attachEvent' in obj) {
6249                         obj.attachEvent('on' + type, handler);
6250                 }
6251
6252                 obj[key] = handler;
6253
6254                 return this;
6255         },
6256
6257         removeListener: function (obj, type, fn) {  // (HTMLElement, String, Function)
6258
6259                 var id = L.stamp(fn),
6260                     key = '_leaflet_' + type + id,
6261                     handler = obj[key];
6262
6263                 if (!handler) { return this; }
6264
6265                 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6266                         this.removeMsTouchListener(obj, type, id);
6267                 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
6268                         this.removeDoubleTapListener(obj, id);
6269
6270                 } else if ('removeEventListener' in obj) {
6271
6272                         if (type === 'mousewheel') {
6273                                 obj.removeEventListener('DOMMouseScroll', handler, false);
6274                                 obj.removeEventListener(type, handler, false);
6275
6276                         } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6277                                 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
6278                         } else {
6279                                 obj.removeEventListener(type, handler, false);
6280                         }
6281                 } else if ('detachEvent' in obj) {
6282                         obj.detachEvent('on' + type, handler);
6283                 }
6284
6285                 obj[key] = null;
6286
6287                 return this;
6288         },
6289
6290         stopPropagation: function (e) {
6291
6292                 if (e.stopPropagation) {
6293                         e.stopPropagation();
6294                 } else {
6295                         e.cancelBubble = true;
6296                 }
6297                 return this;
6298         },
6299
6300         disableClickPropagation: function (el) {
6301                 var stop = L.DomEvent.stopPropagation;
6302
6303                 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6304                         L.DomEvent.addListener(el, L.Draggable.START[i], stop);
6305                 }
6306
6307                 return L.DomEvent
6308                         .addListener(el, 'click', L.DomEvent._fakeStop)
6309                         .addListener(el, 'dblclick', stop);
6310         },
6311
6312         preventDefault: function (e) {
6313
6314                 if (e.preventDefault) {
6315                         e.preventDefault();
6316                 } else {
6317                         e.returnValue = false;
6318                 }
6319                 return this;
6320         },
6321
6322         stop: function (e) {
6323                 return L.DomEvent.preventDefault(e).stopPropagation(e);
6324         },
6325
6326         getMousePosition: function (e, container) {
6327
6328                 var ie7 = L.Browser.ie7,
6329                     body = document.body,
6330                     docEl = document.documentElement,
6331                     x = e.pageX ? e.pageX - body.scrollLeft - docEl.scrollLeft: e.clientX,
6332                     y = e.pageY ? e.pageY - body.scrollTop - docEl.scrollTop: e.clientY,
6333                     pos = new L.Point(x, y),
6334                     rect = container.getBoundingClientRect(),
6335                     left = rect.left - container.clientLeft,
6336                     top = rect.top - container.clientTop;
6337
6338                 // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
6339                 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
6340                 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
6341                         left += container.scrollWidth - container.clientWidth;
6342
6343                         // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
6344                         // need to add it back in if it is visible; scrollbar is on the left as we are RTL
6345                         if (ie7 && L.DomUtil.getStyle(container, 'overflow-y') !== 'hidden' &&
6346                                    L.DomUtil.getStyle(container, 'overflow') !== 'hidden') {
6347                                 left += 17;
6348                         }
6349                 }
6350
6351                 return pos._subtract(new L.Point(left, top));
6352         },
6353
6354         getWheelDelta: function (e) {
6355
6356                 var delta = 0;
6357
6358                 if (e.wheelDelta) {
6359                         delta = e.wheelDelta / 120;
6360                 }
6361                 if (e.detail) {
6362                         delta = -e.detail / 3;
6363                 }
6364                 return delta;
6365         },
6366
6367         _skipEvents: {},
6368
6369         _fakeStop: function (e) {
6370                 // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
6371                 L.DomEvent._skipEvents[e.type] = true;
6372         },
6373
6374         _skipped: function (e) {
6375                 var skipped = this._skipEvents[e.type];
6376                 // reset when checking, as it's only used in map container and propagates outside of the map
6377                 this._skipEvents[e.type] = false;
6378                 return skipped;
6379         },
6380
6381         // check if element really left/entered the event target (for mouseenter/mouseleave)
6382         _checkMouse: function (el, e) {
6383
6384                 var related = e.relatedTarget;
6385
6386                 if (!related) { return true; }
6387
6388                 try {
6389                         while (related && (related !== el)) {
6390                                 related = related.parentNode;
6391                         }
6392                 } catch (err) {
6393                         return false;
6394                 }
6395                 return (related !== el);
6396         },
6397
6398         _getEvent: function () { // evil magic for IE
6399                 /*jshint noarg:false */
6400                 var e = window.event;
6401                 if (!e) {
6402                         var caller = arguments.callee.caller;
6403                         while (caller) {
6404                                 e = caller['arguments'][0];
6405                                 if (e && window.Event === e.constructor) {
6406                                         break;
6407                                 }
6408                                 caller = caller.caller;
6409                         }
6410                 }
6411                 return e;
6412         },
6413
6414         // this is a horrible workaround for a bug in Android where a single touch triggers two click events
6415         _filterClick: function (e, handler) {
6416                 var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
6417                         elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
6418
6419                 // are they closer together than 1000ms yet more than 100ms?
6420                 // Android typically triggers them ~300ms apart while multiple listeners
6421                 // on the same event should be triggered far faster;
6422                 // or check if click is simulated on the element, and if it is, reject any non-simulated events
6423
6424                 if ((elapsed && elapsed > 100 && elapsed < 1000) || (e.target._simulatedClick && !e._simulated)) {
6425                         L.DomEvent.stop(e);
6426                         return;
6427                 }
6428                 L.DomEvent._lastClick = timeStamp;
6429
6430                 return handler(e);
6431         }
6432 };
6433
6434 L.DomEvent.on = L.DomEvent.addListener;
6435 L.DomEvent.off = L.DomEvent.removeListener;
6436
6437
6438 /*
6439  * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
6440  */
6441
6442 L.Draggable = L.Class.extend({
6443         includes: L.Mixin.Events,
6444
6445         statics: {
6446                 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
6447                 END: {
6448                         mousedown: 'mouseup',
6449                         touchstart: 'touchend',
6450                         MSPointerDown: 'touchend'
6451                 },
6452                 MOVE: {
6453                         mousedown: 'mousemove',
6454                         touchstart: 'touchmove',
6455                         MSPointerDown: 'touchmove'
6456                 }
6457         },
6458
6459         initialize: function (element, dragStartTarget) {
6460                 this._element = element;
6461                 this._dragStartTarget = dragStartTarget || element;
6462         },
6463
6464         enable: function () {
6465                 if (this._enabled) { return; }
6466
6467                 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6468                         L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6469                 }
6470
6471                 this._enabled = true;
6472         },
6473
6474         disable: function () {
6475                 if (!this._enabled) { return; }
6476
6477                 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6478                         L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6479                 }
6480
6481                 this._enabled = false;
6482                 this._moved = false;
6483         },
6484
6485         _onDown: function (e) {
6486                 if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
6487
6488                 L.DomEvent
6489                         .stopPropagation(e);
6490
6491                 if (L.Draggable._disabled) { return; }
6492
6493                 L.DomUtil.disableImageDrag();
6494                 L.DomUtil.disableTextSelection();
6495
6496                 var first = e.touches ? e.touches[0] : e,
6497                     el = first.target;
6498
6499                 // if touching a link, highlight it
6500                 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
6501                         L.DomUtil.addClass(el, 'leaflet-active');
6502                 }
6503
6504                 this._moved = false;
6505
6506                 if (this._moving) { return; }
6507
6508                 this._startPoint = new L.Point(first.clientX, first.clientY);
6509                 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
6510
6511                 L.DomEvent
6512                     .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
6513                     .on(document, L.Draggable.END[e.type], this._onUp, this);
6514         },
6515
6516         _onMove: function (e) {
6517                 if (e.touches && e.touches.length > 1) { return; }
6518
6519                 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
6520                     newPoint = new L.Point(first.clientX, first.clientY),
6521                     offset = newPoint.subtract(this._startPoint);
6522
6523                 if (!offset.x && !offset.y) { return; }
6524
6525                 L.DomEvent.preventDefault(e);
6526
6527                 if (!this._moved) {
6528                         this.fire('dragstart');
6529
6530                         this._moved = true;
6531                         this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
6532
6533                         if (!L.Browser.touch) {
6534                                 L.DomUtil.addClass(document.body, 'leaflet-dragging');
6535                         }
6536                 }
6537
6538                 this._newPos = this._startPos.add(offset);
6539                 this._moving = true;
6540
6541                 L.Util.cancelAnimFrame(this._animRequest);
6542                 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
6543         },
6544
6545         _updatePosition: function () {
6546                 this.fire('predrag');
6547                 L.DomUtil.setPosition(this._element, this._newPos);
6548                 this.fire('drag');
6549         },
6550
6551         _onUp: function () {
6552                 if (!L.Browser.touch) {
6553                         L.DomUtil.removeClass(document.body, 'leaflet-dragging');
6554                 }
6555
6556                 for (var i in L.Draggable.MOVE) {
6557                         L.DomEvent
6558                             .off(document, L.Draggable.MOVE[i], this._onMove)
6559                             .off(document, L.Draggable.END[i], this._onUp);
6560                 }
6561
6562                 L.DomUtil.enableImageDrag();
6563                 L.DomUtil.enableTextSelection();
6564
6565                 if (this._moved) {
6566                         // ensure drag is not fired after dragend
6567                         L.Util.cancelAnimFrame(this._animRequest);
6568
6569                         this.fire('dragend');
6570                 }
6571
6572                 this._moving = false;
6573         }
6574 });
6575
6576
6577 /*
6578         L.Handler is a base class for handler classes that are used internally to inject
6579         interaction features like dragging to classes like Map and Marker.
6580 */
6581
6582 L.Handler = L.Class.extend({
6583         initialize: function (map) {
6584                 this._map = map;
6585         },
6586
6587         enable: function () {
6588                 if (this._enabled) { return; }
6589
6590                 this._enabled = true;
6591                 this.addHooks();
6592         },
6593
6594         disable: function () {
6595                 if (!this._enabled) { return; }
6596
6597                 this._enabled = false;
6598                 this.removeHooks();
6599         },
6600
6601         enabled: function () {
6602                 return !!this._enabled;
6603         }
6604 });
6605
6606
6607 /*
6608  * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
6609  */
6610
6611 L.Map.mergeOptions({
6612         dragging: true,
6613
6614         inertia: !L.Browser.android23,
6615         inertiaDeceleration: 3400, // px/s^2
6616         inertiaMaxSpeed: Infinity, // px/s
6617         inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
6618         easeLinearity: 0.25,
6619
6620         // TODO refactor, move to CRS
6621         worldCopyJump: false
6622 });
6623
6624 L.Map.Drag = L.Handler.extend({
6625         addHooks: function () {
6626                 if (!this._draggable) {
6627                         var map = this._map;
6628
6629                         this._draggable = new L.Draggable(map._mapPane, map._container);
6630
6631                         this._draggable.on({
6632                                 'dragstart': this._onDragStart,
6633                                 'drag': this._onDrag,
6634                                 'dragend': this._onDragEnd
6635                         }, this);
6636
6637                         if (map.options.worldCopyJump) {
6638                                 this._draggable.on('predrag', this._onPreDrag, this);
6639                                 map.on('viewreset', this._onViewReset, this);
6640
6641                                 this._onViewReset();
6642                         }
6643                 }
6644                 this._draggable.enable();
6645         },
6646
6647         removeHooks: function () {
6648                 this._draggable.disable();
6649         },
6650
6651         moved: function () {
6652                 return this._draggable && this._draggable._moved;
6653         },
6654
6655         _onDragStart: function () {
6656                 var map = this._map;
6657
6658                 if (map._panAnim) {
6659                         map._panAnim.stop();
6660                 }
6661
6662                 map
6663                     .fire('movestart')
6664                     .fire('dragstart');
6665
6666                 if (map.options.inertia) {
6667                         this._positions = [];
6668                         this._times = [];
6669                 }
6670         },
6671
6672         _onDrag: function () {
6673                 if (this._map.options.inertia) {
6674                         var time = this._lastTime = +new Date(),
6675                             pos = this._lastPos = this._draggable._newPos;
6676
6677                         this._positions.push(pos);
6678                         this._times.push(time);
6679
6680                         if (time - this._times[0] > 200) {
6681                                 this._positions.shift();
6682                                 this._times.shift();
6683                         }
6684                 }
6685
6686                 this._map
6687                     .fire('move')
6688                     .fire('drag');
6689         },
6690
6691         _onViewReset: function () {
6692                 // TODO fix hardcoded Earth values
6693                 var pxCenter = this._map.getSize()._divideBy(2),
6694                     pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
6695
6696                 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6697                 this._worldWidth = this._map.project([0, 180]).x;
6698         },
6699
6700         _onPreDrag: function () {
6701                 // TODO refactor to be able to adjust map pane position after zoom
6702                 var worldWidth = this._worldWidth,
6703                     halfWidth = Math.round(worldWidth / 2),
6704                     dx = this._initialWorldOffset,
6705                     x = this._draggable._newPos.x,
6706                     newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6707                     newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6708                     newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6709
6710                 this._draggable._newPos.x = newX;
6711         },
6712
6713         _onDragEnd: function () {
6714                 var map = this._map,
6715                     options = map.options,
6716                     delay = +new Date() - this._lastTime,
6717
6718                     noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6719
6720                 map.fire('dragend');
6721
6722                 if (noInertia) {
6723                         map.fire('moveend');
6724
6725                 } else {
6726
6727                         var direction = this._lastPos.subtract(this._positions[0]),
6728                             duration = (this._lastTime + delay - this._times[0]) / 1000,
6729                             ease = options.easeLinearity,
6730
6731                             speedVector = direction.multiplyBy(ease / duration),
6732                             speed = speedVector.distanceTo([0, 0]),
6733
6734                             limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6735                             limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6736
6737                             decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6738                             offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6739
6740                         if (!offset.x || !offset.y) {
6741                                 map.fire('moveend');
6742
6743                         } else {
6744                                 L.Util.requestAnimFrame(function () {
6745                                         map.panBy(offset, {
6746                                                 duration: decelerationDuration,
6747                                                 easeLinearity: ease,
6748                                                 noMoveStart: true
6749                                         });
6750                                 });
6751                         }
6752                 }
6753         }
6754 });
6755
6756 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6757
6758
6759 /*
6760  * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6761  */
6762
6763 L.Map.mergeOptions({
6764         doubleClickZoom: true
6765 });
6766
6767 L.Map.DoubleClickZoom = L.Handler.extend({
6768         addHooks: function () {
6769                 this._map.on('dblclick', this._onDoubleClick, this);
6770         },
6771
6772         removeHooks: function () {
6773                 this._map.off('dblclick', this._onDoubleClick, this);
6774         },
6775
6776         _onDoubleClick: function (e) {
6777                 var map = this._map,
6778                     zoom = map.getZoom() + 1;
6779
6780                 if (map.options.doubleClickZoom === 'center') {
6781                         map.setZoom(zoom);
6782                 } else {
6783                         map.setZoomAround(e.containerPoint, zoom);
6784                 }
6785         }
6786 });
6787
6788 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
6789
6790
6791 /*
6792  * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
6793  */
6794
6795 L.Map.mergeOptions({
6796         scrollWheelZoom: true
6797 });
6798
6799 L.Map.ScrollWheelZoom = L.Handler.extend({
6800         addHooks: function () {
6801                 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
6802                 L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6803                 this._delta = 0;
6804         },
6805
6806         removeHooks: function () {
6807                 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
6808                 L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6809         },
6810
6811         _onWheelScroll: function (e) {
6812                 var delta = L.DomEvent.getWheelDelta(e);
6813
6814                 this._delta += delta;
6815                 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
6816
6817                 if (!this._startTime) {
6818                         this._startTime = +new Date();
6819                 }
6820
6821                 var left = Math.max(40 - (+new Date() - this._startTime), 0);
6822
6823                 clearTimeout(this._timer);
6824                 this._timer = setTimeout(L.bind(this._performZoom, this), left);
6825
6826                 L.DomEvent.preventDefault(e);
6827                 L.DomEvent.stopPropagation(e);
6828         },
6829
6830         _performZoom: function () {
6831                 var map = this._map,
6832                     delta = this._delta,
6833                     zoom = map.getZoom();
6834
6835                 delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
6836                 delta = Math.max(Math.min(delta, 4), -4);
6837                 delta = map._limitZoom(zoom + delta) - zoom;
6838
6839                 this._delta = 0;
6840                 this._startTime = null;
6841
6842                 if (!delta) { return; }
6843
6844                 if (map.options.scrollWheelZoom === 'center') {
6845                         map.setZoom(zoom + delta);
6846                 } else {
6847                         map.setZoomAround(this._lastMousePos, zoom + delta);
6848                 }
6849         }
6850 });
6851
6852 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
6853
6854
6855 /*
6856  * Extends the event handling code with double tap support for mobile browsers.
6857  */
6858
6859 L.extend(L.DomEvent, {
6860
6861         _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
6862         _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
6863
6864         // inspired by Zepto touch code by Thomas Fuchs
6865         addDoubleTapListener: function (obj, handler, id) {
6866                 var last,
6867                     doubleTap = false,
6868                     delay = 250,
6869                     touch,
6870                     pre = '_leaflet_',
6871                     touchstart = this._touchstart,
6872                     touchend = this._touchend,
6873                     trackedTouches = [];
6874
6875                 function onTouchStart(e) {
6876                         var count;
6877
6878                         if (L.Browser.msTouch) {
6879                                 trackedTouches.push(e.pointerId);
6880                                 count = trackedTouches.length;
6881                         } else {
6882                                 count = e.touches.length;
6883                         }
6884                         if (count > 1) {
6885                                 return;
6886                         }
6887
6888                         var now = Date.now(),
6889                                 delta = now - (last || now);
6890
6891                         touch = e.touches ? e.touches[0] : e;
6892                         doubleTap = (delta > 0 && delta <= delay);
6893                         last = now;
6894                 }
6895
6896                 function onTouchEnd(e) {
6897                         if (L.Browser.msTouch) {
6898                                 var idx = trackedTouches.indexOf(e.pointerId);
6899                                 if (idx === -1) {
6900                                         return;
6901                                 }
6902                                 trackedTouches.splice(idx, 1);
6903                         }
6904
6905                         if (doubleTap) {
6906                                 if (L.Browser.msTouch) {
6907                                         // work around .type being readonly with MSPointer* events
6908                                         var newTouch = { },
6909                                                 prop;
6910
6911                                         // jshint forin:false
6912                                         for (var i in touch) {
6913                                                 prop = touch[i];
6914                                                 if (typeof prop === 'function') {
6915                                                         newTouch[i] = prop.bind(touch);
6916                                                 } else {
6917                                                         newTouch[i] = prop;
6918                                                 }
6919                                         }
6920                                         touch = newTouch;
6921                                 }
6922                                 touch.type = 'dblclick';
6923                                 handler(touch);
6924                                 last = null;
6925                         }
6926                 }
6927                 obj[pre + touchstart + id] = onTouchStart;
6928                 obj[pre + touchend + id] = onTouchEnd;
6929
6930                 // on msTouch we need to listen on the document, otherwise a drag starting on the map and moving off screen
6931                 // will not come through to us, so we will lose track of how many touches are ongoing
6932                 var endElement = L.Browser.msTouch ? document.documentElement : obj;
6933
6934                 obj.addEventListener(touchstart, onTouchStart, false);
6935                 endElement.addEventListener(touchend, onTouchEnd, false);
6936
6937                 if (L.Browser.msTouch) {
6938                         endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
6939                 }
6940
6941                 return this;
6942         },
6943
6944         removeDoubleTapListener: function (obj, id) {
6945                 var pre = '_leaflet_';
6946
6947                 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
6948                 (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(
6949                         this._touchend, obj[pre + this._touchend + id], false);
6950
6951                 if (L.Browser.msTouch) {
6952                         document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
6953                 }
6954
6955                 return this;
6956         }
6957 });
6958
6959
6960 /*
6961  * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
6962  */
6963
6964 L.extend(L.DomEvent, {
6965
6966         _msTouches: [],
6967         _msDocumentListener: false,
6968
6969         // Provides a touch events wrapper for msPointer events.
6970         // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
6971
6972         addMsTouchListener: function (obj, type, handler, id) {
6973
6974                 switch (type) {
6975                 case 'touchstart':
6976                         return this.addMsTouchListenerStart(obj, type, handler, id);
6977                 case 'touchend':
6978                         return this.addMsTouchListenerEnd(obj, type, handler, id);
6979                 case 'touchmove':
6980                         return this.addMsTouchListenerMove(obj, type, handler, id);
6981                 default:
6982                         throw 'Unknown touch event type';
6983                 }
6984         },
6985
6986         addMsTouchListenerStart: function (obj, type, handler, id) {
6987                 var pre = '_leaflet_',
6988                     touches = this._msTouches;
6989
6990                 var cb = function (e) {
6991
6992                         var alreadyInArray = false;
6993                         for (var i = 0; i < touches.length; i++) {
6994                                 if (touches[i].pointerId === e.pointerId) {
6995                                         alreadyInArray = true;
6996                                         break;
6997                                 }
6998                         }
6999                         if (!alreadyInArray) {
7000                                 touches.push(e);
7001                         }
7002
7003                         e.touches = touches.slice();
7004                         e.changedTouches = [e];
7005
7006                         handler(e);
7007                 };
7008
7009                 obj[pre + 'touchstart' + id] = cb;
7010                 obj.addEventListener('MSPointerDown', cb, false);
7011
7012                 // need to also listen for end events to keep the _msTouches list accurate
7013                 // this needs to be on the body and never go away
7014                 if (!this._msDocumentListener) {
7015                         var internalCb = function (e) {
7016                                 for (var i = 0; i < touches.length; i++) {
7017                                         if (touches[i].pointerId === e.pointerId) {
7018                                                 touches.splice(i, 1);
7019                                                 break;
7020                                         }
7021                                 }
7022                         };
7023                         //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
7024                         document.documentElement.addEventListener('MSPointerUp', internalCb, false);
7025                         document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
7026
7027                         this._msDocumentListener = true;
7028                 }
7029
7030                 return this;
7031         },
7032
7033         addMsTouchListenerMove: function (obj, type, handler, id) {
7034                 var pre = '_leaflet_',
7035                     touches = this._msTouches;
7036
7037                 function cb(e) {
7038
7039                         // don't fire touch moves when mouse isn't down
7040                         if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) { return; }
7041
7042                         for (var i = 0; i < touches.length; i++) {
7043                                 if (touches[i].pointerId === e.pointerId) {
7044                                         touches[i] = e;
7045                                         break;
7046                                 }
7047                         }
7048
7049                         e.touches = touches.slice();
7050                         e.changedTouches = [e];
7051
7052                         handler(e);
7053                 }
7054
7055                 obj[pre + 'touchmove' + id] = cb;
7056                 obj.addEventListener('MSPointerMove', cb, false);
7057
7058                 return this;
7059         },
7060
7061         addMsTouchListenerEnd: function (obj, type, handler, id) {
7062                 var pre = '_leaflet_',
7063                     touches = this._msTouches;
7064
7065                 var cb = function (e) {
7066                         for (var i = 0; i < touches.length; i++) {
7067                                 if (touches[i].pointerId === e.pointerId) {
7068                                         touches.splice(i, 1);
7069                                         break;
7070                                 }
7071                         }
7072
7073                         e.touches = touches.slice();
7074                         e.changedTouches = [e];
7075
7076                         handler(e);
7077                 };
7078
7079                 obj[pre + 'touchend' + id] = cb;
7080                 obj.addEventListener('MSPointerUp', cb, false);
7081                 obj.addEventListener('MSPointerCancel', cb, false);
7082
7083                 return this;
7084         },
7085
7086         removeMsTouchListener: function (obj, type, id) {
7087                 var pre = '_leaflet_',
7088                     cb = obj[pre + type + id];
7089
7090                 switch (type) {
7091                 case 'touchstart':
7092                         obj.removeEventListener('MSPointerDown', cb, false);
7093                         break;
7094                 case 'touchmove':
7095                         obj.removeEventListener('MSPointerMove', cb, false);
7096                         break;
7097                 case 'touchend':
7098                         obj.removeEventListener('MSPointerUp', cb, false);
7099                         obj.removeEventListener('MSPointerCancel', cb, false);
7100                         break;
7101                 }
7102
7103                 return this;
7104         }
7105 });
7106
7107
7108 /*
7109  * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
7110  */
7111
7112 L.Map.mergeOptions({
7113         touchZoom: L.Browser.touch && !L.Browser.android23
7114 });
7115
7116 L.Map.TouchZoom = L.Handler.extend({
7117         addHooks: function () {
7118                 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
7119         },
7120
7121         removeHooks: function () {
7122                 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
7123         },
7124
7125         _onTouchStart: function (e) {
7126                 var map = this._map;
7127
7128                 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
7129
7130                 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7131                     p2 = map.mouseEventToLayerPoint(e.touches[1]),
7132                     viewCenter = map._getCenterLayerPoint();
7133
7134                 this._startCenter = p1.add(p2)._divideBy(2);
7135                 this._startDist = p1.distanceTo(p2);
7136
7137                 this._moved = false;
7138                 this._zooming = true;
7139
7140                 this._centerOffset = viewCenter.subtract(this._startCenter);
7141
7142                 if (map._panAnim) {
7143                         map._panAnim.stop();
7144                 }
7145
7146                 L.DomEvent
7147                     .on(document, 'touchmove', this._onTouchMove, this)
7148                     .on(document, 'touchend', this._onTouchEnd, this);
7149
7150                 L.DomEvent.preventDefault(e);
7151         },
7152
7153         _onTouchMove: function (e) {
7154                 var map = this._map;
7155
7156                 if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
7157
7158                 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7159                     p2 = map.mouseEventToLayerPoint(e.touches[1]);
7160
7161                 this._scale = p1.distanceTo(p2) / this._startDist;
7162                 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
7163
7164                 if (this._scale === 1) { return; }
7165
7166                 if (!this._moved) {
7167                         L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
7168
7169                         map
7170                             .fire('movestart')
7171                             .fire('zoomstart');
7172
7173                         this._moved = true;
7174                 }
7175
7176                 L.Util.cancelAnimFrame(this._animRequest);
7177                 this._animRequest = L.Util.requestAnimFrame(
7178                         this._updateOnMove, this, true, this._map._container);
7179
7180                 L.DomEvent.preventDefault(e);
7181         },
7182
7183         _updateOnMove: function () {
7184                 var map = this._map,
7185                     origin = this._getScaleOrigin(),
7186                     center = map.layerPointToLatLng(origin),
7187                     zoom = map.getScaleZoom(this._scale);
7188
7189                 map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta);
7190         },
7191
7192         _onTouchEnd: function () {
7193                 if (!this._moved || !this._zooming) {
7194                         this._zooming = false;
7195                         return;
7196                 }
7197
7198                 var map = this._map;
7199
7200                 this._zooming = false;
7201                 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
7202                 L.Util.cancelAnimFrame(this._animRequest);
7203
7204                 L.DomEvent
7205                     .off(document, 'touchmove', this._onTouchMove)
7206                     .off(document, 'touchend', this._onTouchEnd);
7207
7208                 var origin = this._getScaleOrigin(),
7209                     center = map.layerPointToLatLng(origin),
7210
7211                     oldZoom = map.getZoom(),
7212                     floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
7213                     roundZoomDelta = (floatZoomDelta > 0 ?
7214                             Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
7215
7216                     zoom = map._limitZoom(oldZoom + roundZoomDelta),
7217                     scale = map.getZoomScale(zoom) / this._scale;
7218
7219                 map._animateZoom(center, zoom, origin, scale);
7220         },
7221
7222         _getScaleOrigin: function () {
7223                 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
7224                 return this._startCenter.add(centerOffset);
7225         }
7226 });
7227
7228 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
7229
7230
7231 /*
7232  * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
7233  */
7234
7235 L.Map.mergeOptions({
7236         tap: true,
7237         tapTolerance: 15
7238 });
7239
7240 L.Map.Tap = L.Handler.extend({
7241         addHooks: function () {
7242                 L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
7243         },
7244
7245         removeHooks: function () {
7246                 L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
7247         },
7248
7249         _onDown: function (e) {
7250                 if (!e.touches) { return; }
7251
7252                 L.DomEvent.preventDefault(e);
7253
7254                 this._fireClick = true;
7255
7256                 // don't simulate click or track longpress if more than 1 touch
7257                 if (e.touches.length > 1) {
7258                         this._fireClick = false;
7259                         clearTimeout(this._holdTimeout);
7260                         return;
7261                 }
7262
7263                 var first = e.touches[0],
7264                     el = first.target;
7265
7266                 this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
7267
7268                 // if touching a link, highlight it
7269                 if (el.tagName.toLowerCase() === 'a') {
7270                         L.DomUtil.addClass(el, 'leaflet-active');
7271                 }
7272
7273                 // simulate long hold but setting a timeout
7274                 this._holdTimeout = setTimeout(L.bind(function () {
7275                         if (this._isTapValid()) {
7276                                 this._fireClick = false;
7277                                 this._onUp();
7278                                 this._simulateEvent('contextmenu', first);
7279                         }
7280                 }, this), 1000);
7281
7282                 L.DomEvent
7283                         .on(document, 'touchmove', this._onMove, this)
7284                         .on(document, 'touchend', this._onUp, this);
7285         },
7286
7287         _onUp: function (e) {
7288                 clearTimeout(this._holdTimeout);
7289
7290                 L.DomEvent
7291                         .off(document, 'touchmove', this._onMove, this)
7292                         .off(document, 'touchend', this._onUp, this);
7293
7294                 if (this._fireClick && e && e.changedTouches) {
7295
7296                         var first = e.changedTouches[0],
7297                             el = first.target;
7298
7299                         if (el.tagName.toLowerCase() === 'a') {
7300                                 L.DomUtil.removeClass(el, 'leaflet-active');
7301                         }
7302
7303                         // simulate click if the touch didn't move too much
7304                         if (this._isTapValid()) {
7305                                 this._simulateEvent('click', first);
7306                         }
7307                 }
7308         },
7309
7310         _isTapValid: function () {
7311                 return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
7312         },
7313
7314         _onMove: function (e) {
7315                 var first = e.touches[0];
7316                 this._newPos = new L.Point(first.clientX, first.clientY);
7317         },
7318
7319         _simulateEvent: function (type, e) {
7320                 var simulatedEvent = document.createEvent('MouseEvents');
7321
7322                 simulatedEvent._simulated = true;
7323                 e.target._simulatedClick = true;
7324
7325                 simulatedEvent.initMouseEvent(
7326                         type, true, true, window, 1,
7327                         e.screenX, e.screenY,
7328                         e.clientX, e.clientY,
7329                         false, false, false, false, 0, null);
7330
7331                 e.target.dispatchEvent(simulatedEvent);
7332         }
7333 });
7334
7335 if (L.Browser.touch && !L.Browser.msTouch) {
7336         L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
7337 }
7338
7339
7340 /*
7341  * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
7342   * (zoom to a selected bounding box), enabled by default.
7343  */
7344
7345 L.Map.mergeOptions({
7346         boxZoom: true
7347 });
7348
7349 L.Map.BoxZoom = L.Handler.extend({
7350         initialize: function (map) {
7351                 this._map = map;
7352                 this._container = map._container;
7353                 this._pane = map._panes.overlayPane;
7354         },
7355
7356         addHooks: function () {
7357                 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
7358         },
7359
7360         removeHooks: function () {
7361                 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
7362         },
7363
7364         _onMouseDown: function (e) {
7365                 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
7366
7367                 L.DomUtil.disableTextSelection();
7368                 L.DomUtil.disableImageDrag();
7369
7370                 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
7371
7372                 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
7373                 L.DomUtil.setPosition(this._box, this._startLayerPoint);
7374
7375                 //TODO refactor: move cursor to styles
7376                 this._container.style.cursor = 'crosshair';
7377
7378                 L.DomEvent
7379                     .on(document, 'mousemove', this._onMouseMove, this)
7380                     .on(document, 'mouseup', this._onMouseUp, this)
7381                     .on(document, 'keydown', this._onKeyDown, this);
7382
7383                 this._map.fire('boxzoomstart');
7384         },
7385
7386         _onMouseMove: function (e) {
7387                 var startPoint = this._startLayerPoint,
7388                     box = this._box,
7389
7390                     layerPoint = this._map.mouseEventToLayerPoint(e),
7391                     offset = layerPoint.subtract(startPoint),
7392
7393                     newPos = new L.Point(
7394                         Math.min(layerPoint.x, startPoint.x),
7395                         Math.min(layerPoint.y, startPoint.y));
7396
7397                 L.DomUtil.setPosition(box, newPos);
7398
7399                 // TODO refactor: remove hardcoded 4 pixels
7400                 box.style.width  = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
7401                 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
7402         },
7403
7404         _finish: function () {
7405                 this._pane.removeChild(this._box);
7406                 this._container.style.cursor = '';
7407
7408                 L.DomUtil.enableTextSelection();
7409                 L.DomUtil.enableImageDrag();
7410
7411                 L.DomEvent
7412                     .off(document, 'mousemove', this._onMouseMove)
7413                     .off(document, 'mouseup', this._onMouseUp)
7414                     .off(document, 'keydown', this._onKeyDown);
7415         },
7416
7417         _onMouseUp: function (e) {
7418
7419                 this._finish();
7420
7421                 var map = this._map,
7422                     layerPoint = map.mouseEventToLayerPoint(e);
7423
7424                 if (this._startLayerPoint.equals(layerPoint)) { return; }
7425
7426                 var bounds = new L.LatLngBounds(
7427                         map.layerPointToLatLng(this._startLayerPoint),
7428                         map.layerPointToLatLng(layerPoint));
7429
7430                 map.fitBounds(bounds);
7431
7432                 map.fire('boxzoomend', {
7433                         boxZoomBounds: bounds
7434                 });
7435         },
7436
7437         _onKeyDown: function (e) {
7438                 if (e.keyCode === 27) {
7439                         this._finish();
7440                 }
7441         }
7442 });
7443
7444 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
7445
7446
7447 /*
7448  * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
7449  */
7450
7451 L.Map.mergeOptions({
7452         keyboard: true,
7453         keyboardPanOffset: 80,
7454         keyboardZoomOffset: 1
7455 });
7456
7457 L.Map.Keyboard = L.Handler.extend({
7458
7459         keyCodes: {
7460                 left:    [37],
7461                 right:   [39],
7462                 down:    [40],
7463                 up:      [38],
7464                 zoomIn:  [187, 107, 61],
7465                 zoomOut: [189, 109, 173]
7466         },
7467
7468         initialize: function (map) {
7469                 this._map = map;
7470
7471                 this._setPanOffset(map.options.keyboardPanOffset);
7472                 this._setZoomOffset(map.options.keyboardZoomOffset);
7473         },
7474
7475         addHooks: function () {
7476                 var container = this._map._container;
7477
7478                 // make the container focusable by tabbing
7479                 if (container.tabIndex === -1) {
7480                         container.tabIndex = '0';
7481                 }
7482
7483                 L.DomEvent
7484                     .on(container, 'focus', this._onFocus, this)
7485                     .on(container, 'blur', this._onBlur, this)
7486                     .on(container, 'mousedown', this._onMouseDown, this);
7487
7488                 this._map
7489                     .on('focus', this._addHooks, this)
7490                     .on('blur', this._removeHooks, this);
7491         },
7492
7493         removeHooks: function () {
7494                 this._removeHooks();
7495
7496                 var container = this._map._container;
7497
7498                 L.DomEvent
7499                     .off(container, 'focus', this._onFocus, this)
7500                     .off(container, 'blur', this._onBlur, this)
7501                     .off(container, 'mousedown', this._onMouseDown, this);
7502
7503                 this._map
7504                     .off('focus', this._addHooks, this)
7505                     .off('blur', this._removeHooks, this);
7506         },
7507
7508         _onMouseDown: function () {
7509                 if (this._focused) { return; }
7510
7511                 var body = document.body,
7512                     docEl = document.documentElement,
7513                     top = body.scrollTop || docEl.scrollTop,
7514                     left = body.scrollTop || docEl.scrollLeft;
7515
7516                 this._map._container.focus();
7517
7518                 window.scrollTo(left, top);
7519         },
7520
7521         _onFocus: function () {
7522                 this._focused = true;
7523                 this._map.fire('focus');
7524         },
7525
7526         _onBlur: function () {
7527                 this._focused = false;
7528                 this._map.fire('blur');
7529         },
7530
7531         _setPanOffset: function (pan) {
7532                 var keys = this._panKeys = {},
7533                     codes = this.keyCodes,
7534                     i, len;
7535
7536                 for (i = 0, len = codes.left.length; i < len; i++) {
7537                         keys[codes.left[i]] = [-1 * pan, 0];
7538                 }
7539                 for (i = 0, len = codes.right.length; i < len; i++) {
7540                         keys[codes.right[i]] = [pan, 0];
7541                 }
7542                 for (i = 0, len = codes.down.length; i < len; i++) {
7543                         keys[codes.down[i]] = [0, pan];
7544                 }
7545                 for (i = 0, len = codes.up.length; i < len; i++) {
7546                         keys[codes.up[i]] = [0, -1 * pan];
7547                 }
7548         },
7549
7550         _setZoomOffset: function (zoom) {
7551                 var keys = this._zoomKeys = {},
7552                     codes = this.keyCodes,
7553                     i, len;
7554
7555                 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
7556                         keys[codes.zoomIn[i]] = zoom;
7557                 }
7558                 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
7559                         keys[codes.zoomOut[i]] = -zoom;
7560                 }
7561         },
7562
7563         _addHooks: function () {
7564                 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
7565         },
7566
7567         _removeHooks: function () {
7568                 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
7569         },
7570
7571         _onKeyDown: function (e) {
7572                 var key = e.keyCode,
7573                     map = this._map;
7574
7575                 if (key in this._panKeys) {
7576
7577                         if (map._panAnim && map._panAnim._inProgress) { return; }
7578
7579                         map.panBy(this._panKeys[key]);
7580
7581                         if (map.options.maxBounds) {
7582                                 map.panInsideBounds(map.options.maxBounds);
7583                         }
7584
7585                 } else if (key in this._zoomKeys) {
7586                         map.setZoom(map.getZoom() + this._zoomKeys[key]);
7587
7588                 } else {
7589                         return;
7590                 }
7591
7592                 L.DomEvent.stop(e);
7593         }
7594 });
7595
7596 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
7597
7598
7599 /*
7600  * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
7601  */
7602
7603 L.Handler.MarkerDrag = L.Handler.extend({
7604         initialize: function (marker) {
7605                 this._marker = marker;
7606         },
7607
7608         addHooks: function () {
7609                 var icon = this._marker._icon;
7610                 if (!this._draggable) {
7611                         this._draggable = new L.Draggable(icon, icon);
7612                 }
7613
7614                 this._draggable
7615                         .on('dragstart', this._onDragStart, this)
7616                         .on('drag', this._onDrag, this)
7617                         .on('dragend', this._onDragEnd, this);
7618                 this._draggable.enable();
7619         },
7620
7621         removeHooks: function () {
7622                 this._draggable
7623                         .off('dragstart', this._onDragStart, this)
7624                         .off('drag', this._onDrag, this)
7625                         .off('dragend', this._onDragEnd, this);
7626
7627                 this._draggable.disable();
7628         },
7629
7630         moved: function () {
7631                 return this._draggable && this._draggable._moved;
7632         },
7633
7634         _onDragStart: function () {
7635                 this._marker
7636                     .closePopup()
7637                     .fire('movestart')
7638                     .fire('dragstart');
7639         },
7640
7641         _onDrag: function () {
7642                 var marker = this._marker,
7643                     shadow = marker._shadow,
7644                     iconPos = L.DomUtil.getPosition(marker._icon),
7645                     latlng = marker._map.layerPointToLatLng(iconPos);
7646
7647                 // update shadow position
7648                 if (shadow) {
7649                         L.DomUtil.setPosition(shadow, iconPos);
7650                 }
7651
7652                 marker._latlng = latlng;
7653
7654                 marker
7655                     .fire('move', {latlng: latlng})
7656                     .fire('drag');
7657         },
7658
7659         _onDragEnd: function () {
7660                 this._marker
7661                     .fire('moveend')
7662                     .fire('dragend');
7663         }
7664 });
7665
7666
7667 /*
7668  * L.Control is a base class for implementing map controls. Handles positioning.
7669  * All other controls extend from this class.
7670  */
7671
7672 L.Control = L.Class.extend({
7673         options: {
7674                 position: 'topright'
7675         },
7676
7677         initialize: function (options) {
7678                 L.setOptions(this, options);
7679         },
7680
7681         getPosition: function () {
7682                 return this.options.position;
7683         },
7684
7685         setPosition: function (position) {
7686                 var map = this._map;
7687
7688                 if (map) {
7689                         map.removeControl(this);
7690                 }
7691
7692                 this.options.position = position;
7693
7694                 if (map) {
7695                         map.addControl(this);
7696                 }
7697
7698                 return this;
7699         },
7700
7701         getContainer: function () {
7702                 return this._container;
7703         },
7704
7705         addTo: function (map) {
7706                 this._map = map;
7707
7708                 var container = this._container = this.onAdd(map),
7709                     pos = this.getPosition(),
7710                     corner = map._controlCorners[pos];
7711
7712                 L.DomUtil.addClass(container, 'leaflet-control');
7713
7714                 if (pos.indexOf('bottom') !== -1) {
7715                         corner.insertBefore(container, corner.firstChild);
7716                 } else {
7717                         corner.appendChild(container);
7718                 }
7719
7720                 return this;
7721         },
7722
7723         removeFrom: function (map) {
7724                 var pos = this.getPosition(),
7725                     corner = map._controlCorners[pos];
7726
7727                 corner.removeChild(this._container);
7728                 this._map = null;
7729
7730                 if (this.onRemove) {
7731                         this.onRemove(map);
7732                 }
7733
7734                 return this;
7735         }
7736 });
7737
7738 L.control = function (options) {
7739         return new L.Control(options);
7740 };
7741
7742
7743 // adds control-related methods to L.Map
7744
7745 L.Map.include({
7746         addControl: function (control) {
7747                 control.addTo(this);
7748                 return this;
7749         },
7750
7751         removeControl: function (control) {
7752                 control.removeFrom(this);
7753                 return this;
7754         },
7755
7756         _initControlPos: function () {
7757                 var corners = this._controlCorners = {},
7758                     l = 'leaflet-',
7759                     container = this._controlContainer =
7760                             L.DomUtil.create('div', l + 'control-container', this._container);
7761
7762                 function createCorner(vSide, hSide) {
7763                         var className = l + vSide + ' ' + l + hSide;
7764
7765                         corners[vSide + hSide] = L.DomUtil.create('div', className, container);
7766                 }
7767
7768                 createCorner('top', 'left');
7769                 createCorner('top', 'right');
7770                 createCorner('bottom', 'left');
7771                 createCorner('bottom', 'right');
7772         },
7773
7774         _clearControlPos: function () {
7775                 this._container.removeChild(this._controlContainer);
7776         }
7777 });
7778
7779
7780 /*
7781  * L.Control.Zoom is used for the default zoom buttons on the map.
7782  */
7783
7784 L.Control.Zoom = L.Control.extend({
7785         options: {
7786                 position: 'topleft'
7787         },
7788
7789         onAdd: function (map) {
7790                 var zoomName = 'leaflet-control-zoom',
7791                     container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
7792
7793                 this._map = map;
7794
7795                 this._zoomInButton  = this._createButton(
7796                         '+', 'Zoom in',  zoomName + '-in',  container, this._zoomIn,  this);
7797                 this._zoomOutButton = this._createButton(
7798                         '-', 'Zoom out', zoomName + '-out', container, this._zoomOut, this);
7799
7800                 map.on('zoomend zoomlevelschange', this._updateDisabled, this);
7801
7802                 return container;
7803         },
7804
7805         onRemove: function (map) {
7806                 map.off('zoomend zoomlevelschange', this._updateDisabled, this);
7807         },
7808
7809         _zoomIn: function (e) {
7810                 this._map.zoomIn(e.shiftKey ? 3 : 1);
7811         },
7812
7813         _zoomOut: function (e) {
7814                 this._map.zoomOut(e.shiftKey ? 3 : 1);
7815         },
7816
7817         _createButton: function (html, title, className, container, fn, context) {
7818                 var link = L.DomUtil.create('a', className, container);
7819                 link.innerHTML = html;
7820                 link.href = '#';
7821                 link.title = title;
7822
7823                 var stop = L.DomEvent.stopPropagation;
7824
7825                 L.DomEvent
7826                     .on(link, 'click', stop)
7827                     .on(link, 'mousedown', stop)
7828                     .on(link, 'dblclick', stop)
7829                     .on(link, 'click', L.DomEvent.preventDefault)
7830                     .on(link, 'click', fn, context);
7831
7832                 return link;
7833         },
7834
7835         _updateDisabled: function () {
7836                 var map = this._map,
7837                         className = 'leaflet-disabled';
7838
7839                 L.DomUtil.removeClass(this._zoomInButton, className);
7840                 L.DomUtil.removeClass(this._zoomOutButton, className);
7841
7842                 if (map._zoom === map.getMinZoom()) {
7843                         L.DomUtil.addClass(this._zoomOutButton, className);
7844                 }
7845                 if (map._zoom === map.getMaxZoom()) {
7846                         L.DomUtil.addClass(this._zoomInButton, className);
7847                 }
7848         }
7849 });
7850
7851 L.Map.mergeOptions({
7852         zoomControl: true
7853 });
7854
7855 L.Map.addInitHook(function () {
7856         if (this.options.zoomControl) {
7857                 this.zoomControl = new L.Control.Zoom();
7858                 this.addControl(this.zoomControl);
7859         }
7860 });
7861
7862 L.control.zoom = function (options) {
7863         return new L.Control.Zoom(options);
7864 };
7865
7866
7867
7868 /*
7869  * L.Control.Attribution is used for displaying attribution on the map (added by default).
7870  */
7871
7872 L.Control.Attribution = L.Control.extend({
7873         options: {
7874                 position: 'bottomright',
7875                 prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
7876         },
7877
7878         initialize: function (options) {
7879                 L.setOptions(this, options);
7880
7881                 this._attributions = {};
7882         },
7883
7884         onAdd: function (map) {
7885                 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
7886                 L.DomEvent.disableClickPropagation(this._container);
7887
7888                 map
7889                     .on('layeradd', this._onLayerAdd, this)
7890                     .on('layerremove', this._onLayerRemove, this);
7891
7892                 this._update();
7893
7894                 return this._container;
7895         },
7896
7897         onRemove: function (map) {
7898                 map
7899                     .off('layeradd', this._onLayerAdd)
7900                     .off('layerremove', this._onLayerRemove);
7901
7902         },
7903
7904         setPrefix: function (prefix) {
7905                 this.options.prefix = prefix;
7906                 this._update();
7907                 return this;
7908         },
7909
7910         addAttribution: function (text) {
7911                 if (!text) { return; }
7912
7913                 if (!this._attributions[text]) {
7914                         this._attributions[text] = 0;
7915                 }
7916                 this._attributions[text]++;
7917
7918                 this._update();
7919
7920                 return this;
7921         },
7922
7923         removeAttribution: function (text) {
7924                 if (!text) { return; }
7925
7926                 if (this._attributions[text]) {
7927                         this._attributions[text]--;
7928                         this._update();
7929                 }
7930
7931                 return this;
7932         },
7933
7934         _update: function () {
7935                 if (!this._map) { return; }
7936
7937                 var attribs = [];
7938
7939                 for (var i in this._attributions) {
7940                         if (this._attributions[i]) {
7941                                 attribs.push(i);
7942                         }
7943                 }
7944
7945                 var prefixAndAttribs = [];
7946
7947                 if (this.options.prefix) {
7948                         prefixAndAttribs.push(this.options.prefix);
7949                 }
7950                 if (attribs.length) {
7951                         prefixAndAttribs.push(attribs.join(', '));
7952                 }
7953
7954                 this._container.innerHTML = prefixAndAttribs.join(' | ');
7955         },
7956
7957         _onLayerAdd: function (e) {
7958                 if (e.layer.getAttribution) {
7959                         this.addAttribution(e.layer.getAttribution());
7960                 }
7961         },
7962
7963         _onLayerRemove: function (e) {
7964                 if (e.layer.getAttribution) {
7965                         this.removeAttribution(e.layer.getAttribution());
7966                 }
7967         }
7968 });
7969
7970 L.Map.mergeOptions({
7971         attributionControl: true
7972 });
7973
7974 L.Map.addInitHook(function () {
7975         if (this.options.attributionControl) {
7976                 this.attributionControl = (new L.Control.Attribution()).addTo(this);
7977         }
7978 });
7979
7980 L.control.attribution = function (options) {
7981         return new L.Control.Attribution(options);
7982 };
7983
7984
7985 /*
7986  * L.Control.Scale is used for displaying metric/imperial scale on the map.
7987  */
7988
7989 L.Control.Scale = L.Control.extend({
7990         options: {
7991                 position: 'bottomleft',
7992                 maxWidth: 100,
7993                 metric: true,
7994                 imperial: true,
7995                 updateWhenIdle: false
7996         },
7997
7998         onAdd: function (map) {
7999                 this._map = map;
8000
8001                 var className = 'leaflet-control-scale',
8002                     container = L.DomUtil.create('div', className),
8003                     options = this.options;
8004
8005                 this._addScales(options, className, container);
8006
8007                 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8008                 map.whenReady(this._update, this);
8009
8010                 return container;
8011         },
8012
8013         onRemove: function (map) {
8014                 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8015         },
8016
8017         _addScales: function (options, className, container) {
8018                 if (options.metric) {
8019                         this._mScale = L.DomUtil.create('div', className + '-line', container);
8020                 }
8021                 if (options.imperial) {
8022                         this._iScale = L.DomUtil.create('div', className + '-line', container);
8023                 }
8024         },
8025
8026         _update: function () {
8027                 var bounds = this._map.getBounds(),
8028                     centerLat = bounds.getCenter().lat,
8029                     halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
8030                     dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
8031
8032                     size = this._map.getSize(),
8033                     options = this.options,
8034                     maxMeters = 0;
8035
8036                 if (size.x > 0) {
8037                         maxMeters = dist * (options.maxWidth / size.x);
8038                 }
8039
8040                 this._updateScales(options, maxMeters);
8041         },
8042
8043         _updateScales: function (options, maxMeters) {
8044                 if (options.metric && maxMeters) {
8045                         this._updateMetric(maxMeters);
8046                 }
8047
8048                 if (options.imperial && maxMeters) {
8049                         this._updateImperial(maxMeters);
8050                 }
8051         },
8052
8053         _updateMetric: function (maxMeters) {
8054                 var meters = this._getRoundNum(maxMeters);
8055
8056                 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
8057                 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
8058         },
8059
8060         _updateImperial: function (maxMeters) {
8061                 var maxFeet = maxMeters * 3.2808399,
8062                     scale = this._iScale,
8063                     maxMiles, miles, feet;
8064
8065                 if (maxFeet > 5280) {
8066                         maxMiles = maxFeet / 5280;
8067                         miles = this._getRoundNum(maxMiles);
8068
8069                         scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
8070                         scale.innerHTML = miles + ' mi';
8071
8072                 } else {
8073                         feet = this._getRoundNum(maxFeet);
8074
8075                         scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
8076                         scale.innerHTML = feet + ' ft';
8077                 }
8078         },
8079
8080         _getScaleWidth: function (ratio) {
8081                 return Math.round(this.options.maxWidth * ratio) - 10;
8082         },
8083
8084         _getRoundNum: function (num) {
8085                 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
8086                     d = num / pow10;
8087
8088                 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
8089
8090                 return pow10 * d;
8091         }
8092 });
8093
8094 L.control.scale = function (options) {
8095         return new L.Control.Scale(options);
8096 };
8097
8098
8099 /*
8100  * L.Control.Layers is a control to allow users to switch between different layers on the map.
8101  */
8102
8103 L.Control.Layers = L.Control.extend({
8104         options: {
8105                 collapsed: true,
8106                 position: 'topright',
8107                 autoZIndex: true
8108         },
8109
8110         initialize: function (baseLayers, overlays, options) {
8111                 L.setOptions(this, options);
8112
8113                 this._layers = {};
8114                 this._lastZIndex = 0;
8115                 this._handlingClick = false;
8116
8117                 for (var i in baseLayers) {
8118                         this._addLayer(baseLayers[i], i);
8119                 }
8120
8121                 for (i in overlays) {
8122                         this._addLayer(overlays[i], i, true);
8123                 }
8124         },
8125
8126         onAdd: function (map) {
8127                 this._initLayout();
8128                 this._update();
8129
8130                 map
8131                     .on('layeradd', this._onLayerChange, this)
8132                     .on('layerremove', this._onLayerChange, this);
8133
8134                 return this._container;
8135         },
8136
8137         onRemove: function (map) {
8138                 map
8139                     .off('layeradd', this._onLayerChange)
8140                     .off('layerremove', this._onLayerChange);
8141         },
8142
8143         addBaseLayer: function (layer, name) {
8144                 this._addLayer(layer, name);
8145                 this._update();
8146                 return this;
8147         },
8148
8149         addOverlay: function (layer, name) {
8150                 this._addLayer(layer, name, true);
8151                 this._update();
8152                 return this;
8153         },
8154
8155         removeLayer: function (layer) {
8156                 var id = L.stamp(layer);
8157                 delete this._layers[id];
8158                 this._update();
8159                 return this;
8160         },
8161
8162         _initLayout: function () {
8163                 var className = 'leaflet-control-layers',
8164                     container = this._container = L.DomUtil.create('div', className);
8165
8166                 //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
8167                 container.setAttribute('aria-haspopup', true);
8168
8169                 if (!L.Browser.touch) {
8170                         L.DomEvent.disableClickPropagation(container);
8171                         L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
8172                 } else {
8173                         L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
8174                 }
8175
8176                 var form = this._form = L.DomUtil.create('form', className + '-list');
8177
8178                 if (this.options.collapsed) {
8179                         if (!L.Browser.android) {
8180                                 L.DomEvent
8181                                     .on(container, 'mouseover', this._expand, this)
8182                                     .on(container, 'mouseout', this._collapse, this);
8183                         }
8184                         var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
8185                         link.href = '#';
8186                         link.title = 'Layers';
8187
8188                         if (L.Browser.touch) {
8189                                 L.DomEvent
8190                                     .on(link, 'click', L.DomEvent.stop)
8191                                     .on(link, 'click', this._expand, this);
8192                         }
8193                         else {
8194                                 L.DomEvent.on(link, 'focus', this._expand, this);
8195                         }
8196
8197                         this._map.on('click', this._collapse, this);
8198                         // TODO keyboard accessibility
8199                 } else {
8200                         this._expand();
8201                 }
8202
8203                 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
8204                 this._separator = L.DomUtil.create('div', className + '-separator', form);
8205                 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
8206
8207                 container.appendChild(form);
8208         },
8209
8210         _addLayer: function (layer, name, overlay) {
8211                 var id = L.stamp(layer);
8212
8213                 this._layers[id] = {
8214                         layer: layer,
8215                         name: name,
8216                         overlay: overlay
8217                 };
8218
8219                 if (this.options.autoZIndex && layer.setZIndex) {
8220                         this._lastZIndex++;
8221                         layer.setZIndex(this._lastZIndex);
8222                 }
8223         },
8224
8225         _update: function () {
8226                 if (!this._container) {
8227                         return;
8228                 }
8229
8230                 this._baseLayersList.innerHTML = '';
8231                 this._overlaysList.innerHTML = '';
8232
8233                 var baseLayersPresent = false,
8234                     overlaysPresent = false,
8235                     i, obj;
8236
8237                 for (i in this._layers) {
8238                         obj = this._layers[i];
8239                         this._addItem(obj);
8240                         overlaysPresent = overlaysPresent || obj.overlay;
8241                         baseLayersPresent = baseLayersPresent || !obj.overlay;
8242                 }
8243
8244                 this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
8245         },
8246
8247         _onLayerChange: function (e) {
8248                 var obj = this._layers[L.stamp(e.layer)];
8249
8250                 if (!obj) { return; }
8251
8252                 if (!this._handlingClick) {
8253                         this._update();
8254                 }
8255
8256                 var type = obj.overlay ?
8257                         (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
8258                         (e.type === 'layeradd' ? 'baselayerchange' : null);
8259
8260                 if (type) {
8261                         this._map.fire(type, obj);
8262                 }
8263         },
8264
8265         // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
8266         _createRadioElement: function (name, checked) {
8267
8268                 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
8269                 if (checked) {
8270                         radioHtml += ' checked="checked"';
8271                 }
8272                 radioHtml += '/>';
8273
8274                 var radioFragment = document.createElement('div');
8275                 radioFragment.innerHTML = radioHtml;
8276
8277                 return radioFragment.firstChild;
8278         },
8279
8280         _addItem: function (obj) {
8281                 var label = document.createElement('label'),
8282                     input,
8283                     checked = this._map.hasLayer(obj.layer);
8284
8285                 if (obj.overlay) {
8286                         input = document.createElement('input');
8287                         input.type = 'checkbox';
8288                         input.className = 'leaflet-control-layers-selector';
8289                         input.defaultChecked = checked;
8290                 } else {
8291                         input = this._createRadioElement('leaflet-base-layers', checked);
8292                 }
8293
8294                 input.layerId = L.stamp(obj.layer);
8295
8296                 L.DomEvent.on(input, 'click', this._onInputClick, this);
8297
8298                 var name = document.createElement('span');
8299                 name.innerHTML = ' ' + obj.name;
8300
8301                 label.appendChild(input);
8302                 label.appendChild(name);
8303
8304                 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
8305                 container.appendChild(label);
8306
8307                 return label;
8308         },
8309
8310         _onInputClick: function () {
8311                 var i, input, obj,
8312                     inputs = this._form.getElementsByTagName('input'),
8313                     inputsLen = inputs.length;
8314
8315                 this._handlingClick = true;
8316
8317                 for (i = 0; i < inputsLen; i++) {
8318                         input = inputs[i];
8319                         obj = this._layers[input.layerId];
8320
8321                         if (input.checked && !this._map.hasLayer(obj.layer)) {
8322                                 this._map.addLayer(obj.layer);
8323
8324                         } else if (!input.checked && this._map.hasLayer(obj.layer)) {
8325                                 this._map.removeLayer(obj.layer);
8326                         }
8327                 }
8328
8329                 this._handlingClick = false;
8330         },
8331
8332         _expand: function () {
8333                 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
8334         },
8335
8336         _collapse: function () {
8337                 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
8338         }
8339 });
8340
8341 L.control.layers = function (baseLayers, overlays, options) {
8342         return new L.Control.Layers(baseLayers, overlays, options);
8343 };
8344
8345
8346 /*
8347  * L.PosAnimation is used by Leaflet internally for pan animations.
8348  */
8349
8350 L.PosAnimation = L.Class.extend({
8351         includes: L.Mixin.Events,
8352
8353         run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8354                 this.stop();
8355
8356                 this._el = el;
8357                 this._inProgress = true;
8358                 this._newPos = newPos;
8359
8360                 this.fire('start');
8361
8362                 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
8363                         's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
8364
8365                 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8366                 L.DomUtil.setPosition(el, newPos);
8367
8368                 // toggle reflow, Chrome flickers for some reason if you don't do this
8369                 L.Util.falseFn(el.offsetWidth);
8370
8371                 // there's no native way to track value updates of transitioned properties, so we imitate this
8372                 this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
8373         },
8374
8375         stop: function () {
8376                 if (!this._inProgress) { return; }
8377
8378                 // if we just removed the transition property, the element would jump to its final position,
8379                 // so we need to make it stay at the current position
8380
8381                 L.DomUtil.setPosition(this._el, this._getPos());
8382                 this._onTransitionEnd();
8383                 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
8384         },
8385
8386         _onStep: function () {
8387                 var stepPos = this._getPos();
8388                 if (!stepPos) {
8389                         this._onTransitionEnd();
8390                         return;
8391                 }
8392                 // jshint camelcase: false
8393                 // make L.DomUtil.getPosition return intermediate position value during animation
8394                 this._el._leaflet_pos = stepPos;
8395
8396                 this.fire('step');
8397         },
8398
8399         // you can't easily get intermediate values of properties animated with CSS3 Transitions,
8400         // we need to parse computed style (in case of transform it returns matrix string)
8401
8402         _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
8403
8404         _getPos: function () {
8405                 var left, top, matches,
8406                     el = this._el,
8407                     style = window.getComputedStyle(el);
8408
8409                 if (L.Browser.any3d) {
8410                         matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
8411                         if (!matches) { return; }
8412                         left = parseFloat(matches[1]);
8413                         top  = parseFloat(matches[2]);
8414                 } else {
8415                         left = parseFloat(style.left);
8416                         top  = parseFloat(style.top);
8417                 }
8418
8419                 return new L.Point(left, top, true);
8420         },
8421
8422         _onTransitionEnd: function () {
8423                 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8424
8425                 if (!this._inProgress) { return; }
8426                 this._inProgress = false;
8427
8428                 this._el.style[L.DomUtil.TRANSITION] = '';
8429
8430                 // jshint camelcase: false
8431                 // make sure L.DomUtil.getPosition returns the final position value after animation
8432                 this._el._leaflet_pos = this._newPos;
8433
8434                 clearInterval(this._stepTimer);
8435
8436                 this.fire('step').fire('end');
8437         }
8438
8439 });
8440
8441
8442 /*
8443  * Extends L.Map to handle panning animations.
8444  */
8445
8446 L.Map.include({
8447
8448         setView: function (center, zoom, options) {
8449
8450                 zoom = this._limitZoom(zoom);
8451                 center = L.latLng(center);
8452                 options = options || {};
8453
8454                 if (this._panAnim) {
8455                         this._panAnim.stop();
8456                 }
8457
8458                 if (this._loaded && !options.reset && options !== true) {
8459
8460                         if (options.animate !== undefined) {
8461                                 options.zoom = L.extend({animate: options.animate}, options.zoom);
8462                                 options.pan = L.extend({animate: options.animate}, options.pan);
8463                         }
8464
8465                         // try animating pan or zoom
8466                         var animated = (this._zoom !== zoom) ?
8467                                 this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
8468                                 this._tryAnimatedPan(center, options.pan);
8469
8470                         if (animated) {
8471                                 // prevent resize handler call, the view will refresh after animation anyway
8472                                 clearTimeout(this._sizeTimer);
8473                                 return this;
8474                         }
8475                 }
8476
8477                 // animation didn't start, just reset the map view
8478                 this._resetView(center, zoom);
8479
8480                 return this;
8481         },
8482
8483         panBy: function (offset, options) {
8484                 offset = L.point(offset).round();
8485                 options = options || {};
8486
8487                 if (!offset.x && !offset.y) {
8488                         return this;
8489                 }
8490
8491                 if (!this._panAnim) {
8492                         this._panAnim = new L.PosAnimation();
8493
8494                         this._panAnim.on({
8495                                 'step': this._onPanTransitionStep,
8496                                 'end': this._onPanTransitionEnd
8497                         }, this);
8498                 }
8499
8500                 // don't fire movestart if animating inertia
8501                 if (!options.noMoveStart) {
8502                         this.fire('movestart');
8503                 }
8504
8505                 // animate pan unless animate: false specified
8506                 if (options.animate !== false) {
8507                         L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
8508
8509                         var newPos = this._getMapPanePos().subtract(offset);
8510                         this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
8511                 } else {
8512                         this._rawPanBy(offset);
8513                         this.fire('move').fire('moveend');
8514                 }
8515
8516                 return this;
8517         },
8518
8519         _onPanTransitionStep: function () {
8520                 this.fire('move');
8521         },
8522
8523         _onPanTransitionEnd: function () {
8524                 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
8525                 this.fire('moveend');
8526         },
8527
8528         _tryAnimatedPan: function (center, options) {
8529                 // difference between the new and current centers in pixels
8530                 var offset = this._getCenterOffset(center)._floor();
8531
8532                 // don't animate too far unless animate: true specified in options
8533                 if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
8534
8535                 this.panBy(offset, options);
8536
8537                 return true;
8538         }
8539 });
8540
8541
8542 /*
8543  * L.PosAnimation fallback implementation that powers Leaflet pan animations
8544  * in browsers that don't support CSS3 Transitions.
8545  */
8546
8547 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8548
8549         run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8550                 this.stop();
8551
8552                 this._el = el;
8553                 this._inProgress = true;
8554                 this._duration = duration || 0.25;
8555                 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8556
8557                 this._startPos = L.DomUtil.getPosition(el);
8558                 this._offset = newPos.subtract(this._startPos);
8559                 this._startTime = +new Date();
8560
8561                 this.fire('start');
8562
8563                 this._animate();
8564         },
8565
8566         stop: function () {
8567                 if (!this._inProgress) { return; }
8568
8569                 this._step();
8570                 this._complete();
8571         },
8572
8573         _animate: function () {
8574                 // animation loop
8575                 this._animId = L.Util.requestAnimFrame(this._animate, this);
8576                 this._step();
8577         },
8578
8579         _step: function () {
8580                 var elapsed = (+new Date()) - this._startTime,
8581                     duration = this._duration * 1000;
8582
8583                 if (elapsed < duration) {
8584                         this._runFrame(this._easeOut(elapsed / duration));
8585                 } else {
8586                         this._runFrame(1);
8587                         this._complete();
8588                 }
8589         },
8590
8591         _runFrame: function (progress) {
8592                 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8593                 L.DomUtil.setPosition(this._el, pos);
8594
8595                 this.fire('step');
8596         },
8597
8598         _complete: function () {
8599                 L.Util.cancelAnimFrame(this._animId);
8600
8601                 this._inProgress = false;
8602                 this.fire('end');
8603         },
8604
8605         _easeOut: function (t) {
8606                 return 1 - Math.pow(1 - t, this._easeOutPower);
8607         }
8608 });
8609
8610
8611 /*
8612  * Extends L.Map to handle zoom animations.
8613  */
8614
8615 L.Map.mergeOptions({
8616         zoomAnimation: true,
8617         zoomAnimationThreshold: 4
8618 });
8619
8620 if (L.DomUtil.TRANSITION) {
8621
8622         L.Map.addInitHook(function () {
8623                 // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
8624                 this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
8625                                 L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
8626
8627                 // zoom transitions run with the same duration for all layers, so if one of transitionend events
8628                 // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
8629                 if (this._zoomAnimated) {
8630                         L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8631                 }
8632         });
8633 }
8634
8635 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8636
8637         _catchTransitionEnd: function () {
8638                 if (this._animatingZoom) {
8639                         this._onZoomTransitionEnd();
8640                 }
8641         },
8642
8643         _nothingToAnimate: function () {
8644                 return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
8645         },
8646
8647         _tryAnimatedZoom: function (center, zoom, options) {
8648
8649                 if (this._animatingZoom) { return true; }
8650
8651                 options = options || {};
8652
8653                 // don't animate if disabled, not supported or zoom difference is too large
8654                 if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
8655                         Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
8656
8657                 // offset is the pixel coords of the zoom origin relative to the current center
8658                 var scale = this.getZoomScale(zoom),
8659                     offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
8660                         origin = this._getCenterLayerPoint()._add(offset);
8661
8662                 // don't animate if the zoom origin isn't within one screen from the current center, unless forced
8663                 if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
8664
8665                 this
8666                     .fire('movestart')
8667                     .fire('zoomstart');
8668
8669                 this._animateZoom(center, zoom, origin, scale, null, true);
8670
8671                 return true;
8672         },
8673
8674         _animateZoom: function (center, zoom, origin, scale, delta, backwards) {
8675
8676                 this._animatingZoom = true;
8677
8678                 // put transform transition on all layers with leaflet-zoom-animated class
8679                 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8680
8681                 // remember what center/zoom to set after animation
8682                 this._animateToCenter = center;
8683                 this._animateToZoom = zoom;
8684
8685                 // disable any dragging during animation
8686                 if (L.Draggable) {
8687                         L.Draggable._disabled = true;
8688                 }
8689
8690                 this.fire('zoomanim', {
8691                         center: center,
8692                         zoom: zoom,
8693                         origin: origin,
8694                         scale: scale,
8695                         delta: delta,
8696                         backwards: backwards
8697                 });
8698         },
8699
8700         _onZoomTransitionEnd: function () {
8701
8702                 this._animatingZoom = false;
8703
8704                 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8705
8706                 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8707
8708                 if (L.Draggable) {
8709                         L.Draggable._disabled = false;
8710                 }
8711         }
8712 });
8713
8714
8715 /*
8716         Zoom animation logic for L.TileLayer.
8717 */
8718
8719 L.TileLayer.include({
8720         _animateZoom: function (e) {
8721                 if (!this._animating) {
8722                         this._animating = true;
8723                         this._prepareBgBuffer();
8724                 }
8725
8726                 var bg = this._bgBuffer,
8727                     transform = L.DomUtil.TRANSFORM,
8728                     initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
8729                     scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
8730
8731                 bg.style[transform] = e.backwards ?
8732                                 scaleStr + ' ' + initialTransform :
8733                                 initialTransform + ' ' + scaleStr;
8734         },
8735
8736         _endZoomAnim: function () {
8737                 var front = this._tileContainer,
8738                     bg = this._bgBuffer;
8739
8740                 front.style.visibility = '';
8741                 front.parentNode.appendChild(front); // Bring to fore
8742
8743                 // force reflow
8744                 L.Util.falseFn(bg.offsetWidth);
8745
8746                 this._animating = false;
8747         },
8748
8749         _clearBgBuffer: function () {
8750                 var map = this._map;
8751
8752                 if (map && !map._animatingZoom && !map.touchZoom._zooming) {
8753                         this._bgBuffer.innerHTML = '';
8754                         this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
8755                 }
8756         },
8757
8758         _prepareBgBuffer: function () {
8759
8760                 var front = this._tileContainer,
8761                     bg = this._bgBuffer;
8762
8763                 // if foreground layer doesn't have many tiles but bg layer does,
8764                 // keep the existing bg layer and just zoom it some more
8765
8766                 var bgLoaded = this._getLoadedTilesPercentage(bg),
8767                     frontLoaded = this._getLoadedTilesPercentage(front);
8768
8769                 if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
8770
8771                         front.style.visibility = 'hidden';
8772                         this._stopLoadingImages(front);
8773                         return;
8774                 }
8775
8776                 // prepare the buffer to become the front tile pane
8777                 bg.style.visibility = 'hidden';
8778                 bg.style[L.DomUtil.TRANSFORM] = '';
8779
8780                 // switch out the current layer to be the new bg layer (and vice-versa)
8781                 this._tileContainer = bg;
8782                 bg = this._bgBuffer = front;
8783
8784                 this._stopLoadingImages(bg);
8785
8786                 //prevent bg buffer from clearing right after zoom
8787                 clearTimeout(this._clearBgBufferTimer);
8788         },
8789
8790         _getLoadedTilesPercentage: function (container) {
8791                 var tiles = container.getElementsByTagName('img'),
8792                     i, len, count = 0;
8793
8794                 for (i = 0, len = tiles.length; i < len; i++) {
8795                         if (tiles[i].complete) {
8796                                 count++;
8797                         }
8798                 }
8799                 return count / len;
8800         },
8801
8802         // stops loading all tiles in the background layer
8803         _stopLoadingImages: function (container) {
8804                 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
8805                     i, len, tile;
8806
8807                 for (i = 0, len = tiles.length; i < len; i++) {
8808                         tile = tiles[i];
8809
8810                         if (!tile.complete) {
8811                                 tile.onload = L.Util.falseFn;
8812                                 tile.onerror = L.Util.falseFn;
8813                                 tile.src = L.Util.emptyImageUrl;
8814
8815                                 tile.parentNode.removeChild(tile);
8816                         }
8817                 }
8818         }
8819 });
8820
8821
8822 /*
8823  * Provides L.Map with convenient shortcuts for using browser geolocation features.
8824  */
8825
8826 L.Map.include({
8827         _defaultLocateOptions: {
8828                 watch: false,
8829                 setView: false,
8830                 maxZoom: Infinity,
8831                 timeout: 10000,
8832                 maximumAge: 0,
8833                 enableHighAccuracy: false
8834         },
8835
8836         locate: function (/*Object*/ options) {
8837
8838                 options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
8839
8840                 if (!navigator.geolocation) {
8841                         this._handleGeolocationError({
8842                                 code: 0,
8843                                 message: 'Geolocation not supported.'
8844                         });
8845                         return this;
8846                 }
8847
8848                 var onResponse = L.bind(this._handleGeolocationResponse, this),
8849                         onError = L.bind(this._handleGeolocationError, this);
8850
8851                 if (options.watch) {
8852                         this._locationWatchId =
8853                                 navigator.geolocation.watchPosition(onResponse, onError, options);
8854                 } else {
8855                         navigator.geolocation.getCurrentPosition(onResponse, onError, options);
8856                 }
8857                 return this;
8858         },
8859
8860         stopLocate: function () {
8861                 if (navigator.geolocation) {
8862                         navigator.geolocation.clearWatch(this._locationWatchId);
8863                 }
8864                 if (this._locateOptions) {
8865                         this._locateOptions.setView = false;
8866                 }
8867                 return this;
8868         },
8869
8870         _handleGeolocationError: function (error) {
8871                 var c = error.code,
8872                     message = error.message ||
8873                             (c === 1 ? 'permission denied' :
8874                             (c === 2 ? 'position unavailable' : 'timeout'));
8875
8876                 if (this._locateOptions.setView && !this._loaded) {
8877                         this.fitWorld();
8878                 }
8879
8880                 this.fire('locationerror', {
8881                         code: c,
8882                         message: 'Geolocation error: ' + message + '.'
8883                 });
8884         },
8885
8886         _handleGeolocationResponse: function (pos) {
8887                 var lat = pos.coords.latitude,
8888                     lng = pos.coords.longitude,
8889                     latlng = new L.LatLng(lat, lng),
8890
8891                     latAccuracy = 180 * pos.coords.accuracy / 40075017,
8892                     lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
8893
8894                     bounds = L.latLngBounds(
8895                             [lat - latAccuracy, lng - lngAccuracy],
8896                             [lat + latAccuracy, lng + lngAccuracy]),
8897
8898                     options = this._locateOptions;
8899
8900                 if (options.setView) {
8901                         var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
8902                         this.setView(latlng, zoom);
8903                 }
8904
8905                 var data = {
8906                         latlng: latlng,
8907                         bounds: bounds
8908                 };
8909
8910                 for (var i in pos.coords) {
8911                         if (typeof pos.coords[i] === 'number') {
8912                                 data[i] = pos.coords[i];
8913                         }
8914                 }
8915
8916                 this.fire('locationfound', data);
8917         }
8918 });
8919
8920
8921 }(window, document));