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