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