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