]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/leaflet/leaflet.js
2b66295fc11d550ff12ac9f474b6684a0b635689
[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';
11
12 // define Leaflet for Node module pattern loaders, including Browserify
13 if (typeof module === 'object' && typeof module.exports === 'object') {
14         module.exports = L;
15
16 // define Leaflet as an AMD module
17 } else if (typeof define === 'function' && define.amd) {
18         define(L);
19 }
20
21 // define Leaflet as a global L variable, saving the original L to restore later if needed
22
23 L.noConflict = function () {
24         window.L = oldL;
25         return this;
26 };
27
28 window.L = L;
29
30
31 /*
32  * L.Util contains various utility functions used throughout Leaflet code.
33  */
34
35 L.Util = {
36         extend: function (dest) { // (Object[, Object, ...]) ->
37                 var sources = Array.prototype.slice.call(arguments, 1),
38                     i, j, len, src;
39
40                 for (j = 0, len = sources.length; j < len; j++) {
41                         src = sources[j] || {};
42                         for (i in src) {
43                                 if (src.hasOwnProperty(i)) {
44                                         dest[i] = src[i];
45                                 }
46                         }
47                 }
48                 return dest;
49         },
50
51         bind: function (fn, obj) { // (Function, Object) -> Function
52                 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
53                 return function () {
54                         return fn.apply(obj, args || arguments);
55                 };
56         },
57
58         stamp: (function () {
59                 var lastId = 0,
60                     key = '_leaflet_id';
61                 return function (obj) {
62                         obj[key] = obj[key] || ++lastId;
63                         return obj[key];
64                 };
65         }()),
66
67         invokeEach: function (obj, method, context) {
68                 var i, args;
69
70                 if (typeof obj === 'object') {
71                         args = Array.prototype.slice.call(arguments, 3);
72
73                         for (i in obj) {
74                                 method.apply(context, [i, obj[i]].concat(args));
75                         }
76                         return true;
77                 }
78
79                 return false;
80         },
81
82         limitExecByInterval: function (fn, time, context) {
83                 var lock, execOnUnlock;
84
85                 return function wrapperFn() {
86                         var args = arguments;
87
88                         if (lock) {
89                                 execOnUnlock = true;
90                                 return;
91                         }
92
93                         lock = true;
94
95                         setTimeout(function () {
96                                 lock = false;
97
98                                 if (execOnUnlock) {
99                                         wrapperFn.apply(context, args);
100                                         execOnUnlock = false;
101                                 }
102                         }, time);
103
104                         fn.apply(context, args);
105                 };
106         },
107
108         falseFn: function () {
109                 return false;
110         },
111
112         formatNum: function (num, digits) {
113                 var pow = Math.pow(10, digits || 5);
114                 return Math.round(num * pow) / pow;
115         },
116
117         trim: function (str) {
118                 return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
119         },
120
121         splitWords: function (str) {
122                 return L.Util.trim(str).split(/\s+/);
123         },
124
125         setOptions: function (obj, options) {
126                 obj.options = L.extend({}, obj.options, options);
127                 return obj.options;
128         },
129
130         getParamString: function (obj, existingUrl, uppercase) {
131                 var params = [];
132                 for (var i in obj) {
133                         params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
134                 }
135                 return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
136         },
137
138         compileTemplate: function (str, data) {
139                 // based on https://gist.github.com/padolsey/6008842
140                 str = str.replace(/"/g, '\\\"');
141                 str = str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
142                         return '" + o["' + key + '"]' + (typeof data[key] === 'function' ? '(o)' : '') + ' + "';
143                 });
144                 // jshint evil: true
145                 return new Function('o', 'return "' + str + '";');
146         },
147
148         template: function (str, data) {
149                 var cache = L.Util._templateCache = L.Util._templateCache || {};
150                 cache[str] = cache[str] || L.Util.compileTemplate(str, data);
151                 return cache[str](data);
152         },
153
154         isArray: Array.isArray || function (obj) {
155                 return (Object.prototype.toString.call(obj) === '[object Array]');
156         },
157
158         emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
159 };
160
161 (function () {
162
163         // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
164
165         function getPrefixed(name) {
166                 var i, fn,
167                     prefixes = ['webkit', 'moz', 'o', 'ms'];
168
169                 for (i = 0; i < prefixes.length && !fn; i++) {
170                         fn = window[prefixes[i] + name];
171                 }
172
173                 return fn;
174         }
175
176         var lastTime = 0;
177
178         function timeoutDefer(fn) {
179                 var time = +new Date(),
180                     timeToCall = Math.max(0, 16 - (time - lastTime));
181
182                 lastTime = time + timeToCall;
183                 return window.setTimeout(fn, timeToCall);
184         }
185
186         var requestFn = window.requestAnimationFrame ||
187                 getPrefixed('RequestAnimationFrame') || timeoutDefer;
188
189         var cancelFn = window.cancelAnimationFrame ||
190                 getPrefixed('CancelAnimationFrame') ||
191                 getPrefixed('CancelRequestAnimationFrame') ||
192                 function (id) { window.clearTimeout(id); };
193
194
195         L.Util.requestAnimFrame = function (fn, context, immediate, element) {
196                 fn = L.bind(fn, context);
197
198                 if (immediate && requestFn === timeoutDefer) {
199                         fn();
200                 } else {
201                         return requestFn.call(window, fn, element);
202                 }
203         };
204
205         L.Util.cancelAnimFrame = function (id) {
206                 if (id) {
207                         cancelFn.call(window, id);
208                 }
209         };
210
211 }());
212
213 // shortcuts for most used utility functions
214 L.extend = L.Util.extend;
215 L.bind = L.Util.bind;
216 L.stamp = L.Util.stamp;
217 L.setOptions = L.Util.setOptions;
218
219
220 /*
221  * L.Class powers the OOP facilities of the library.
222  * Thanks to John Resig and Dean Edwards for inspiration!
223  */
224
225 L.Class = function () {};
226
227 L.Class.extend = function (props) {
228
229         // extended class with the new prototype
230         var NewClass = function () {
231
232                 // call the constructor
233                 if (this.initialize) {
234                         this.initialize.apply(this, arguments);
235                 }
236
237                 // call all constructor hooks
238                 if (this._initHooks) {
239                         this.callInitHooks();
240                 }
241         };
242
243         // instantiate class without calling constructor
244         var F = function () {};
245         F.prototype = this.prototype;
246
247         var proto = new F();
248         proto.constructor = NewClass;
249
250         NewClass.prototype = proto;
251
252         //inherit parent's statics
253         for (var i in this) {
254                 if (this.hasOwnProperty(i) && i !== 'prototype') {
255                         NewClass[i] = this[i];
256                 }
257         }
258
259         // mix static properties into the class
260         if (props.statics) {
261                 L.extend(NewClass, props.statics);
262                 delete props.statics;
263         }
264
265         // mix includes into the prototype
266         if (props.includes) {
267                 L.Util.extend.apply(null, [proto].concat(props.includes));
268                 delete props.includes;
269         }
270
271         // merge options
272         if (props.options && proto.options) {
273                 props.options = L.extend({}, proto.options, props.options);
274         }
275
276         // mix given properties into the prototype
277         L.extend(proto, props);
278
279         proto._initHooks = [];
280
281         var parent = this;
282         // jshint camelcase: false
283         NewClass.__super__ = parent.prototype;
284
285         // add method for calling all hooks
286         proto.callInitHooks = function () {
287
288                 if (this._initHooksCalled) { return; }
289
290                 if (parent.prototype.callInitHooks) {
291                         parent.prototype.callInitHooks.call(this);
292                 }
293
294                 this._initHooksCalled = true;
295
296                 for (var i = 0, len = proto._initHooks.length; i < len; i++) {
297                         proto._initHooks[i].call(this);
298                 }
299         };
300
301         return NewClass;
302 };
303
304
305 // method for adding properties to prototype
306 L.Class.include = function (props) {
307         L.extend(this.prototype, props);
308 };
309
310 // merge new default options to the Class
311 L.Class.mergeOptions = function (options) {
312         L.extend(this.prototype.options, options);
313 };
314
315 // add a constructor hook
316 L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
317         var args = Array.prototype.slice.call(arguments, 1);
318
319         var init = typeof fn === 'function' ? fn : function () {
320                 this[fn].apply(this, args);
321         };
322
323         this.prototype._initHooks = this.prototype._initHooks || [];
324         this.prototype._initHooks.push(init);
325 };
326
327
328 /*
329  * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
330  */
331
332 var eventsKey = '_leaflet_events';
333
334 L.Mixin = {};
335
336 L.Mixin.Events = {
337
338         addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
339
340                 // types can be a map of types/handlers
341                 if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
342
343                 var events = this[eventsKey] = this[eventsKey] || {},
344                     contextId = context && context !== this && L.stamp(context),
345                     i, len, event, type, indexKey, indexLenKey, typeIndex;
346
347                 // types can be a string of space-separated words
348                 types = L.Util.splitWords(types);
349
350                 for (i = 0, len = types.length; i < len; i++) {
351                         event = {
352                                 action: fn,
353                                 context: context || this
354                         };
355                         type = types[i];
356
357                         if (contextId) {
358                                 // store listeners of a particular context in a separate hash (if it has an id)
359                                 // gives a major performance boost when removing thousands of map layers
360
361                                 indexKey = type + '_idx';
362                                 indexLenKey = indexKey + '_len';
363
364                                 typeIndex = events[indexKey] = events[indexKey] || {};
365
366                                 if (!typeIndex[contextId]) {
367                                         typeIndex[contextId] = [];
368
369                                         // keep track of the number of keys in the index to quickly check if it's empty
370                                         events[indexLenKey] = (events[indexLenKey] || 0) + 1;
371                                 }
372
373                                 typeIndex[contextId].push(event);
374
375
376                         } else {
377                                 events[type] = events[type] || [];
378                                 events[type].push(event);
379                         }
380                 }
381
382                 return this;
383         },
384
385         hasEventListeners: function (type) { // (String) -> Boolean
386                 var events = this[eventsKey];
387                 return !!events && ((type in events && events[type].length > 0) ||
388                                     (type + '_idx' in events && events[type + '_idx_len'] > 0));
389         },
390
391         removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
392
393                 if (!this[eventsKey]) {
394                         return this;
395                 }
396
397                 if (!types) {
398                         return this.clearAllEventListeners();
399                 }
400
401                 if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
402
403                 var events = this[eventsKey],
404                     contextId = context && context !== this && L.stamp(context),
405                     i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
406
407                 types = L.Util.splitWords(types);
408
409                 for (i = 0, len = types.length; i < len; i++) {
410                         type = types[i];
411                         indexKey = type + '_idx';
412                         indexLenKey = indexKey + '_len';
413
414                         typeIndex = events[indexKey];
415
416                         if (!fn) {
417                                 // clear all listeners for a type if function isn't specified
418                                 delete events[type];
419                                 delete events[indexKey];
420                                 delete events[indexLenKey];
421
422                         } else {
423                                 listeners = contextId && typeIndex ? typeIndex[contextId] : events[type];
424
425                                 if (listeners) {
426                                         for (j = listeners.length - 1; j >= 0; j--) {
427                                                 if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
428                                                         removed = listeners.splice(j, 1);
429                                                         // set the old action to a no-op, because it is possible
430                                                         // that the listener is being iterated over as part of a dispatch
431                                                         removed[0].action = L.Util.falseFn;
432                                                 }
433                                         }
434
435                                         if (context && typeIndex && (listeners.length === 0)) {
436                                                 delete typeIndex[contextId];
437                                                 events[indexLenKey]--;
438                                         }
439                                 }
440                         }
441                 }
442
443                 return this;
444         },
445
446         clearAllEventListeners: function () {
447                 delete this[eventsKey];
448                 return this;
449         },
450
451         fireEvent: function (type, data) { // (String[, Object])
452                 if (!this.hasEventListeners(type)) {
453                         return this;
454                 }
455
456                 var event = L.Util.extend({}, data, { type: type, target: this });
457
458                 var events = this[eventsKey],
459                     listeners, i, len, typeIndex, contextId;
460
461                 if (events[type]) {
462                         // make sure adding/removing listeners inside other listeners won't cause infinite loop
463                         listeners = events[type].slice();
464
465                         for (i = 0, len = listeners.length; i < len; i++) {
466                                 listeners[i].action.call(listeners[i].context, event);
467                         }
468                 }
469
470                 // fire event for the context-indexed listeners as well
471                 typeIndex = events[type + '_idx'];
472
473                 for (contextId in typeIndex) {
474                         listeners = typeIndex[contextId].slice();
475
476                         if (listeners) {
477                                 for (i = 0, len = listeners.length; i < len; i++) {
478                                         listeners[i].action.call(listeners[i].context, event);
479                                 }
480                         }
481                 }
482
483                 return this;
484         },
485
486         addOneTimeEventListener: function (types, fn, context) {
487
488                 if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
489
490                 var handler = L.bind(function () {
491                         this
492                             .removeEventListener(types, fn, context)
493                             .removeEventListener(types, handler, context);
494                 }, this);
495
496                 return this
497                     .addEventListener(types, fn, context)
498                     .addEventListener(types, handler, context);
499         }
500 };
501
502 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
503 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
504 L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
505 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
506
507
508 /*
509  * L.Browser handles different browser and feature detections for internal Leaflet use.
510  */
511
512 (function () {
513
514         var ie = 'ActiveXObject' in window,
515                 ielt9 = ie && !document.addEventListener,
516
517             // terrible browser detection to work around Safari / iOS / Android browser bugs
518             ua = navigator.userAgent.toLowerCase(),
519             webkit = ua.indexOf('webkit') !== -1,
520             chrome = ua.indexOf('chrome') !== -1,
521             phantomjs = ua.indexOf('phantom') !== -1,
522             android = ua.indexOf('android') !== -1,
523             android23 = ua.search('android [23]') !== -1,
524                 gecko = ua.indexOf('gecko') !== -1,
525
526             mobile = typeof orientation !== undefined + '',
527             msPointer = window.navigator && window.navigator.msPointerEnabled &&
528                       window.navigator.msMaxTouchPoints && !window.PointerEvent,
529                 pointer = (window.PointerEvent && window.navigator.pointerEnabled && window.navigator.maxTouchPoints) ||
530                                   msPointer,
531             retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
532                      ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
533                       window.matchMedia('(min-resolution:144dpi)').matches),
534
535             doc = document.documentElement,
536             ie3d = ie && ('transition' in doc.style),
537             webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
538             gecko3d = 'MozPerspective' in doc.style,
539             opera3d = 'OTransition' in doc.style,
540             any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
541
542
543         // PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch.
544         // https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151
545
546         var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
547
548                 var startName = 'ontouchstart';
549
550                 // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.Pointer) or WebKit, etc.
551                 if (pointer || (startName in doc)) {
552                         return true;
553                 }
554
555                 // Firefox/Gecko
556                 var div = document.createElement('div'),
557                     supported = false;
558
559                 if (!div.setAttribute) {
560                         return false;
561                 }
562                 div.setAttribute(startName, 'return;');
563
564                 if (typeof div[startName] === 'function') {
565                         supported = true;
566                 }
567
568                 div.removeAttribute(startName);
569                 div = null;
570
571                 return supported;
572         }());
573
574
575         L.Browser = {
576                 ie: ie,
577                 ielt9: ielt9,
578                 webkit: webkit,
579                 gecko: gecko && !webkit && !window.opera && !ie,
580
581                 android: android,
582                 android23: android23,
583
584                 chrome: chrome,
585
586                 ie3d: ie3d,
587                 webkit3d: webkit3d,
588                 gecko3d: gecko3d,
589                 opera3d: opera3d,
590                 any3d: any3d,
591
592                 mobile: mobile,
593                 mobileWebkit: mobile && webkit,
594                 mobileWebkit3d: mobile && webkit3d,
595                 mobileOpera: mobile && window.opera,
596
597                 touch: touch,
598                 msPointer: msPointer,
599                 pointer: pointer,
600
601                 retina: retina
602         };
603
604 }());
605
606
607 /*
608  * L.Point represents a point with x and y coordinates.
609  */
610
611 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
612         this.x = (round ? Math.round(x) : x);
613         this.y = (round ? Math.round(y) : y);
614 };
615
616 L.Point.prototype = {
617
618         clone: function () {
619                 return new L.Point(this.x, this.y);
620         },
621
622         // non-destructive, returns a new point
623         add: function (point) {
624                 return this.clone()._add(L.point(point));
625         },
626
627         // destructive, used directly for performance in situations where it's safe to modify existing point
628         _add: function (point) {
629                 this.x += point.x;
630                 this.y += point.y;
631                 return this;
632         },
633
634         subtract: function (point) {
635                 return this.clone()._subtract(L.point(point));
636         },
637
638         _subtract: function (point) {
639                 this.x -= point.x;
640                 this.y -= point.y;
641                 return this;
642         },
643
644         divideBy: function (num) {
645                 return this.clone()._divideBy(num);
646         },
647
648         _divideBy: function (num) {
649                 this.x /= num;
650                 this.y /= num;
651                 return this;
652         },
653
654         multiplyBy: function (num) {
655                 return this.clone()._multiplyBy(num);
656         },
657
658         _multiplyBy: function (num) {
659                 this.x *= num;
660                 this.y *= num;
661                 return this;
662         },
663
664         round: function () {
665                 return this.clone()._round();
666         },
667
668         _round: function () {
669                 this.x = Math.round(this.x);
670                 this.y = Math.round(this.y);
671                 return this;
672         },
673
674         floor: function () {
675                 return this.clone()._floor();
676         },
677
678         _floor: function () {
679                 this.x = Math.floor(this.x);
680                 this.y = Math.floor(this.y);
681                 return this;
682         },
683
684         distanceTo: function (point) {
685                 point = L.point(point);
686
687                 var x = point.x - this.x,
688                     y = point.y - this.y;
689
690                 return Math.sqrt(x * x + y * y);
691         },
692
693         equals: function (point) {
694                 point = L.point(point);
695
696                 return point.x === this.x &&
697                        point.y === this.y;
698         },
699
700         contains: function (point) {
701                 point = L.point(point);
702
703                 return Math.abs(point.x) <= Math.abs(this.x) &&
704                        Math.abs(point.y) <= Math.abs(this.y);
705         },
706
707         toString: function () {
708                 return 'Point(' +
709                         L.Util.formatNum(this.x) + ', ' +
710                         L.Util.formatNum(this.y) + ')';
711         }
712 };
713
714 L.point = function (x, y, round) {
715         if (x instanceof L.Point) {
716                 return x;
717         }
718         if (L.Util.isArray(x)) {
719                 return new L.Point(x[0], x[1]);
720         }
721         if (x === undefined || x === null) {
722                 return x;
723         }
724         return new L.Point(x, y, round);
725 };
726
727
728 /*
729  * L.Bounds represents a rectangular area on the screen in pixel coordinates.
730  */
731
732 L.Bounds = function (a, b) { //(Point, Point) or Point[]
733         if (!a) { return; }
734
735         var points = b ? [a, b] : a;
736
737         for (var i = 0, len = points.length; i < len; i++) {
738                 this.extend(points[i]);
739         }
740 };
741
742 L.Bounds.prototype = {
743         // extend the bounds to contain the given point
744         extend: function (point) { // (Point)
745                 point = L.point(point);
746
747                 if (!this.min && !this.max) {
748                         this.min = point.clone();
749                         this.max = point.clone();
750                 } else {
751                         this.min.x = Math.min(point.x, this.min.x);
752                         this.max.x = Math.max(point.x, this.max.x);
753                         this.min.y = Math.min(point.y, this.min.y);
754                         this.max.y = Math.max(point.y, this.max.y);
755                 }
756                 return this;
757         },
758
759         getCenter: function (round) { // (Boolean) -> Point
760                 return new L.Point(
761                         (this.min.x + this.max.x) / 2,
762                         (this.min.y + this.max.y) / 2, round);
763         },
764
765         getBottomLeft: function () { // -> Point
766                 return new L.Point(this.min.x, this.max.y);
767         },
768
769         getTopRight: function () { // -> Point
770                 return new L.Point(this.max.x, this.min.y);
771         },
772
773         getSize: function () {
774                 return this.max.subtract(this.min);
775         },
776
777         contains: function (obj) { // (Bounds) or (Point) -> Boolean
778                 var min, max;
779
780                 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
781                         obj = L.point(obj);
782                 } else {
783                         obj = L.bounds(obj);
784                 }
785
786                 if (obj instanceof L.Bounds) {
787                         min = obj.min;
788                         max = obj.max;
789                 } else {
790                         min = max = obj;
791                 }
792
793                 return (min.x >= this.min.x) &&
794                        (max.x <= this.max.x) &&
795                        (min.y >= this.min.y) &&
796                        (max.y <= this.max.y);
797         },
798
799         intersects: function (bounds) { // (Bounds) -> Boolean
800                 bounds = L.bounds(bounds);
801
802                 var min = this.min,
803                     max = this.max,
804                     min2 = bounds.min,
805                     max2 = bounds.max,
806                     xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
807                     yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
808
809                 return xIntersects && yIntersects;
810         },
811
812         isValid: function () {
813                 return !!(this.min && this.max);
814         }
815 };
816
817 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
818         if (!a || a instanceof L.Bounds) {
819                 return a;
820         }
821         return new L.Bounds(a, b);
822 };
823
824
825 /*
826  * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
827  */
828
829 L.Transformation = function (a, b, c, d) {
830         this._a = a;
831         this._b = b;
832         this._c = c;
833         this._d = d;
834 };
835
836 L.Transformation.prototype = {
837         transform: function (point, scale) { // (Point, Number) -> Point
838                 return this._transform(point.clone(), scale);
839         },
840
841         // destructive transform (faster)
842         _transform: function (point, scale) {
843                 scale = scale || 1;
844                 point.x = scale * (this._a * point.x + this._b);
845                 point.y = scale * (this._c * point.y + this._d);
846                 return point;
847         },
848
849         untransform: function (point, scale) {
850                 scale = scale || 1;
851                 return new L.Point(
852                         (point.x / scale - this._b) / this._a,
853                         (point.y / scale - this._d) / this._c);
854         }
855 };
856
857
858 /*
859  * L.DomUtil contains various utility functions for working with DOM.
860  */
861
862 L.DomUtil = {
863         get: function (id) {
864                 return (typeof id === 'string' ? document.getElementById(id) : id);
865         },
866
867         getStyle: function (el, style) {
868
869                 var value = el.style[style];
870
871                 if (!value && el.currentStyle) {
872                         value = el.currentStyle[style];
873                 }
874
875                 if ((!value || value === 'auto') && document.defaultView) {
876                         var css = document.defaultView.getComputedStyle(el, null);
877                         value = css ? css[style] : null;
878                 }
879
880                 return value === 'auto' ? null : value;
881         },
882
883         getViewportOffset: function (element) {
884
885                 var top = 0,
886                     left = 0,
887                     el = element,
888                     docBody = document.body,
889                     docEl = document.documentElement,
890                     pos;
891
892                 do {
893                         top  += el.offsetTop  || 0;
894                         left += el.offsetLeft || 0;
895
896                         //add borders
897                         top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
898                         left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
899
900                         pos = L.DomUtil.getStyle(el, 'position');
901
902                         if (el.offsetParent === docBody && pos === 'absolute') { break; }
903
904                         if (pos === 'fixed') {
905                                 top  += docBody.scrollTop  || docEl.scrollTop  || 0;
906                                 left += docBody.scrollLeft || docEl.scrollLeft || 0;
907                                 break;
908                         }
909
910                         if (pos === 'relative' && !el.offsetLeft) {
911                                 var width = L.DomUtil.getStyle(el, 'width'),
912                                     maxWidth = L.DomUtil.getStyle(el, 'max-width'),
913                                     r = el.getBoundingClientRect();
914
915                                 if (width !== 'none' || maxWidth !== 'none') {
916                                         left += r.left + el.clientLeft;
917                                 }
918
919                                 //calculate full y offset since we're breaking out of the loop
920                                 top += r.top + (docBody.scrollTop  || docEl.scrollTop  || 0);
921
922                                 break;
923                         }
924
925                         el = el.offsetParent;
926
927                 } while (el);
928
929                 el = element;
930
931                 do {
932                         if (el === docBody) { break; }
933
934                         top  -= el.scrollTop  || 0;
935                         left -= el.scrollLeft || 0;
936
937                         el = el.parentNode;
938                 } while (el);
939
940                 return new L.Point(left, top);
941         },
942
943         documentIsLtr: function () {
944                 if (!L.DomUtil._docIsLtrCached) {
945                         L.DomUtil._docIsLtrCached = true;
946                         L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
947                 }
948                 return L.DomUtil._docIsLtr;
949         },
950
951         create: function (tagName, className, container) {
952
953                 var el = document.createElement(tagName);
954                 el.className = className;
955
956                 if (container) {
957                         container.appendChild(el);
958                 }
959
960                 return el;
961         },
962
963         hasClass: function (el, name) {
964                 if (el.classList !== undefined) {
965                         return el.classList.contains(name);
966                 }
967                 var className = L.DomUtil._getClass(el);
968                 return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
969         },
970
971         addClass: function (el, name) {
972                 if (el.classList !== undefined) {
973                         var classes = L.Util.splitWords(name);
974                         for (var i = 0, len = classes.length; i < len; i++) {
975                                 el.classList.add(classes[i]);
976                         }
977                 } else if (!L.DomUtil.hasClass(el, name)) {
978                         var className = L.DomUtil._getClass(el);
979                         L.DomUtil._setClass(el, (className ? className + ' ' : '') + name);
980                 }
981         },
982
983         removeClass: function (el, name) {
984                 if (el.classList !== undefined) {
985                         el.classList.remove(name);
986                 } else {
987                         L.DomUtil._setClass(el, L.Util.trim((' ' + L.DomUtil._getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
988                 }
989         },
990
991         _setClass: function (el, name) {
992                 if (el.className.baseVal === undefined) {
993                         el.className = name;
994                 } else {
995                         // in case of SVG element
996                         el.className.baseVal = name;
997                 }
998         },
999
1000         _getClass: function (el) {
1001                 return el.className.baseVal === undefined ? el.className : el.className.baseVal;
1002         },
1003
1004         setOpacity: function (el, value) {
1005
1006                 if ('opacity' in el.style) {
1007                         el.style.opacity = value;
1008
1009                 } else if ('filter' in el.style) {
1010
1011                         var filter = false,
1012                             filterName = 'DXImageTransform.Microsoft.Alpha';
1013
1014                         // filters collection throws an error if we try to retrieve a filter that doesn't exist
1015                         try {
1016                                 filter = el.filters.item(filterName);
1017                         } catch (e) {
1018                                 // don't set opacity to 1 if we haven't already set an opacity,
1019                                 // it isn't needed and breaks transparent pngs.
1020                                 if (value === 1) { return; }
1021                         }
1022
1023                         value = Math.round(value * 100);
1024
1025                         if (filter) {
1026                                 filter.Enabled = (value !== 100);
1027                                 filter.Opacity = value;
1028                         } else {
1029                                 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
1030                         }
1031                 }
1032         },
1033
1034         testProp: function (props) {
1035
1036                 var style = document.documentElement.style;
1037
1038                 for (var i = 0; i < props.length; i++) {
1039                         if (props[i] in style) {
1040                                 return props[i];
1041                         }
1042                 }
1043                 return false;
1044         },
1045
1046         getTranslateString: function (point) {
1047                 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
1048                 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
1049                 // (same speed either way), Opera 12 doesn't support translate3d
1050
1051                 var is3d = L.Browser.webkit3d,
1052                     open = 'translate' + (is3d ? '3d' : '') + '(',
1053                     close = (is3d ? ',0' : '') + ')';
1054
1055                 return open + point.x + 'px,' + point.y + 'px' + close;
1056         },
1057
1058         getScaleString: function (scale, origin) {
1059
1060                 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
1061                     scaleStr = ' scale(' + scale + ') ';
1062
1063                 return preTranslateStr + scaleStr;
1064         },
1065
1066         setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
1067
1068                 // jshint camelcase: false
1069                 el._leaflet_pos = point;
1070
1071                 if (!disable3D && L.Browser.any3d) {
1072                         el.style[L.DomUtil.TRANSFORM] =  L.DomUtil.getTranslateString(point);
1073
1074                         // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
1075                         if (L.Browser.mobileWebkit3d) {
1076                                 el.style.WebkitBackfaceVisibility = 'hidden';
1077                         }
1078                 } else {
1079                         el.style.left = point.x + 'px';
1080                         el.style.top = point.y + 'px';
1081                 }
1082         },
1083
1084         getPosition: function (el) {
1085                 // this method is only used for elements previously positioned using setPosition,
1086                 // so it's safe to cache the position for performance
1087
1088                 // jshint camelcase: false
1089                 return el._leaflet_pos;
1090         }
1091 };
1092
1093
1094 // prefix style property names
1095
1096 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
1097         ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
1098
1099 // webkitTransition comes first because some browser versions that drop vendor prefix don't do
1100 // the same for the transitionend event, in particular the Android 4.1 stock browser
1101
1102 L.DomUtil.TRANSITION = L.DomUtil.testProp(
1103         ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
1104
1105 L.DomUtil.TRANSITION_END =
1106         L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
1107         L.DomUtil.TRANSITION + 'End' : 'transitionend';
1108
1109 (function () {
1110     if ('onselectstart' in document) {
1111         L.extend(L.DomUtil, {
1112             disableTextSelection: function () {
1113                 L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
1114             },
1115
1116             enableTextSelection: function () {
1117                 L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
1118             }
1119         });
1120     } else {
1121         var userSelectProperty = L.DomUtil.testProp(
1122             ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
1123
1124         L.extend(L.DomUtil, {
1125             disableTextSelection: function () {
1126                 if (userSelectProperty) {
1127                     var style = document.documentElement.style;
1128                     this._userSelect = style[userSelectProperty];
1129                     style[userSelectProperty] = 'none';
1130                 }
1131             },
1132
1133             enableTextSelection: function () {
1134                 if (userSelectProperty) {
1135                     document.documentElement.style[userSelectProperty] = this._userSelect;
1136                     delete this._userSelect;
1137                 }
1138             }
1139         });
1140     }
1141
1142         L.extend(L.DomUtil, {
1143                 disableImageDrag: function () {
1144                         L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
1145                 },
1146
1147                 enableImageDrag: function () {
1148                         L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
1149                 }
1150         });
1151 })();
1152
1153
1154 /*
1155  * L.LatLng represents a geographical point with latitude and longitude coordinates.
1156  */
1157
1158 L.LatLng = function (lat, lng, alt) { // (Number, Number, Number)
1159         lat = parseFloat(lat);
1160         lng = parseFloat(lng);
1161
1162         if (isNaN(lat) || isNaN(lng)) {
1163                 throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
1164         }
1165
1166         this.lat = lat;
1167         this.lng = lng;
1168
1169         if (alt !== undefined) {
1170                 this.alt = parseFloat(alt);
1171         }
1172 };
1173
1174 L.extend(L.LatLng, {
1175         DEG_TO_RAD: Math.PI / 180,
1176         RAD_TO_DEG: 180 / Math.PI,
1177         MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
1178 });
1179
1180 L.LatLng.prototype = {
1181         equals: function (obj) { // (LatLng) -> Boolean
1182                 if (!obj) { return false; }
1183
1184                 obj = L.latLng(obj);
1185
1186                 var margin = Math.max(
1187                         Math.abs(this.lat - obj.lat),
1188                         Math.abs(this.lng - obj.lng));
1189
1190                 return margin <= L.LatLng.MAX_MARGIN;
1191         },
1192
1193         toString: function (precision) { // (Number) -> String
1194                 return 'LatLng(' +
1195                         L.Util.formatNum(this.lat, precision) + ', ' +
1196                         L.Util.formatNum(this.lng, precision) + ')';
1197         },
1198
1199         // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1200         // TODO move to projection code, LatLng shouldn't know about Earth
1201         distanceTo: function (other) { // (LatLng) -> Number
1202                 other = L.latLng(other);
1203
1204                 var R = 6378137, // earth radius in meters
1205                     d2r = L.LatLng.DEG_TO_RAD,
1206                     dLat = (other.lat - this.lat) * d2r,
1207                     dLon = (other.lng - this.lng) * d2r,
1208                     lat1 = this.lat * d2r,
1209                     lat2 = other.lat * d2r,
1210                     sin1 = Math.sin(dLat / 2),
1211                     sin2 = Math.sin(dLon / 2);
1212
1213                 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1214
1215                 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1216         },
1217
1218         wrap: function (a, b) { // (Number, Number) -> LatLng
1219                 var lng = this.lng;
1220
1221                 a = a || -180;
1222                 b = b ||  180;
1223
1224                 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1225
1226                 return new L.LatLng(this.lat, lng);
1227         }
1228 };
1229
1230 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1231         if (a instanceof L.LatLng) {
1232                 return a;
1233         }
1234         if (L.Util.isArray(a)) {
1235                 if (typeof a[0] === 'number' || typeof a[0] === 'string') {
1236                         return new L.LatLng(a[0], a[1], a[2]);
1237                 } else {
1238                         return null;
1239                 }
1240         }
1241         if (a === undefined || a === null) {
1242                 return a;
1243         }
1244         if (typeof a === 'object' && 'lat' in a) {
1245                 return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
1246         }
1247         if (b === undefined) {
1248                 return null;
1249         }
1250         return new L.LatLng(a, b);
1251 };
1252
1253
1254
1255 /*
1256  * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1257  */
1258
1259 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1260         if (!southWest) { return; }
1261
1262         var latlngs = northEast ? [southWest, northEast] : southWest;
1263
1264         for (var i = 0, len = latlngs.length; i < len; i++) {
1265                 this.extend(latlngs[i]);
1266         }
1267 };
1268
1269 L.LatLngBounds.prototype = {
1270         // extend the bounds to contain the given point or bounds
1271         extend: function (obj) { // (LatLng) or (LatLngBounds)
1272                 if (!obj) { return this; }
1273
1274                 var latLng = L.latLng(obj);
1275                 if (latLng !== null) {
1276                         obj = latLng;
1277                 } else {
1278                         obj = L.latLngBounds(obj);
1279                 }
1280
1281                 if (obj instanceof L.LatLng) {
1282                         if (!this._southWest && !this._northEast) {
1283                                 this._southWest = new L.LatLng(obj.lat, obj.lng);
1284                                 this._northEast = new L.LatLng(obj.lat, obj.lng);
1285                         } else {
1286                                 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1287                                 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1288
1289                                 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1290                                 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1291                         }
1292                 } else if (obj instanceof L.LatLngBounds) {
1293                         this.extend(obj._southWest);
1294                         this.extend(obj._northEast);
1295                 }
1296                 return this;
1297         },
1298
1299         // extend the bounds by a percentage
1300         pad: function (bufferRatio) { // (Number) -> LatLngBounds
1301                 var sw = this._southWest,
1302                     ne = this._northEast,
1303                     heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1304                     widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1305
1306                 return new L.LatLngBounds(
1307                         new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1308                         new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1309         },
1310
1311         getCenter: function () { // -> LatLng
1312                 return new L.LatLng(
1313                         (this._southWest.lat + this._northEast.lat) / 2,
1314                         (this._southWest.lng + this._northEast.lng) / 2);
1315         },
1316
1317         getSouthWest: function () {
1318                 return this._southWest;
1319         },
1320
1321         getNorthEast: function () {
1322                 return this._northEast;
1323         },
1324
1325         getNorthWest: function () {
1326                 return new L.LatLng(this.getNorth(), this.getWest());
1327         },
1328
1329         getSouthEast: function () {
1330                 return new L.LatLng(this.getSouth(), this.getEast());
1331         },
1332
1333         getWest: function () {
1334                 return this._southWest.lng;
1335         },
1336
1337         getSouth: function () {
1338                 return this._southWest.lat;
1339         },
1340
1341         getEast: function () {
1342                 return this._northEast.lng;
1343         },
1344
1345         getNorth: function () {
1346                 return this._northEast.lat;
1347         },
1348
1349         contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1350                 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1351                         obj = L.latLng(obj);
1352                 } else {
1353                         obj = L.latLngBounds(obj);
1354                 }
1355
1356                 var sw = this._southWest,
1357                     ne = this._northEast,
1358                     sw2, ne2;
1359
1360                 if (obj instanceof L.LatLngBounds) {
1361                         sw2 = obj.getSouthWest();
1362                         ne2 = obj.getNorthEast();
1363                 } else {
1364                         sw2 = ne2 = obj;
1365                 }
1366
1367                 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1368                        (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1369         },
1370
1371         intersects: function (bounds) { // (LatLngBounds)
1372                 bounds = L.latLngBounds(bounds);
1373
1374                 var sw = this._southWest,
1375                     ne = this._northEast,
1376                     sw2 = bounds.getSouthWest(),
1377                     ne2 = bounds.getNorthEast(),
1378
1379                     latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1380                     lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1381
1382                 return latIntersects && lngIntersects;
1383         },
1384
1385         toBBoxString: function () {
1386                 return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
1387         },
1388
1389         equals: function (bounds) { // (LatLngBounds)
1390                 if (!bounds) { return false; }
1391
1392                 bounds = L.latLngBounds(bounds);
1393
1394                 return this._southWest.equals(bounds.getSouthWest()) &&
1395                        this._northEast.equals(bounds.getNorthEast());
1396         },
1397
1398         isValid: function () {
1399                 return !!(this._southWest && this._northEast);
1400         }
1401 };
1402
1403 //TODO International date line?
1404
1405 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1406         if (!a || a instanceof L.LatLngBounds) {
1407                 return a;
1408         }
1409         return new L.LatLngBounds(a, b);
1410 };
1411
1412
1413 /*
1414  * L.Projection contains various geographical projections used by CRS classes.
1415  */
1416
1417 L.Projection = {};
1418
1419
1420 /*
1421  * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1422  */
1423
1424 L.Projection.SphericalMercator = {
1425         MAX_LATITUDE: 85.0511287798,
1426
1427         project: function (latlng) { // (LatLng) -> Point
1428                 var d = L.LatLng.DEG_TO_RAD,
1429                     max = this.MAX_LATITUDE,
1430                     lat = Math.max(Math.min(max, latlng.lat), -max),
1431                     x = latlng.lng * d,
1432                     y = lat * d;
1433
1434                 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1435
1436                 return new L.Point(x, y);
1437         },
1438
1439         unproject: function (point) { // (Point, Boolean) -> LatLng
1440                 var d = L.LatLng.RAD_TO_DEG,
1441                     lng = point.x * d,
1442                     lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1443
1444                 return new L.LatLng(lat, lng);
1445         }
1446 };
1447
1448
1449 /*
1450  * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1451  */
1452
1453 L.Projection.LonLat = {
1454         project: function (latlng) {
1455                 return new L.Point(latlng.lng, latlng.lat);
1456         },
1457
1458         unproject: function (point) {
1459                 return new L.LatLng(point.y, point.x);
1460         }
1461 };
1462
1463
1464 /*
1465  * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1466  */
1467
1468 L.CRS = {
1469         latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1470                 var projectedPoint = this.projection.project(latlng),
1471                     scale = this.scale(zoom);
1472
1473                 return this.transformation._transform(projectedPoint, scale);
1474         },
1475
1476         pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1477                 var scale = this.scale(zoom),
1478                     untransformedPoint = this.transformation.untransform(point, scale);
1479
1480                 return this.projection.unproject(untransformedPoint);
1481         },
1482
1483         project: function (latlng) {
1484                 return this.projection.project(latlng);
1485         },
1486
1487         scale: function (zoom) {
1488                 return 256 * Math.pow(2, zoom);
1489         },
1490
1491         getSize: function (zoom) {
1492                 var s = this.scale(zoom);
1493                 return L.point(s, s);
1494         }
1495 };
1496
1497
1498 /*
1499  * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1500  */
1501
1502 L.CRS.Simple = L.extend({}, L.CRS, {
1503         projection: L.Projection.LonLat,
1504         transformation: new L.Transformation(1, 0, -1, 0),
1505
1506         scale: function (zoom) {
1507                 return Math.pow(2, zoom);
1508         }
1509 });
1510
1511
1512 /*
1513  * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1514  * and is used by Leaflet by default.
1515  */
1516
1517 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1518         code: 'EPSG:3857',
1519
1520         projection: L.Projection.SphericalMercator,
1521         transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1522
1523         project: function (latlng) { // (LatLng) -> Point
1524                 var projectedPoint = this.projection.project(latlng),
1525                     earthRadius = 6378137;
1526                 return projectedPoint.multiplyBy(earthRadius);
1527         }
1528 });
1529
1530 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1531         code: 'EPSG:900913'
1532 });
1533
1534
1535 /*
1536  * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1537  */
1538
1539 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1540         code: 'EPSG:4326',
1541
1542         projection: L.Projection.LonLat,
1543         transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1544 });
1545
1546
1547 /*
1548  * L.Map is the central class of the API - it is used to create a map.
1549  */
1550
1551 L.Map = L.Class.extend({
1552
1553         includes: L.Mixin.Events,
1554
1555         options: {
1556                 crs: L.CRS.EPSG3857,
1557
1558                 /*
1559                 center: LatLng,
1560                 zoom: Number,
1561                 layers: Array,
1562                 */
1563
1564                 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1565                 trackResize: true,
1566                 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1567         },
1568
1569         initialize: function (id, options) { // (HTMLElement or String, Object)
1570                 options = L.setOptions(this, options);
1571
1572
1573                 this._initContainer(id);
1574                 this._initLayout();
1575
1576                 // hack for https://github.com/Leaflet/Leaflet/issues/1980
1577                 this._onResize = L.bind(this._onResize, this);
1578
1579                 this._initEvents();
1580
1581                 if (options.maxBounds) {
1582                         this.setMaxBounds(options.maxBounds);
1583                 }
1584
1585                 if (options.center && options.zoom !== undefined) {
1586                         this.setView(L.latLng(options.center), options.zoom, {reset: true});
1587                 }
1588
1589                 this._handlers = [];
1590
1591                 this._layers = {};
1592                 this._zoomBoundLayers = {};
1593                 this._tileLayersNum = 0;
1594
1595                 this.callInitHooks();
1596
1597                 this._addLayers(options.layers);
1598         },
1599
1600
1601         // public methods that modify map state
1602
1603         // replaced by animation-powered implementation in Map.PanAnimation.js
1604         setView: function (center, zoom) {
1605                 zoom = zoom === undefined ? this.getZoom() : zoom;
1606                 this._resetView(L.latLng(center), this._limitZoom(zoom));
1607                 return this;
1608         },
1609
1610         setZoom: function (zoom, options) {
1611                 if (!this._loaded) {
1612                         this._zoom = this._limitZoom(zoom);
1613                         return this;
1614                 }
1615                 return this.setView(this.getCenter(), zoom, {zoom: options});
1616         },
1617
1618         zoomIn: function (delta, options) {
1619                 return this.setZoom(this._zoom + (delta || 1), options);
1620         },
1621
1622         zoomOut: function (delta, options) {
1623                 return this.setZoom(this._zoom - (delta || 1), options);
1624         },
1625
1626         setZoomAround: function (latlng, zoom, options) {
1627                 var scale = this.getZoomScale(zoom),
1628                     viewHalf = this.getSize().divideBy(2),
1629                     containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
1630
1631                     centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
1632                     newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
1633
1634                 return this.setView(newCenter, zoom, {zoom: options});
1635         },
1636
1637         fitBounds: function (bounds, options) {
1638
1639                 options = options || {};
1640                 bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
1641
1642                 var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
1643                     paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
1644
1645                     zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
1646                     paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
1647
1648                     swPoint = this.project(bounds.getSouthWest(), zoom),
1649                     nePoint = this.project(bounds.getNorthEast(), zoom),
1650                     center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
1651
1652                 zoom = options && options.maxZoom ? Math.min(options.maxZoom, zoom) : zoom;
1653
1654                 return this.setView(center, zoom, options);
1655         },
1656
1657         fitWorld: function (options) {
1658                 return this.fitBounds([[-90, -180], [90, 180]], options);
1659         },
1660
1661         panTo: function (center, options) { // (LatLng)
1662                 return this.setView(center, this._zoom, {pan: options});
1663         },
1664
1665         panBy: function (offset) { // (Point)
1666                 // replaced with animated panBy in Map.PanAnimation.js
1667                 this.fire('movestart');
1668
1669                 this._rawPanBy(L.point(offset));
1670
1671                 this.fire('move');
1672                 return this.fire('moveend');
1673         },
1674
1675         setMaxBounds: function (bounds) {
1676                 bounds = L.latLngBounds(bounds);
1677
1678                 this.options.maxBounds = bounds;
1679
1680                 if (!bounds) {
1681                         return this.off('moveend', this._panInsideMaxBounds, this);
1682                 }
1683
1684                 if (this._loaded) {
1685                         this._panInsideMaxBounds();
1686                 }
1687
1688                 return this.on('moveend', this._panInsideMaxBounds, this);
1689         },
1690
1691         panInsideBounds: function (bounds, options) {
1692                 var center = this.getCenter(),
1693                         newCenter = this._limitCenter(center, this._zoom, bounds);
1694
1695                 if (center.equals(newCenter)) { return this; }
1696
1697                 return this.panTo(newCenter, options);
1698         },
1699
1700         addLayer: function (layer) {
1701                 // TODO method is too big, refactor
1702
1703                 var id = L.stamp(layer);
1704
1705                 if (this._layers[id]) { return this; }
1706
1707                 this._layers[id] = layer;
1708
1709                 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1710                 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1711                         this._zoomBoundLayers[id] = layer;
1712                         this._updateZoomLevels();
1713                 }
1714
1715                 // TODO looks ugly, refactor!!!
1716                 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1717                         this._tileLayersNum++;
1718                         this._tileLayersToLoad++;
1719                         layer.on('load', this._onTileLayerLoad, this);
1720                 }
1721
1722                 if (this._loaded) {
1723                         this._layerAdd(layer);
1724                 }
1725
1726                 return this;
1727         },
1728
1729         removeLayer: function (layer) {
1730                 var id = L.stamp(layer);
1731
1732                 if (!this._layers[id]) { return this; }
1733
1734                 if (this._loaded) {
1735                         layer.onRemove(this);
1736                 }
1737
1738                 delete this._layers[id];
1739
1740                 if (this._loaded) {
1741                         this.fire('layerremove', {layer: layer});
1742                 }
1743
1744                 if (this._zoomBoundLayers[id]) {
1745                         delete this._zoomBoundLayers[id];
1746                         this._updateZoomLevels();
1747                 }
1748
1749                 // TODO looks ugly, refactor
1750                 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1751                         this._tileLayersNum--;
1752                         this._tileLayersToLoad--;
1753                         layer.off('load', this._onTileLayerLoad, this);
1754                 }
1755
1756                 return this;
1757         },
1758
1759         hasLayer: function (layer) {
1760                 if (!layer) { return false; }
1761
1762                 return (L.stamp(layer) in this._layers);
1763         },
1764
1765         eachLayer: function (method, context) {
1766                 for (var i in this._layers) {
1767                         method.call(context, this._layers[i]);
1768                 }
1769                 return this;
1770         },
1771
1772         invalidateSize: function (options) {
1773                 options = L.extend({
1774                         animate: false,
1775                         pan: true
1776                 }, options === true ? {animate: true} : options);
1777
1778                 var oldSize = this.getSize();
1779                 this._sizeChanged = true;
1780                 this._initialCenter = null;
1781
1782                 if (!this._loaded) { return this; }
1783
1784                 var newSize = this.getSize(),
1785                     oldCenter = oldSize.divideBy(2).round(),
1786                     newCenter = newSize.divideBy(2).round(),
1787                     offset = oldCenter.subtract(newCenter);
1788
1789                 if (!offset.x && !offset.y) { return this; }
1790
1791                 if (options.animate && options.pan) {
1792                         this.panBy(offset);
1793
1794                 } else {
1795                         if (options.pan) {
1796                                 this._rawPanBy(offset);
1797                         }
1798
1799                         this.fire('move');
1800
1801                         if (options.debounceMoveend) {
1802                                 clearTimeout(this._sizeTimer);
1803                                 this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1804                         } else {
1805                                 this.fire('moveend');
1806                         }
1807                 }
1808
1809                 return this.fire('resize', {
1810                         oldSize: oldSize,
1811                         newSize: newSize
1812                 });
1813         },
1814
1815         // TODO handler.addTo
1816         addHandler: function (name, HandlerClass) {
1817                 if (!HandlerClass) { return this; }
1818
1819                 var handler = this[name] = new HandlerClass(this);
1820
1821                 this._handlers.push(handler);
1822
1823                 if (this.options[name]) {
1824                         handler.enable();
1825                 }
1826
1827                 return this;
1828         },
1829
1830         remove: function () {
1831                 if (this._loaded) {
1832                         this.fire('unload');
1833                 }
1834
1835                 this._initEvents('off');
1836
1837                 try {
1838                         // throws error in IE6-8
1839                         delete this._container._leaflet;
1840                 } catch (e) {
1841                         this._container._leaflet = undefined;
1842                 }
1843
1844                 this._clearPanes();
1845                 if (this._clearControlPos) {
1846                         this._clearControlPos();
1847                 }
1848
1849                 this._clearHandlers();
1850
1851                 return this;
1852         },
1853
1854
1855         // public methods for getting map state
1856
1857         getCenter: function () { // (Boolean) -> LatLng
1858                 this._checkIfLoaded();
1859
1860                 if (this._initialCenter && !this._moved()) {
1861                         return this._initialCenter;
1862                 }
1863                 return this.layerPointToLatLng(this._getCenterLayerPoint());
1864         },
1865
1866         getZoom: function () {
1867                 return this._zoom;
1868         },
1869
1870         getBounds: function () {
1871                 var bounds = this.getPixelBounds(),
1872                     sw = this.unproject(bounds.getBottomLeft()),
1873                     ne = this.unproject(bounds.getTopRight());
1874
1875                 return new L.LatLngBounds(sw, ne);
1876         },
1877
1878         getMinZoom: function () {
1879                 return this.options.minZoom === undefined ?
1880                         (this._layersMinZoom === undefined ? 0 : this._layersMinZoom) :
1881                         this.options.minZoom;
1882         },
1883
1884         getMaxZoom: function () {
1885                 return this.options.maxZoom === undefined ?
1886                         (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
1887                         this.options.maxZoom;
1888         },
1889
1890         getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1891                 bounds = L.latLngBounds(bounds);
1892
1893                 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1894                     maxZoom = this.getMaxZoom(),
1895                     size = this.getSize(),
1896
1897                     nw = bounds.getNorthWest(),
1898                     se = bounds.getSouthEast(),
1899
1900                     zoomNotFound = true,
1901                     boundsSize;
1902
1903                 padding = L.point(padding || [0, 0]);
1904
1905                 do {
1906                         zoom++;
1907                         boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1908                         zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1909
1910                 } while (zoomNotFound && zoom <= maxZoom);
1911
1912                 if (zoomNotFound && inside) {
1913                         return null;
1914                 }
1915
1916                 return inside ? zoom : zoom - 1;
1917         },
1918
1919         getSize: function () {
1920                 if (!this._size || this._sizeChanged) {
1921                         this._size = new L.Point(
1922                                 this._container.clientWidth,
1923                                 this._container.clientHeight);
1924
1925                         this._sizeChanged = false;
1926                 }
1927                 return this._size.clone();
1928         },
1929
1930         getPixelBounds: function () {
1931                 var topLeftPoint = this._getTopLeftPoint();
1932                 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1933         },
1934
1935         getPixelOrigin: function () {
1936                 this._checkIfLoaded();
1937                 return this._initialTopLeftPoint;
1938         },
1939
1940         getPanes: function () {
1941                 return this._panes;
1942         },
1943
1944         getContainer: function () {
1945                 return this._container;
1946         },
1947
1948
1949         // TODO replace with universal implementation after refactoring projections
1950
1951         getZoomScale: function (toZoom) {
1952                 var crs = this.options.crs;
1953                 return crs.scale(toZoom) / crs.scale(this._zoom);
1954         },
1955
1956         getScaleZoom: function (scale) {
1957                 return this._zoom + (Math.log(scale) / Math.LN2);
1958         },
1959
1960
1961         // conversion methods
1962
1963         project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1964                 zoom = zoom === undefined ? this._zoom : zoom;
1965                 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1966         },
1967
1968         unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1969                 zoom = zoom === undefined ? this._zoom : zoom;
1970                 return this.options.crs.pointToLatLng(L.point(point), zoom);
1971         },
1972
1973         layerPointToLatLng: function (point) { // (Point)
1974                 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1975                 return this.unproject(projectedPoint);
1976         },
1977
1978         latLngToLayerPoint: function (latlng) { // (LatLng)
1979                 var projectedPoint = this.project(L.latLng(latlng))._round();
1980                 return projectedPoint._subtract(this.getPixelOrigin());
1981         },
1982
1983         containerPointToLayerPoint: function (point) { // (Point)
1984                 return L.point(point).subtract(this._getMapPanePos());
1985         },
1986
1987         layerPointToContainerPoint: function (point) { // (Point)
1988                 return L.point(point).add(this._getMapPanePos());
1989         },
1990
1991         containerPointToLatLng: function (point) {
1992                 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1993                 return this.layerPointToLatLng(layerPoint);
1994         },
1995
1996         latLngToContainerPoint: function (latlng) {
1997                 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1998         },
1999
2000         mouseEventToContainerPoint: function (e) { // (MouseEvent)
2001                 return L.DomEvent.getMousePosition(e, this._container);
2002         },
2003
2004         mouseEventToLayerPoint: function (e) { // (MouseEvent)
2005                 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
2006         },
2007
2008         mouseEventToLatLng: function (e) { // (MouseEvent)
2009                 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
2010         },
2011
2012
2013         // map initialization methods
2014
2015         _initContainer: function (id) {
2016                 var container = this._container = L.DomUtil.get(id);
2017
2018                 if (!container) {
2019                         throw new Error('Map container not found.');
2020                 } else if (container._leaflet) {
2021                         throw new Error('Map container is already initialized.');
2022                 }
2023
2024                 container._leaflet = true;
2025         },
2026
2027         _initLayout: function () {
2028                 var container = this._container;
2029
2030                 L.DomUtil.addClass(container, 'leaflet-container' +
2031                         (L.Browser.touch ? ' leaflet-touch' : '') +
2032                         (L.Browser.retina ? ' leaflet-retina' : '') +
2033                         (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
2034                         (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
2035
2036                 var position = L.DomUtil.getStyle(container, 'position');
2037
2038                 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
2039                         container.style.position = 'relative';
2040                 }
2041
2042                 this._initPanes();
2043
2044                 if (this._initControlPos) {
2045                         this._initControlPos();
2046                 }
2047         },
2048
2049         _initPanes: function () {
2050                 var panes = this._panes = {};
2051
2052                 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2053
2054                 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2055                 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2056                 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2057                 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2058                 panes.markerPane = this._createPane('leaflet-marker-pane');
2059                 panes.popupPane = this._createPane('leaflet-popup-pane');
2060
2061                 var zoomHide = ' leaflet-zoom-hide';
2062
2063                 if (!this.options.markerZoomAnimation) {
2064                         L.DomUtil.addClass(panes.markerPane, zoomHide);
2065                         L.DomUtil.addClass(panes.shadowPane, zoomHide);
2066                         L.DomUtil.addClass(panes.popupPane, zoomHide);
2067                 }
2068         },
2069
2070         _createPane: function (className, container) {
2071                 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2072         },
2073
2074         _clearPanes: function () {
2075                 this._container.removeChild(this._mapPane);
2076         },
2077
2078         _addLayers: function (layers) {
2079                 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2080
2081                 for (var i = 0, len = layers.length; i < len; i++) {
2082                         this.addLayer(layers[i]);
2083                 }
2084         },
2085
2086
2087         // private methods that modify map state
2088
2089         _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2090
2091                 var zoomChanged = (this._zoom !== zoom);
2092
2093                 if (!afterZoomAnim) {
2094                         this.fire('movestart');
2095
2096                         if (zoomChanged) {
2097                                 this.fire('zoomstart');
2098                         }
2099                 }
2100
2101                 this._zoom = zoom;
2102                 this._initialCenter = center;
2103
2104                 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2105
2106                 if (!preserveMapOffset) {
2107                         L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2108                 } else {
2109                         this._initialTopLeftPoint._add(this._getMapPanePos());
2110                 }
2111
2112                 this._tileLayersToLoad = this._tileLayersNum;
2113
2114                 var loading = !this._loaded;
2115                 this._loaded = true;
2116
2117                 if (loading) {
2118                         this.fire('load');
2119                         this.eachLayer(this._layerAdd, this);
2120                 }
2121
2122                 this.fire('viewreset', {hard: !preserveMapOffset});
2123
2124                 this.fire('move');
2125
2126                 if (zoomChanged || afterZoomAnim) {
2127                         this.fire('zoomend');
2128                 }
2129
2130                 this.fire('moveend', {hard: !preserveMapOffset});
2131         },
2132
2133         _rawPanBy: function (offset) {
2134                 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2135         },
2136
2137         _getZoomSpan: function () {
2138                 return this.getMaxZoom() - this.getMinZoom();
2139         },
2140
2141         _updateZoomLevels: function () {
2142                 var i,
2143                         minZoom = Infinity,
2144                         maxZoom = -Infinity,
2145                         oldZoomSpan = this._getZoomSpan();
2146
2147                 for (i in this._zoomBoundLayers) {
2148                         var layer = this._zoomBoundLayers[i];
2149                         if (!isNaN(layer.options.minZoom)) {
2150                                 minZoom = Math.min(minZoom, layer.options.minZoom);
2151                         }
2152                         if (!isNaN(layer.options.maxZoom)) {
2153                                 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2154                         }
2155                 }
2156
2157                 if (i === undefined) { // we have no tilelayers
2158                         this._layersMaxZoom = this._layersMinZoom = undefined;
2159                 } else {
2160                         this._layersMaxZoom = maxZoom;
2161                         this._layersMinZoom = minZoom;
2162                 }
2163
2164                 if (oldZoomSpan !== this._getZoomSpan()) {
2165                         this.fire('zoomlevelschange');
2166                 }
2167         },
2168
2169         _panInsideMaxBounds: function () {
2170                 this.panInsideBounds(this.options.maxBounds);
2171         },
2172
2173         _checkIfLoaded: function () {
2174                 if (!this._loaded) {
2175                         throw new Error('Set map center and zoom first.');
2176                 }
2177         },
2178
2179         // map events
2180
2181         _initEvents: function (onOff) {
2182                 if (!L.DomEvent) { return; }
2183
2184                 onOff = onOff || 'on';
2185
2186                 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2187
2188                 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2189                               'mouseleave', 'mousemove', 'contextmenu'],
2190                     i, len;
2191
2192                 for (i = 0, len = events.length; i < len; i++) {
2193                         L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2194                 }
2195
2196                 if (this.options.trackResize) {
2197                         L.DomEvent[onOff](window, 'resize', this._onResize, this);
2198                 }
2199         },
2200
2201         _onResize: function () {
2202                 L.Util.cancelAnimFrame(this._resizeRequest);
2203                 this._resizeRequest = L.Util.requestAnimFrame(
2204                         function () { this.invalidateSize({debounceMoveend: true}); }, this, false, this._container);
2205         },
2206
2207         _onMouseClick: function (e) {
2208                 if (!this._loaded || (!e._simulated &&
2209                         ((this.dragging && this.dragging.moved()) ||
2210                          (this.boxZoom  && this.boxZoom.moved()))) ||
2211                             L.DomEvent._skipped(e)) { return; }
2212
2213                 this.fire('preclick');
2214                 this._fireMouseEvent(e);
2215         },
2216
2217         _fireMouseEvent: function (e) {
2218                 if (!this._loaded || L.DomEvent._skipped(e)) { return; }
2219
2220                 var type = e.type;
2221
2222                 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2223
2224                 if (!this.hasEventListeners(type)) { return; }
2225
2226                 if (type === 'contextmenu') {
2227                         L.DomEvent.preventDefault(e);
2228                 }
2229
2230                 var containerPoint = this.mouseEventToContainerPoint(e),
2231                     layerPoint = this.containerPointToLayerPoint(containerPoint),
2232                     latlng = this.layerPointToLatLng(layerPoint);
2233
2234                 this.fire(type, {
2235                         latlng: latlng,
2236                         layerPoint: layerPoint,
2237                         containerPoint: containerPoint,
2238                         originalEvent: e
2239                 });
2240         },
2241
2242         _onTileLayerLoad: function () {
2243                 this._tileLayersToLoad--;
2244                 if (this._tileLayersNum && !this._tileLayersToLoad) {
2245                         this.fire('tilelayersload');
2246                 }
2247         },
2248
2249         _clearHandlers: function () {
2250                 for (var i = 0, len = this._handlers.length; i < len; i++) {
2251                         this._handlers[i].disable();
2252                 }
2253         },
2254
2255         whenReady: function (callback, context) {
2256                 if (this._loaded) {
2257                         callback.call(context || this, this);
2258                 } else {
2259                         this.on('load', callback, context);
2260                 }
2261                 return this;
2262         },
2263
2264         _layerAdd: function (layer) {
2265                 layer.onAdd(this);
2266                 this.fire('layeradd', {layer: layer});
2267         },
2268
2269
2270         // private methods for getting map state
2271
2272         _getMapPanePos: function () {
2273                 return L.DomUtil.getPosition(this._mapPane);
2274         },
2275
2276         _moved: function () {
2277                 var pos = this._getMapPanePos();
2278                 return pos && !pos.equals([0, 0]);
2279         },
2280
2281         _getTopLeftPoint: function () {
2282                 return this.getPixelOrigin().subtract(this._getMapPanePos());
2283         },
2284
2285         _getNewTopLeftPoint: function (center, zoom) {
2286                 var viewHalf = this.getSize()._divideBy(2);
2287                 // TODO round on display, not calculation to increase precision?
2288                 return this.project(center, zoom)._subtract(viewHalf)._round();
2289         },
2290
2291         _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2292                 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2293                 return this.project(latlng, newZoom)._subtract(topLeft);
2294         },
2295
2296         // layer point of the current center
2297         _getCenterLayerPoint: function () {
2298                 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2299         },
2300
2301         // offset of the specified place to the current center in pixels
2302         _getCenterOffset: function (latlng) {
2303                 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2304         },
2305
2306         // adjust center for view to get inside bounds
2307         _limitCenter: function (center, zoom, bounds) {
2308
2309                 if (!bounds) { return center; }
2310
2311                 var centerPoint = this.project(center, zoom),
2312                     viewHalf = this.getSize().divideBy(2),
2313                     viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
2314                     offset = this._getBoundsOffset(viewBounds, bounds, zoom);
2315
2316                 return this.unproject(centerPoint.add(offset), zoom);
2317         },
2318
2319         // adjust offset for view to get inside bounds
2320         _limitOffset: function (offset, bounds) {
2321                 if (!bounds) { return offset; }
2322
2323                 var viewBounds = this.getPixelBounds(),
2324                     newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
2325
2326                 return offset.add(this._getBoundsOffset(newBounds, bounds));
2327         },
2328
2329         // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
2330         _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
2331                 var nwOffset = this.project(maxBounds.getNorthWest(), zoom).subtract(pxBounds.min),
2332                     seOffset = this.project(maxBounds.getSouthEast(), zoom).subtract(pxBounds.max),
2333
2334                     dx = this._rebound(nwOffset.x, -seOffset.x),
2335                     dy = this._rebound(nwOffset.y, -seOffset.y);
2336
2337                 return new L.Point(dx, dy);
2338         },
2339
2340         _rebound: function (left, right) {
2341                 return left + right > 0 ?
2342                         Math.round(left - right) / 2 :
2343                         Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
2344         },
2345
2346         _limitZoom: function (zoom) {
2347                 var min = this.getMinZoom(),
2348                     max = this.getMaxZoom();
2349
2350                 return Math.max(min, Math.min(max, zoom));
2351         }
2352 });
2353
2354 L.map = function (id, options) {
2355         return new L.Map(id, options);
2356 };
2357
2358
2359 /*
2360  * Mercator projection that takes into account that the Earth is not a perfect sphere.
2361  * Less popular than spherical mercator; used by projections like EPSG:3395.
2362  */
2363
2364 L.Projection.Mercator = {
2365         MAX_LATITUDE: 85.0840591556,
2366
2367         R_MINOR: 6356752.314245179,
2368         R_MAJOR: 6378137,
2369
2370         project: function (latlng) { // (LatLng) -> Point
2371                 var d = L.LatLng.DEG_TO_RAD,
2372                     max = this.MAX_LATITUDE,
2373                     lat = Math.max(Math.min(max, latlng.lat), -max),
2374                     r = this.R_MAJOR,
2375                     r2 = this.R_MINOR,
2376                     x = latlng.lng * d * r,
2377                     y = lat * d,
2378                     tmp = r2 / r,
2379                     eccent = Math.sqrt(1.0 - tmp * tmp),
2380                     con = eccent * Math.sin(y);
2381
2382                 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2383
2384                 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2385                 y = -r * Math.log(ts);
2386
2387                 return new L.Point(x, y);
2388         },
2389
2390         unproject: function (point) { // (Point, Boolean) -> LatLng
2391                 var d = L.LatLng.RAD_TO_DEG,
2392                     r = this.R_MAJOR,
2393                     r2 = this.R_MINOR,
2394                     lng = point.x * d / r,
2395                     tmp = r2 / r,
2396                     eccent = Math.sqrt(1 - (tmp * tmp)),
2397                     ts = Math.exp(- point.y / r),
2398                     phi = (Math.PI / 2) - 2 * Math.atan(ts),
2399                     numIter = 15,
2400                     tol = 1e-7,
2401                     i = numIter,
2402                     dphi = 0.1,
2403                     con;
2404
2405                 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2406                         con = eccent * Math.sin(phi);
2407                         dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2408                                     Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2409                         phi += dphi;
2410                 }
2411
2412                 return new L.LatLng(phi * d, lng);
2413         }
2414 };
2415
2416
2417
2418 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2419         code: 'EPSG:3395',
2420
2421         projection: L.Projection.Mercator,
2422
2423         transformation: (function () {
2424                 var m = L.Projection.Mercator,
2425                     r = m.R_MAJOR,
2426                     scale = 0.5 / (Math.PI * r);
2427
2428                 return new L.Transformation(scale, 0.5, -scale, 0.5);
2429         }())
2430 });
2431
2432
2433 /*
2434  * L.TileLayer is used for standard xyz-numbered tile layers.
2435  */
2436
2437 L.TileLayer = L.Class.extend({
2438         includes: L.Mixin.Events,
2439
2440         options: {
2441                 minZoom: 0,
2442                 maxZoom: 18,
2443                 tileSize: 256,
2444                 subdomains: 'abc',
2445                 errorTileUrl: '',
2446                 attribution: '',
2447                 zoomOffset: 0,
2448                 opacity: 1,
2449                 /*
2450                 maxNativeZoom: null,
2451                 zIndex: null,
2452                 tms: false,
2453                 continuousWorld: false,
2454                 noWrap: false,
2455                 zoomReverse: false,
2456                 detectRetina: false,
2457                 reuseTiles: false,
2458                 bounds: false,
2459                 */
2460                 unloadInvisibleTiles: L.Browser.mobile,
2461                 updateWhenIdle: L.Browser.mobile
2462         },
2463
2464         initialize: function (url, options) {
2465                 options = L.setOptions(this, options);
2466
2467                 // detecting retina displays, adjusting tileSize and zoom levels
2468                 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2469
2470                         options.tileSize = Math.floor(options.tileSize / 2);
2471                         options.zoomOffset++;
2472
2473                         if (options.minZoom > 0) {
2474                                 options.minZoom--;
2475                         }
2476                         this.options.maxZoom--;
2477                 }
2478
2479                 if (options.bounds) {
2480                         options.bounds = L.latLngBounds(options.bounds);
2481                 }
2482
2483                 this._url = url;
2484
2485                 var subdomains = this.options.subdomains;
2486
2487                 if (typeof subdomains === 'string') {
2488                         this.options.subdomains = subdomains.split('');
2489                 }
2490         },
2491
2492         onAdd: function (map) {
2493                 this._map = map;
2494                 this._animated = map._zoomAnimated;
2495
2496                 // create a container div for tiles
2497                 this._initContainer();
2498
2499                 // set up events
2500                 map.on({
2501                         'viewreset': this._reset,
2502                         'moveend': this._update
2503                 }, this);
2504
2505                 if (this._animated) {
2506                         map.on({
2507                                 'zoomanim': this._animateZoom,
2508                                 'zoomend': this._endZoomAnim
2509                         }, this);
2510                 }
2511
2512                 if (!this.options.updateWhenIdle) {
2513                         this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2514                         map.on('move', this._limitedUpdate, this);
2515                 }
2516
2517                 this._reset();
2518                 this._update();
2519         },
2520
2521         addTo: function (map) {
2522                 map.addLayer(this);
2523                 return this;
2524         },
2525
2526         onRemove: function (map) {
2527                 this._container.parentNode.removeChild(this._container);
2528
2529                 map.off({
2530                         'viewreset': this._reset,
2531                         'moveend': this._update
2532                 }, this);
2533
2534                 if (this._animated) {
2535                         map.off({
2536                                 'zoomanim': this._animateZoom,
2537                                 'zoomend': this._endZoomAnim
2538                         }, this);
2539                 }
2540
2541                 if (!this.options.updateWhenIdle) {
2542                         map.off('move', this._limitedUpdate, this);
2543                 }
2544
2545                 this._container = null;
2546                 this._map = null;
2547         },
2548
2549         bringToFront: function () {
2550                 var pane = this._map._panes.tilePane;
2551
2552                 if (this._container) {
2553                         pane.appendChild(this._container);
2554                         this._setAutoZIndex(pane, Math.max);
2555                 }
2556
2557                 return this;
2558         },
2559
2560         bringToBack: function () {
2561                 var pane = this._map._panes.tilePane;
2562
2563                 if (this._container) {
2564                         pane.insertBefore(this._container, pane.firstChild);
2565                         this._setAutoZIndex(pane, Math.min);
2566                 }
2567
2568                 return this;
2569         },
2570
2571         getAttribution: function () {
2572                 return this.options.attribution;
2573         },
2574
2575         getContainer: function () {
2576                 return this._container;
2577         },
2578
2579         setOpacity: function (opacity) {
2580                 this.options.opacity = opacity;
2581
2582                 if (this._map) {
2583                         this._updateOpacity();
2584                 }
2585
2586                 return this;
2587         },
2588
2589         setZIndex: function (zIndex) {
2590                 this.options.zIndex = zIndex;
2591                 this._updateZIndex();
2592
2593                 return this;
2594         },
2595
2596         setUrl: function (url, noRedraw) {
2597                 this._url = url;
2598
2599                 if (!noRedraw) {
2600                         this.redraw();
2601                 }
2602
2603                 return this;
2604         },
2605
2606         redraw: function () {
2607                 if (this._map) {
2608                         this._reset({hard: true});
2609                         this._update();
2610                 }
2611                 return this;
2612         },
2613
2614         _updateZIndex: function () {
2615                 if (this._container && this.options.zIndex !== undefined) {
2616                         this._container.style.zIndex = this.options.zIndex;
2617                 }
2618         },
2619
2620         _setAutoZIndex: function (pane, compare) {
2621
2622                 var layers = pane.children,
2623                     edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2624                     zIndex, i, len;
2625
2626                 for (i = 0, len = layers.length; i < len; i++) {
2627
2628                         if (layers[i] !== this._container) {
2629                                 zIndex = parseInt(layers[i].style.zIndex, 10);
2630
2631                                 if (!isNaN(zIndex)) {
2632                                         edgeZIndex = compare(edgeZIndex, zIndex);
2633                                 }
2634                         }
2635                 }
2636
2637                 this.options.zIndex = this._container.style.zIndex =
2638                         (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2639         },
2640
2641         _updateOpacity: function () {
2642                 var i,
2643                     tiles = this._tiles;
2644
2645                 if (L.Browser.ielt9) {
2646                         for (i in tiles) {
2647                                 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2648                         }
2649                 } else {
2650                         L.DomUtil.setOpacity(this._container, this.options.opacity);
2651                 }
2652         },
2653
2654         _initContainer: function () {
2655                 var tilePane = this._map._panes.tilePane;
2656
2657                 if (!this._container) {
2658                         this._container = L.DomUtil.create('div', 'leaflet-layer');
2659
2660                         this._updateZIndex();
2661
2662                         if (this._animated) {
2663                                 var className = 'leaflet-tile-container';
2664
2665                                 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2666                                 this._tileContainer = L.DomUtil.create('div', className, this._container);
2667
2668                         } else {
2669                                 this._tileContainer = this._container;
2670                         }
2671
2672                         tilePane.appendChild(this._container);
2673
2674                         if (this.options.opacity < 1) {
2675                                 this._updateOpacity();
2676                         }
2677                 }
2678         },
2679
2680         _reset: function (e) {
2681                 for (var key in this._tiles) {
2682                         this.fire('tileunload', {tile: this._tiles[key]});
2683                 }
2684
2685                 this._tiles = {};
2686                 this._tilesToLoad = 0;
2687
2688                 if (this.options.reuseTiles) {
2689                         this._unusedTiles = [];
2690                 }
2691
2692                 this._tileContainer.innerHTML = '';
2693
2694                 if (this._animated && e && e.hard) {
2695                         this._clearBgBuffer();
2696                 }
2697
2698                 this._initContainer();
2699         },
2700
2701         _getTileSize: function () {
2702                 var map = this._map,
2703                     zoom = map.getZoom() + this.options.zoomOffset,
2704                     zoomN = this.options.maxNativeZoom,
2705                     tileSize = this.options.tileSize;
2706
2707                 if (zoomN && zoom > zoomN) {
2708                         tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize);
2709                 }
2710
2711                 return tileSize;
2712         },
2713
2714         _update: function () {
2715
2716                 if (!this._map) { return; }
2717
2718                 var map = this._map,
2719                     bounds = map.getPixelBounds(),
2720                     zoom = map.getZoom(),
2721                     tileSize = this._getTileSize();
2722
2723                 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2724                         return;
2725                 }
2726
2727                 var tileBounds = L.bounds(
2728                         bounds.min.divideBy(tileSize)._floor(),
2729                         bounds.max.divideBy(tileSize)._floor());
2730
2731                 this._addTilesFromCenterOut(tileBounds);
2732
2733                 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2734                         this._removeOtherTiles(tileBounds);
2735                 }
2736         },
2737
2738         _addTilesFromCenterOut: function (bounds) {
2739                 var queue = [],
2740                     center = bounds.getCenter();
2741
2742                 var j, i, point;
2743
2744                 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2745                         for (i = bounds.min.x; i <= bounds.max.x; i++) {
2746                                 point = new L.Point(i, j);
2747
2748                                 if (this._tileShouldBeLoaded(point)) {
2749                                         queue.push(point);
2750                                 }
2751                         }
2752                 }
2753
2754                 var tilesToLoad = queue.length;
2755
2756                 if (tilesToLoad === 0) { return; }
2757
2758                 // load tiles in order of their distance to center
2759                 queue.sort(function (a, b) {
2760                         return a.distanceTo(center) - b.distanceTo(center);
2761                 });
2762
2763                 var fragment = document.createDocumentFragment();
2764
2765                 // if its the first batch of tiles to load
2766                 if (!this._tilesToLoad) {
2767                         this.fire('loading');
2768                 }
2769
2770                 this._tilesToLoad += tilesToLoad;
2771
2772                 for (i = 0; i < tilesToLoad; i++) {
2773                         this._addTile(queue[i], fragment);
2774                 }
2775
2776                 this._tileContainer.appendChild(fragment);
2777         },
2778
2779         _tileShouldBeLoaded: function (tilePoint) {
2780                 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2781                         return false; // already loaded
2782                 }
2783
2784                 var options = this.options;
2785
2786                 if (!options.continuousWorld) {
2787                         var limit = this._getWrapTileNum();
2788
2789                         // don't load if exceeds world bounds
2790                         if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) ||
2791                                 tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; }
2792                 }
2793
2794                 if (options.bounds) {
2795                         var tileSize = options.tileSize,
2796                             nwPoint = tilePoint.multiplyBy(tileSize),
2797                             sePoint = nwPoint.add([tileSize, tileSize]),
2798                             nw = this._map.unproject(nwPoint),
2799                             se = this._map.unproject(sePoint);
2800
2801                         // TODO temporary hack, will be removed after refactoring projections
2802                         // https://github.com/Leaflet/Leaflet/issues/1618
2803                         if (!options.continuousWorld && !options.noWrap) {
2804                                 nw = nw.wrap();
2805                                 se = se.wrap();
2806                         }
2807
2808                         if (!options.bounds.intersects([nw, se])) { return false; }
2809                 }
2810
2811                 return true;
2812         },
2813
2814         _removeOtherTiles: function (bounds) {
2815                 var kArr, x, y, key;
2816
2817                 for (key in this._tiles) {
2818                         kArr = key.split(':');
2819                         x = parseInt(kArr[0], 10);
2820                         y = parseInt(kArr[1], 10);
2821
2822                         // remove tile if it's out of bounds
2823                         if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2824                                 this._removeTile(key);
2825                         }
2826                 }
2827         },
2828
2829         _removeTile: function (key) {
2830                 var tile = this._tiles[key];
2831
2832                 this.fire('tileunload', {tile: tile, url: tile.src});
2833
2834                 if (this.options.reuseTiles) {
2835                         L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2836                         this._unusedTiles.push(tile);
2837
2838                 } else if (tile.parentNode === this._tileContainer) {
2839                         this._tileContainer.removeChild(tile);
2840                 }
2841
2842                 // for https://github.com/CloudMade/Leaflet/issues/137
2843                 if (!L.Browser.android) {
2844                         tile.onload = null;
2845                         tile.src = L.Util.emptyImageUrl;
2846                 }
2847
2848                 delete this._tiles[key];
2849         },
2850
2851         _addTile: function (tilePoint, container) {
2852                 var tilePos = this._getTilePos(tilePoint);
2853
2854                 // get unused tile - or create a new tile
2855                 var tile = this._getTile();
2856
2857                 /*
2858                 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2859                 Android 4 browser has display issues with top/left and requires transform instead
2860                 Android 2 browser requires top/left or tiles disappear on load or first drag
2861                 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2862                 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2863                 */
2864                 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2865
2866                 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2867
2868                 this._loadTile(tile, tilePoint);
2869
2870                 if (tile.parentNode !== this._tileContainer) {
2871                         container.appendChild(tile);
2872                 }
2873         },
2874
2875         _getZoomForUrl: function () {
2876
2877                 var options = this.options,
2878                     zoom = this._map.getZoom();
2879
2880                 if (options.zoomReverse) {
2881                         zoom = options.maxZoom - zoom;
2882                 }
2883
2884                 zoom += options.zoomOffset;
2885
2886                 return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom;
2887         },
2888
2889         _getTilePos: function (tilePoint) {
2890                 var origin = this._map.getPixelOrigin(),
2891                     tileSize = this._getTileSize();
2892
2893                 return tilePoint.multiplyBy(tileSize).subtract(origin);
2894         },
2895
2896         // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2897
2898         getTileUrl: function (tilePoint) {
2899                 return L.Util.template(this._url, L.extend({
2900                         s: this._getSubdomain(tilePoint),
2901                         z: tilePoint.z,
2902                         x: tilePoint.x,
2903                         y: tilePoint.y
2904                 }, this.options));
2905         },
2906
2907         _getWrapTileNum: function () {
2908                 var crs = this._map.options.crs,
2909                     size = crs.getSize(this._map.getZoom());
2910                 return size.divideBy(this.options.tileSize);
2911         },
2912
2913         _adjustTilePoint: function (tilePoint) {
2914
2915                 var limit = this._getWrapTileNum();
2916
2917                 // wrap tile coordinates
2918                 if (!this.options.continuousWorld && !this.options.noWrap) {
2919                         tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x;
2920                 }
2921
2922                 if (this.options.tms) {
2923                         tilePoint.y = limit.y - tilePoint.y - 1;
2924                 }
2925
2926                 tilePoint.z = this._getZoomForUrl();
2927         },
2928
2929         _getSubdomain: function (tilePoint) {
2930                 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2931                 return this.options.subdomains[index];
2932         },
2933
2934         _getTile: function () {
2935                 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2936                         var tile = this._unusedTiles.pop();
2937                         this._resetTile(tile);
2938                         return tile;
2939                 }
2940                 return this._createTile();
2941         },
2942
2943         // Override if data stored on a tile needs to be cleaned up before reuse
2944         _resetTile: function (/*tile*/) {},
2945
2946         _createTile: function () {
2947                 var tile = L.DomUtil.create('img', 'leaflet-tile');
2948                 tile.style.width = tile.style.height = this._getTileSize() + 'px';
2949                 tile.galleryimg = 'no';
2950
2951                 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2952
2953                 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2954                         L.DomUtil.setOpacity(tile, this.options.opacity);
2955                 }
2956                 // without this hack, tiles disappear after zoom on Chrome for Android
2957                 // https://github.com/Leaflet/Leaflet/issues/2078
2958                 if (L.Browser.mobileWebkit3d) {
2959                         tile.style.WebkitBackfaceVisibility = 'hidden';
2960                 }
2961                 return tile;
2962         },
2963
2964         _loadTile: function (tile, tilePoint) {
2965                 tile._layer  = this;
2966                 tile.onload  = this._tileOnLoad;
2967                 tile.onerror = this._tileOnError;
2968
2969                 this._adjustTilePoint(tilePoint);
2970                 tile.src     = this.getTileUrl(tilePoint);
2971
2972                 this.fire('tileloadstart', {
2973                         tile: tile,
2974                         url: tile.src
2975                 });
2976         },
2977
2978         _tileLoaded: function () {
2979                 this._tilesToLoad--;
2980
2981                 if (this._animated) {
2982                         L.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated');
2983                 }
2984
2985                 if (!this._tilesToLoad) {
2986                         this.fire('load');
2987
2988                         if (this._animated) {
2989                                 // clear scaled tiles after all new tiles are loaded (for performance)
2990                                 clearTimeout(this._clearBgBufferTimer);
2991                                 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2992                         }
2993                 }
2994         },
2995
2996         _tileOnLoad: function () {
2997                 var layer = this._layer;
2998
2999                 //Only if we are loading an actual image
3000                 if (this.src !== L.Util.emptyImageUrl) {
3001                         L.DomUtil.addClass(this, 'leaflet-tile-loaded');
3002
3003                         layer.fire('tileload', {
3004                                 tile: this,
3005                                 url: this.src
3006                         });
3007                 }
3008
3009                 layer._tileLoaded();
3010         },
3011
3012         _tileOnError: function () {
3013                 var layer = this._layer;
3014
3015                 layer.fire('tileerror', {
3016                         tile: this,
3017                         url: this.src
3018                 });
3019
3020                 var newUrl = layer.options.errorTileUrl;
3021                 if (newUrl) {
3022                         this.src = newUrl;
3023                 }
3024
3025                 layer._tileLoaded();
3026         }
3027 });
3028
3029 L.tileLayer = function (url, options) {
3030         return new L.TileLayer(url, options);
3031 };
3032
3033
3034 /*
3035  * L.TileLayer.WMS is used for putting WMS tile layers on the map.
3036  */
3037
3038 L.TileLayer.WMS = L.TileLayer.extend({
3039
3040         defaultWmsParams: {
3041                 service: 'WMS',
3042                 request: 'GetMap',
3043                 version: '1.1.1',
3044                 layers: '',
3045                 styles: '',
3046                 format: 'image/jpeg',
3047                 transparent: false
3048         },
3049
3050         initialize: function (url, options) { // (String, Object)
3051
3052                 this._url = url;
3053
3054                 var wmsParams = L.extend({}, this.defaultWmsParams),
3055                     tileSize = options.tileSize || this.options.tileSize;
3056
3057                 if (options.detectRetina && L.Browser.retina) {
3058                         wmsParams.width = wmsParams.height = tileSize * 2;
3059                 } else {
3060                         wmsParams.width = wmsParams.height = tileSize;
3061                 }
3062
3063                 for (var i in options) {
3064                         // all keys that are not TileLayer options go to WMS params
3065                         if (!this.options.hasOwnProperty(i) && i !== 'crs') {
3066                                 wmsParams[i] = options[i];
3067                         }
3068                 }
3069
3070                 this.wmsParams = wmsParams;
3071
3072                 L.setOptions(this, options);
3073         },
3074
3075         onAdd: function (map) {
3076
3077                 this._crs = this.options.crs || map.options.crs;
3078
3079                 this._wmsVersion = parseFloat(this.wmsParams.version);
3080
3081                 var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
3082                 this.wmsParams[projectionKey] = this._crs.code;
3083
3084                 L.TileLayer.prototype.onAdd.call(this, map);
3085         },
3086
3087         getTileUrl: function (tilePoint) { // (Point, Number) -> String
3088
3089                 var map = this._map,
3090                     tileSize = this.options.tileSize,
3091
3092                     nwPoint = tilePoint.multiplyBy(tileSize),
3093                     sePoint = nwPoint.add([tileSize, tileSize]),
3094
3095                     nw = this._crs.project(map.unproject(nwPoint, tilePoint.z)),
3096                     se = this._crs.project(map.unproject(sePoint, tilePoint.z)),
3097                     bbox = this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
3098                         [se.y, nw.x, nw.y, se.x].join(',') :
3099                         [nw.x, se.y, se.x, nw.y].join(','),
3100
3101                     url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
3102
3103                 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
3104         },
3105
3106         setParams: function (params, noRedraw) {
3107
3108                 L.extend(this.wmsParams, params);
3109
3110                 if (!noRedraw) {
3111                         this.redraw();
3112                 }
3113
3114                 return this;
3115         }
3116 });
3117
3118 L.tileLayer.wms = function (url, options) {
3119         return new L.TileLayer.WMS(url, options);
3120 };
3121
3122
3123 /*
3124  * L.TileLayer.Canvas is a class that you can use as a base for creating
3125  * dynamically drawn Canvas-based tile layers.
3126  */
3127
3128 L.TileLayer.Canvas = L.TileLayer.extend({
3129         options: {
3130                 async: false
3131         },
3132
3133         initialize: function (options) {
3134                 L.setOptions(this, options);
3135         },
3136
3137         redraw: function () {
3138                 if (this._map) {
3139                         this._reset({hard: true});
3140                         this._update();
3141                 }
3142
3143                 for (var i in this._tiles) {
3144                         this._redrawTile(this._tiles[i]);
3145                 }
3146                 return this;
3147         },
3148
3149         _redrawTile: function (tile) {
3150                 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3151         },
3152
3153         _createTile: function () {
3154                 var tile = L.DomUtil.create('canvas', 'leaflet-tile');
3155                 tile.width = tile.height = this.options.tileSize;
3156                 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3157                 return tile;
3158         },
3159
3160         _loadTile: function (tile, tilePoint) {
3161                 tile._layer = this;
3162                 tile._tilePoint = tilePoint;
3163
3164                 this._redrawTile(tile);
3165
3166                 if (!this.options.async) {
3167                         this.tileDrawn(tile);
3168                 }
3169         },
3170
3171         drawTile: function (/*tile, tilePoint*/) {
3172                 // override with rendering code
3173         },
3174
3175         tileDrawn: function (tile) {
3176                 this._tileOnLoad.call(tile);
3177         }
3178 });
3179
3180
3181 L.tileLayer.canvas = function (options) {
3182         return new L.TileLayer.Canvas(options);
3183 };
3184
3185
3186 /*
3187  * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3188  */
3189
3190 L.ImageOverlay = L.Class.extend({
3191         includes: L.Mixin.Events,
3192
3193         options: {
3194                 opacity: 1
3195         },
3196
3197         initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3198                 this._url = url;
3199                 this._bounds = L.latLngBounds(bounds);
3200
3201                 L.setOptions(this, options);
3202         },
3203
3204         onAdd: function (map) {
3205                 this._map = map;
3206
3207                 if (!this._image) {
3208                         this._initImage();
3209                 }
3210
3211                 map._panes.overlayPane.appendChild(this._image);
3212
3213                 map.on('viewreset', this._reset, this);
3214
3215                 if (map.options.zoomAnimation && L.Browser.any3d) {
3216                         map.on('zoomanim', this._animateZoom, this);
3217                 }
3218
3219                 this._reset();
3220         },
3221
3222         onRemove: function (map) {
3223                 map.getPanes().overlayPane.removeChild(this._image);
3224
3225                 map.off('viewreset', this._reset, this);
3226
3227                 if (map.options.zoomAnimation) {
3228                         map.off('zoomanim', this._animateZoom, this);
3229                 }
3230         },
3231
3232         addTo: function (map) {
3233                 map.addLayer(this);
3234                 return this;
3235         },
3236
3237         setOpacity: function (opacity) {
3238                 this.options.opacity = opacity;
3239                 this._updateOpacity();
3240                 return this;
3241         },
3242
3243         // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3244         bringToFront: function () {
3245                 if (this._image) {
3246                         this._map._panes.overlayPane.appendChild(this._image);
3247                 }
3248                 return this;
3249         },
3250
3251         bringToBack: function () {
3252                 var pane = this._map._panes.overlayPane;
3253                 if (this._image) {
3254                         pane.insertBefore(this._image, pane.firstChild);
3255                 }
3256                 return this;
3257         },
3258
3259         setUrl: function (url) {
3260                 this._url = url;
3261                 this._image.src = this._url;
3262         },
3263
3264         getAttribution: function () {
3265                 return this.options.attribution;
3266         },
3267
3268         _initImage: function () {
3269                 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3270
3271                 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3272                         L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3273                 } else {
3274                         L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3275                 }
3276
3277                 this._updateOpacity();
3278
3279                 //TODO createImage util method to remove duplication
3280                 L.extend(this._image, {
3281                         galleryimg: 'no',
3282                         onselectstart: L.Util.falseFn,
3283                         onmousemove: L.Util.falseFn,
3284                         onload: L.bind(this._onImageLoad, this),
3285                         src: this._url
3286                 });
3287         },
3288
3289         _animateZoom: function (e) {
3290                 var map = this._map,
3291                     image = this._image,
3292                     scale = map.getZoomScale(e.zoom),
3293                     nw = this._bounds.getNorthWest(),
3294                     se = this._bounds.getSouthEast(),
3295
3296                     topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3297                     size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3298                     origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3299
3300                 image.style[L.DomUtil.TRANSFORM] =
3301                         L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3302         },
3303
3304         _reset: function () {
3305                 var image   = this._image,
3306                     topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3307                     size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3308
3309                 L.DomUtil.setPosition(image, topLeft);
3310
3311                 image.style.width  = size.x + 'px';
3312                 image.style.height = size.y + 'px';
3313         },
3314
3315         _onImageLoad: function () {
3316                 this.fire('load');
3317         },
3318
3319         _updateOpacity: function () {
3320                 L.DomUtil.setOpacity(this._image, this.options.opacity);
3321         }
3322 });
3323
3324 L.imageOverlay = function (url, bounds, options) {
3325         return new L.ImageOverlay(url, bounds, options);
3326 };
3327
3328
3329 /*
3330  * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3331  */
3332
3333 L.Icon = L.Class.extend({
3334         options: {
3335                 /*
3336                 iconUrl: (String) (required)
3337                 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3338                 iconSize: (Point) (can be set through CSS)
3339                 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3340                 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3341                 shadowUrl: (String) (no shadow by default)
3342                 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3343                 shadowSize: (Point)
3344                 shadowAnchor: (Point)
3345                 */
3346                 className: ''
3347         },
3348
3349         initialize: function (options) {
3350                 L.setOptions(this, options);
3351         },
3352
3353         createIcon: function (oldIcon) {
3354                 return this._createIcon('icon', oldIcon);
3355         },
3356
3357         createShadow: function (oldIcon) {
3358                 return this._createIcon('shadow', oldIcon);
3359         },
3360
3361         _createIcon: function (name, oldIcon) {
3362                 var src = this._getIconUrl(name);
3363
3364                 if (!src) {
3365                         if (name === 'icon') {
3366                                 throw new Error('iconUrl not set in Icon options (see the docs).');
3367                         }
3368                         return null;
3369                 }
3370
3371                 var img;
3372                 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3373                         img = this._createImg(src);
3374                 } else {
3375                         img = this._createImg(src, oldIcon);
3376                 }
3377                 this._setIconStyles(img, name);
3378
3379                 return img;
3380         },
3381
3382         _setIconStyles: function (img, name) {
3383                 var options = this.options,
3384                     size = L.point(options[name + 'Size']),
3385                     anchor;
3386
3387                 if (name === 'shadow') {
3388                         anchor = L.point(options.shadowAnchor || options.iconAnchor);
3389                 } else {
3390                         anchor = L.point(options.iconAnchor);
3391                 }
3392
3393                 if (!anchor && size) {
3394                         anchor = size.divideBy(2, true);
3395                 }
3396
3397                 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3398
3399                 if (anchor) {
3400                         img.style.marginLeft = (-anchor.x) + 'px';
3401                         img.style.marginTop  = (-anchor.y) + 'px';
3402                 }
3403
3404                 if (size) {
3405                         img.style.width  = size.x + 'px';
3406                         img.style.height = size.y + 'px';
3407                 }
3408         },
3409
3410         _createImg: function (src, el) {
3411                 el = el || document.createElement('img');
3412                 el.src = src;
3413                 return el;
3414         },
3415
3416         _getIconUrl: function (name) {
3417                 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3418                         return this.options[name + 'RetinaUrl'];
3419                 }
3420                 return this.options[name + 'Url'];
3421         }
3422 });
3423
3424 L.icon = function (options) {
3425         return new L.Icon(options);
3426 };
3427
3428
3429 /*
3430  * L.Icon.Default is the blue marker icon used by default in Leaflet.
3431  */
3432
3433 L.Icon.Default = L.Icon.extend({
3434
3435         options: {
3436                 iconSize: [25, 41],
3437                 iconAnchor: [12, 41],
3438                 popupAnchor: [1, -34],
3439
3440                 shadowSize: [41, 41]
3441         },
3442
3443         _getIconUrl: function (name) {
3444                 var key = name + 'Url';
3445
3446                 if (this.options[key]) {
3447                         return this.options[key];
3448                 }
3449
3450                 if (L.Browser.retina && name === 'icon') {
3451                         name += '-2x';
3452                 }
3453
3454                 var path = L.Icon.Default.imagePath;
3455
3456                 if (!path) {
3457                         throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3458                 }
3459
3460                 return path + '/marker-' + name + '.png';
3461         }
3462 });
3463
3464 L.Icon.Default.imagePath = (function () {
3465         var scripts = document.getElementsByTagName('script'),
3466             leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3467
3468         var i, len, src, matches, path;
3469
3470         for (i = 0, len = scripts.length; i < len; i++) {
3471                 src = scripts[i].src;
3472                 matches = src.match(leafletRe);
3473
3474                 if (matches) {
3475                         path = src.split(leafletRe)[0];
3476                         return (path ? path + '/' : '') + 'images';
3477                 }
3478         }
3479 }());
3480
3481
3482 /*
3483  * L.Marker is used to display clickable/draggable icons on the map.
3484  */
3485
3486 L.Marker = L.Class.extend({
3487
3488         includes: L.Mixin.Events,
3489
3490         options: {
3491                 icon: new L.Icon.Default(),
3492                 title: '',
3493                 alt: '',
3494                 clickable: true,
3495                 draggable: false,
3496                 keyboard: true,
3497                 zIndexOffset: 0,
3498                 opacity: 1,
3499                 riseOnHover: false,
3500                 riseOffset: 250
3501         },
3502
3503         initialize: function (latlng, options) {
3504                 L.setOptions(this, options);
3505                 this._latlng = L.latLng(latlng);
3506         },
3507
3508         onAdd: function (map) {
3509                 this._map = map;
3510
3511                 map.on('viewreset', this.update, this);
3512
3513                 this._initIcon();
3514                 this.update();
3515                 this.fire('add');
3516
3517                 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3518                         map.on('zoomanim', this._animateZoom, this);
3519                 }
3520         },
3521
3522         addTo: function (map) {
3523                 map.addLayer(this);
3524                 return this;
3525         },
3526
3527         onRemove: function (map) {
3528                 if (this.dragging) {
3529                         this.dragging.disable();
3530                 }
3531
3532                 this._removeIcon();
3533                 this._removeShadow();
3534
3535                 this.fire('remove');
3536
3537                 map.off({
3538                         'viewreset': this.update,
3539                         'zoomanim': this._animateZoom
3540                 }, this);
3541
3542                 this._map = null;
3543         },
3544
3545         getLatLng: function () {
3546                 return this._latlng;
3547         },
3548
3549         setLatLng: function (latlng) {
3550                 this._latlng = L.latLng(latlng);
3551
3552                 this.update();
3553
3554                 return this.fire('move', { latlng: this._latlng });
3555         },
3556
3557         setZIndexOffset: function (offset) {
3558                 this.options.zIndexOffset = offset;
3559                 this.update();
3560
3561                 return this;
3562         },
3563
3564         setIcon: function (icon) {
3565
3566                 this.options.icon = icon;
3567
3568                 if (this._map) {
3569                         this._initIcon();
3570                         this.update();
3571                 }
3572
3573                 if (this._popup) {
3574                         this.bindPopup(this._popup);
3575                 }
3576
3577                 return this;
3578         },
3579
3580         update: function () {
3581                 if (this._icon) {
3582                         var pos = this._map.latLngToLayerPoint(this._latlng).round();
3583                         this._setPos(pos);
3584                 }
3585
3586                 return this;
3587         },
3588
3589         _initIcon: function () {
3590                 var options = this.options,
3591                     map = this._map,
3592                     animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3593                     classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3594
3595                 var icon = options.icon.createIcon(this._icon),
3596                         addIcon = false;
3597
3598                 // if we're not reusing the icon, remove the old one and init new one
3599                 if (icon !== this._icon) {
3600                         if (this._icon) {
3601                                 this._removeIcon();
3602                         }
3603                         addIcon = true;
3604
3605                         if (options.title) {
3606                                 icon.title = options.title;
3607                         }
3608                         
3609                         if (options.alt) {
3610                                 icon.alt = options.alt;
3611                         }
3612                 }
3613
3614                 L.DomUtil.addClass(icon, classToAdd);
3615
3616                 if (options.keyboard) {
3617                         icon.tabIndex = '0';
3618                 }
3619
3620                 this._icon = icon;
3621
3622                 this._initInteraction();
3623
3624                 if (options.riseOnHover) {
3625                         L.DomEvent
3626                                 .on(icon, 'mouseover', this._bringToFront, this)
3627                                 .on(icon, 'mouseout', this._resetZIndex, this);
3628                 }
3629
3630                 var newShadow = options.icon.createShadow(this._shadow),
3631                         addShadow = false;
3632
3633                 if (newShadow !== this._shadow) {
3634                         this._removeShadow();
3635                         addShadow = true;
3636                 }
3637
3638                 if (newShadow) {
3639                         L.DomUtil.addClass(newShadow, classToAdd);
3640                 }
3641                 this._shadow = newShadow;
3642
3643
3644                 if (options.opacity < 1) {
3645                         this._updateOpacity();
3646                 }
3647
3648
3649                 var panes = this._map._panes;
3650
3651                 if (addIcon) {
3652                         panes.markerPane.appendChild(this._icon);
3653                 }
3654
3655                 if (newShadow && addShadow) {
3656                         panes.shadowPane.appendChild(this._shadow);
3657                 }
3658         },
3659
3660         _removeIcon: function () {
3661                 if (this.options.riseOnHover) {
3662                         L.DomEvent
3663                             .off(this._icon, 'mouseover', this._bringToFront)
3664                             .off(this._icon, 'mouseout', this._resetZIndex);
3665                 }
3666
3667                 this._map._panes.markerPane.removeChild(this._icon);
3668
3669                 this._icon = null;
3670         },
3671
3672         _removeShadow: function () {
3673                 if (this._shadow) {
3674                         this._map._panes.shadowPane.removeChild(this._shadow);
3675                 }
3676                 this._shadow = null;
3677         },
3678
3679         _setPos: function (pos) {
3680                 L.DomUtil.setPosition(this._icon, pos);
3681
3682                 if (this._shadow) {
3683                         L.DomUtil.setPosition(this._shadow, pos);
3684                 }
3685
3686                 this._zIndex = pos.y + this.options.zIndexOffset;
3687
3688                 this._resetZIndex();
3689         },
3690
3691         _updateZIndex: function (offset) {
3692                 this._icon.style.zIndex = this._zIndex + offset;
3693         },
3694
3695         _animateZoom: function (opt) {
3696                 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
3697
3698                 this._setPos(pos);
3699         },
3700
3701         _initInteraction: function () {
3702
3703                 if (!this.options.clickable) { return; }
3704
3705                 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3706
3707                 var icon = this._icon,
3708                     events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3709
3710                 L.DomUtil.addClass(icon, 'leaflet-clickable');
3711                 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3712                 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3713
3714                 for (var i = 0; i < events.length; i++) {
3715                         L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3716                 }
3717
3718                 if (L.Handler.MarkerDrag) {
3719                         this.dragging = new L.Handler.MarkerDrag(this);
3720
3721                         if (this.options.draggable) {
3722                                 this.dragging.enable();
3723                         }
3724                 }
3725         },
3726
3727         _onMouseClick: function (e) {
3728                 var wasDragged = this.dragging && this.dragging.moved();
3729
3730                 if (this.hasEventListeners(e.type) || wasDragged) {
3731                         L.DomEvent.stopPropagation(e);
3732                 }
3733
3734                 if (wasDragged) { return; }
3735
3736                 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3737
3738                 this.fire(e.type, {
3739                         originalEvent: e,
3740                         latlng: this._latlng
3741                 });
3742         },
3743
3744         _onKeyPress: function (e) {
3745                 if (e.keyCode === 13) {
3746                         this.fire('click', {
3747                                 originalEvent: e,
3748                                 latlng: this._latlng
3749                         });
3750                 }
3751         },
3752
3753         _fireMouseEvent: function (e) {
3754
3755                 this.fire(e.type, {
3756                         originalEvent: e,
3757                         latlng: this._latlng
3758                 });
3759
3760                 // TODO proper custom event propagation
3761                 // this line will always be called if marker is in a FeatureGroup
3762                 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3763                         L.DomEvent.preventDefault(e);
3764                 }
3765                 if (e.type !== 'mousedown') {
3766                         L.DomEvent.stopPropagation(e);
3767                 } else {
3768                         L.DomEvent.preventDefault(e);
3769                 }
3770         },
3771
3772         setOpacity: function (opacity) {
3773                 this.options.opacity = opacity;
3774                 if (this._map) {
3775                         this._updateOpacity();
3776                 }
3777
3778                 return this;
3779         },
3780
3781         _updateOpacity: function () {
3782                 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3783                 if (this._shadow) {
3784                         L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3785                 }
3786         },
3787
3788         _bringToFront: function () {
3789                 this._updateZIndex(this.options.riseOffset);
3790         },
3791
3792         _resetZIndex: function () {
3793                 this._updateZIndex(0);
3794         }
3795 });
3796
3797 L.marker = function (latlng, options) {
3798         return new L.Marker(latlng, options);
3799 };
3800
3801
3802 /*
3803  * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3804  * to use with L.Marker.
3805  */
3806
3807 L.DivIcon = L.Icon.extend({
3808         options: {
3809                 iconSize: [12, 12], // also can be set through CSS
3810                 /*
3811                 iconAnchor: (Point)
3812                 popupAnchor: (Point)
3813                 html: (String)
3814                 bgPos: (Point)
3815                 */
3816                 className: 'leaflet-div-icon',
3817                 html: false
3818         },
3819
3820         createIcon: function (oldIcon) {
3821                 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3822                     options = this.options;
3823
3824                 if (options.html !== false) {
3825                         div.innerHTML = options.html;
3826                 } else {
3827                         div.innerHTML = '';
3828                 }
3829
3830                 if (options.bgPos) {
3831                         div.style.backgroundPosition =
3832                                 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3833                 }
3834
3835                 this._setIconStyles(div, 'icon');
3836                 return div;
3837         },
3838
3839         createShadow: function () {
3840                 return null;
3841         }
3842 });
3843
3844 L.divIcon = function (options) {
3845         return new L.DivIcon(options);
3846 };
3847
3848
3849 /*
3850  * L.Popup is used for displaying popups on the map.
3851  */
3852
3853 L.Map.mergeOptions({
3854         closePopupOnClick: true
3855 });
3856
3857 L.Popup = L.Class.extend({
3858         includes: L.Mixin.Events,
3859
3860         options: {
3861                 minWidth: 50,
3862                 maxWidth: 300,
3863                 // maxHeight: null,
3864                 autoPan: true,
3865                 closeButton: true,
3866                 offset: [0, 7],
3867                 autoPanPadding: [5, 5],
3868                 // autoPanPaddingTopLeft: null,
3869                 // autoPanPaddingBottomRight: null,
3870                 keepInView: false,
3871                 className: '',
3872                 zoomAnimation: true
3873         },
3874
3875         initialize: function (options, source) {
3876                 L.setOptions(this, options);
3877
3878                 this._source = source;
3879                 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3880                 this._isOpen = false;
3881         },
3882
3883         onAdd: function (map) {
3884                 this._map = map;
3885
3886                 if (!this._container) {
3887                         this._initLayout();
3888                 }
3889
3890                 var animFade = map.options.fadeAnimation;
3891
3892                 if (animFade) {
3893                         L.DomUtil.setOpacity(this._container, 0);
3894                 }
3895                 map._panes.popupPane.appendChild(this._container);
3896
3897                 map.on(this._getEvents(), this);
3898
3899                 this.update();
3900
3901                 if (animFade) {
3902                         L.DomUtil.setOpacity(this._container, 1);
3903                 }
3904
3905                 this.fire('open');
3906
3907                 map.fire('popupopen', {popup: this});
3908
3909                 if (this._source) {
3910                         this._source.fire('popupopen', {popup: this});
3911                 }
3912         },
3913
3914         addTo: function (map) {
3915                 map.addLayer(this);
3916                 return this;
3917         },
3918
3919         openOn: function (map) {
3920                 map.openPopup(this);
3921                 return this;
3922         },
3923
3924         onRemove: function (map) {
3925                 map._panes.popupPane.removeChild(this._container);
3926
3927                 L.Util.falseFn(this._container.offsetWidth); // force reflow
3928
3929                 map.off(this._getEvents(), this);
3930
3931                 if (map.options.fadeAnimation) {
3932                         L.DomUtil.setOpacity(this._container, 0);
3933                 }
3934
3935                 this._map = null;
3936
3937                 this.fire('close');
3938
3939                 map.fire('popupclose', {popup: this});
3940
3941        &n