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