aecf2677ba664db88dab18925a9771c7aedffaf0
[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.4';
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 && window.navigator.maxTouchPoints) ||
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                         var pos = this._map.latLngToLayerPoint(this._latlng).round();
3541                         L.Util.requestAnimFrame(function () {
3542                                 this._setPos(pos);
3543                         }, this);
3544                 }
3545
3546                 return this;
3547         },
3548
3549         _initIcon: function () {
3550                 var options = this.options,
3551                     map = this._map,
3552                     animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3553                     classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3554
3555                 var icon = options.icon.createIcon(this._icon),
3556                         addIcon = false;
3557
3558                 // if we're not reusing the icon, remove the old one and init new one
3559                 if (icon !== this._icon) {
3560                         if (this._icon) {
3561                                 this._removeIcon();
3562                         }
3563                         addIcon = true;
3564
3565                         if (options.title) {
3566                                 icon.title = options.title;
3567                         }
3568                         
3569                         if (options.alt) {
3570                                 icon.alt = options.alt;
3571                         }
3572                 }
3573
3574                 L.DomUtil.addClass(icon, classToAdd);
3575
3576                 if (options.keyboard) {
3577                         icon.tabIndex = '0';
3578                 }
3579
3580                 this._icon = icon;
3581
3582                 this._initInteraction();
3583
3584                 if (options.riseOnHover) {
3585                         L.DomEvent
3586                                 .on(icon, 'mouseover', this._bringToFront, this)
3587                                 .on(icon, 'mouseout', this._resetZIndex, this);
3588                 }
3589
3590                 var newShadow = options.icon.createShadow(this._shadow),
3591                         addShadow = false;
3592
3593                 if (newShadow !== this._shadow) {
3594                         this._removeShadow();
3595                         addShadow = true;
3596                 }
3597
3598                 if (newShadow) {
3599                         L.DomUtil.addClass(newShadow, classToAdd);
3600                 }
3601                 this._shadow = newShadow;
3602
3603
3604                 if (options.opacity < 1) {
3605                         this._updateOpacity();
3606                 }
3607
3608
3609                 var panes = this._map._panes;
3610
3611                 if (addIcon) {
3612                         panes.markerPane.appendChild(this._icon);
3613                 }
3614
3615                 if (newShadow && addShadow) {
3616                         panes.shadowPane.appendChild(this._shadow);
3617                 }
3618         },
3619
3620         _removeIcon: function () {
3621                 if (this.options.riseOnHover) {
3622                         L.DomEvent
3623                             .off(this._icon, 'mouseover', this._bringToFront)
3624                             .off(this._icon, 'mouseout', this._resetZIndex);
3625                 }
3626
3627                 this._map._panes.markerPane.removeChild(this._icon);
3628
3629                 this._icon = null;
3630         },
3631
3632         _removeShadow: function () {
3633                 if (this._shadow) {
3634                         this._map._panes.shadowPane.removeChild(this._shadow);
3635                 }
3636                 this._shadow = null;
3637         },
3638
3639         _setPos: function (pos) {
3640                 L.DomUtil.setPosition(this._icon, pos);
3641
3642                 if (this._shadow) {
3643                         L.DomUtil.setPosition(this._shadow, pos);
3644                 }
3645
3646                 this._zIndex = pos.y + this.options.zIndexOffset;
3647
3648                 this._resetZIndex();
3649         },
3650
3651         _updateZIndex: function (offset) {
3652                 this._icon.style.zIndex = this._zIndex + offset;
3653         },
3654
3655         _animateZoom: function (opt) {
3656                 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
3657
3658                 this._setPos(pos);
3659         },
3660
3661         _initInteraction: function () {
3662
3663                 if (!this.options.clickable) { return; }
3664
3665                 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3666
3667                 var icon = this._icon,
3668                     events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3669
3670                 L.DomUtil.addClass(icon, 'leaflet-clickable');
3671                 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3672                 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3673
3674                 for (var i = 0; i < events.length; i++) {
3675                         L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3676                 }
3677
3678                 if (L.Handler.MarkerDrag) {
3679                         this.dragging = new L.Handler.MarkerDrag(this);
3680
3681                         if (this.options.draggable) {
3682                                 this.dragging.enable();
3683                         }
3684                 }
3685         },
3686
3687         _onMouseClick: function (e) {
3688                 var wasDragged = this.dragging && this.dragging.moved();
3689
3690                 if (this.hasEventListeners(e.type) || wasDragged) {
3691                         L.DomEvent.stopPropagation(e);
3692                 }
3693
3694                 if (wasDragged) { return; }
3695
3696                 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3697
3698                 this.fire(e.type, {
3699                         originalEvent: e,
3700                         latlng: this._latlng
3701                 });
3702         },
3703
3704         _onKeyPress: function (e) {
3705                 if (e.keyCode === 13) {
3706                         this.fire('click', {
3707                                 originalEvent: e,
3708                                 latlng: this._latlng
3709                         });
3710                 }
3711         },
3712
3713         _fireMouseEvent: function (e) {
3714
3715                 this.fire(e.type, {
3716                         originalEvent: e,
3717                         latlng: this._latlng
3718                 });
3719
3720                 // TODO proper custom event propagation
3721                 // this line will always be called if marker is in a FeatureGroup
3722                 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3723                         L.DomEvent.preventDefault(e);
3724                 }
3725                 if (e.type !== 'mousedown') {
3726                         L.DomEvent.stopPropagation(e);
3727                 } else {
3728                         L.DomEvent.preventDefault(e);
3729                 }
3730         },
3731
3732         setOpacity: function (opacity) {
3733                 this.options.opacity = opacity;
3734                 if (this._map) {
3735                         this._updateOpacity();
3736                 }
3737
3738                 return this;
3739         },
3740
3741         _updateOpacity: function () {
3742                 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3743                 if (this._shadow) {
3744                         L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3745                 }
3746         },
3747
3748         _bringToFront: function () {
3749                 this._updateZIndex(this.options.riseOffset);
3750         },
3751
3752         _resetZIndex: function () {
3753                 this._updateZIndex(0);
3754         }
3755 });
3756
3757 L.marker = function (latlng, options) {
3758         return new L.Marker(latlng, options);
3759 };
3760
3761
3762 /*
3763  * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3764  * to use with L.Marker.
3765  */
3766
3767 L.DivIcon = L.Icon.extend({
3768         options: {
3769                 iconSize: [12, 12], // also can be set through CSS
3770                 /*
3771                 iconAnchor: (Point)
3772                 popupAnchor: (Point)
3773                 html: (String)
3774                 bgPos: (Point)
3775                 */
3776                 className: 'leaflet-div-icon',
3777                 html: false
3778         },
3779
3780         createIcon: function (oldIcon) {
3781                 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3782                     options = this.options;
3783
3784                 if (options.html !== false) {
3785                         div.innerHTML = options.html;
3786                 } else {
3787                         div.innerHTML = '';
3788                 }
3789
3790                 if (options.bgPos) {
3791                         div.style.backgroundPosition =
3792                                 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3793                 }
3794
3795                 this._setIconStyles(div, 'icon');
3796                 return div;
3797         },
3798
3799         createShadow: function () {
3800                 return null;
3801         }
3802 });
3803
3804 L.divIcon = function (options) {
3805         return new L.DivIcon(options);
3806 };
3807
3808
3809 /*
3810  * L.Popup is used for displaying popups on the map.
3811  */
3812
3813 L.Map.mergeOptions({
3814         closePopupOnClick: true
3815 });
3816
3817 L.Popup = L.Class.extend({
3818         includes: L.Mixin.Events,
3819
3820         options: {
3821                 minWidth: 50,
3822                 maxWidth: 300,
3823                 // maxHeight: null,
3824                 autoPan: true,
3825                 closeButton: true,
3826                 offset: [0, 7],
3827                 autoPanPadding: [5, 5],
3828                 // autoPanPaddingTopLeft: null,
3829                 // autoPanPaddingBottomRight: null,
3830                 keepInView: false,
3831                 className: '',
3832                 zoomAnimation: true
3833         },
3834
3835         initialize: function (options, source) {
3836                 L.setOptions(this, options);
3837
3838                 this._source = source;
3839                 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3840                 this._isOpen = false;
3841         },
3842
3843         onAdd: function (map) {
3844                 this._map = map;
3845
3846                 if (!this._container) {
3847                         this._initLayout();
3848                 }
3849
3850                 var animFade = map.options.fadeAnimation;
3851
3852                 if (animFade) {
3853                         L.DomUtil.setOpacity(this._container, 0);
3854                 }
3855                 map._panes.popupPane.appendChild(this._container);
3856
3857                 map.on(this._getEvents(), this);
3858
3859                 this.update();
3860
3861                 if (animFade) {
3862                         L.DomUtil.setOpacity(this._container, 1);
3863                 }
3864
3865                 this.fire('open');
3866
3867                 map.fire('popupopen', {popup: this});
3868
3869                 if (this._source) {
3870                         this._source.fire('popupopen', {popup: this});
3871                 }
3872         },
3873
3874         addTo: function (map) {
3875                 map.addLayer(this);
3876                 return this;
3877         },
3878
3879         openOn: function (map) {
3880                 map.openPopup(this);
3881                 return this;
3882         },
3883
3884         onRemove: function (map) {
3885                 map._panes.popupPane.removeChild(this._container);
3886
3887                 L.Util.falseFn(this._container.offsetWidth); // force reflow
3888
3889                 map.off(this._getEvents(), this);
3890
3891                 if (map.options.fadeAnimation) {
3892                         L.DomUtil.setOpacity(this._container, 0);
3893                 }
3894
3895                 this._map = null;
3896
3897                 this.fire('close');
3898
3899                 map.fire('popupclose', {popup: this});
3900
3901                 if (this._source) {
3902                         this._source.fire('popupclose', {popup: this});
3903                 }
3904         },
3905
3906         getLatLng: function () {
3907                 return this._latlng;
3908         },
3909
3910         setLatLng: function (latlng) {
3911                 this._latlng = L.latLng(latlng);
3912                 if (this._map) {
3913                         this._updatePosition();
3914                         this._adjustPan();
3915                 }
3916                 return this;
3917         },
3918
3919         getContent: function () {
3920                 return this._content;
3921         },
3922
3923         setContent: function (content) {
3924                 this._content = content;
3925                 this.update();
3926                 return this;
3927         },
3928
3929         update: function () {
3930                 if (!this._map) { return; }
3931
3932                 this._container.style.visibility = 'hidden';
3933
3934                 this._updateContent();
3935                 this._updateLayout();
3936                 this._updatePosition();
3937
3938                 this._container.style.visibility = '';
3939
3940                 this._adjustPan();
3941         },
3942
3943         _getEvents: function () {
3944   &n