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