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