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