2 Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
3 (c) 2010-2013, Vladimir Agafonkin
4 (c) 2010-2011, CloudMade
6 (function (window, document, undefined) {
12 // define Leaflet for Node module pattern loaders, including Browserify
13 if (typeof module === 'object' && typeof module.exports === 'object') {
16 // define Leaflet as an AMD module
17 } else if (typeof define === 'function' && define.amd) {
21 // define Leaflet as a global L variable, saving the original L to restore later if needed
23 L.noConflict = function () {
32 * L.Util contains various utility functions used throughout Leaflet code.
36 extend: function (dest) { // (Object[, Object, ...]) ->
37 var sources = Array.prototype.slice.call(arguments, 1),
40 for (j = 0, len = sources.length; j < len; j++) {
41 src = sources[j] || {};
43 if (src.hasOwnProperty(i)) {
51 bind: function (fn, obj) { // (Function, Object) -> Function
52 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
54 return fn.apply(obj, args || arguments);
61 return function (obj) {
62 obj[key] = obj[key] || ++lastId;
67 invokeEach: function (obj, method, context) {
70 if (typeof obj === 'object') {
71 args = Array.prototype.slice.call(arguments, 3);
74 method.apply(context, [i, obj[i]].concat(args));
82 limitExecByInterval: function (fn, time, context) {
83 var lock, execOnUnlock;
85 return function wrapperFn() {
95 setTimeout(function () {
99 wrapperFn.apply(context, args);
100 execOnUnlock = false;
104 fn.apply(context, args);
108 falseFn: function () {
112 formatNum: function (num, digits) {
113 var pow = Math.pow(10, digits || 5);
114 return Math.round(num * pow) / pow;
117 trim: function (str) {
118 return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
121 splitWords: function (str) {
122 return L.Util.trim(str).split(/\s+/);
125 setOptions: function (obj, options) {
126 obj.options = L.extend({}, obj.options, options);
130 getParamString: function (obj, existingUrl, uppercase) {
133 params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
135 return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
138 template: function (str, data) {
139 return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
140 var value = data[key];
141 if (value === undefined) {
142 throw new Error('No value provided for variable ' + str);
143 } else if (typeof value === 'function') {
150 isArray: function (obj) {
151 return (Object.prototype.toString.call(obj) === '[object Array]');
154 emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
159 // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
161 function getPrefixed(name) {
163 prefixes = ['webkit', 'moz', 'o', 'ms'];
165 for (i = 0; i < prefixes.length && !fn; i++) {
166 fn = window[prefixes[i] + name];
174 function timeoutDefer(fn) {
175 var time = +new Date(),
176 timeToCall = Math.max(0, 16 - (time - lastTime));
178 lastTime = time + timeToCall;
179 return window.setTimeout(fn, timeToCall);
182 var requestFn = window.requestAnimationFrame ||
183 getPrefixed('RequestAnimationFrame') || timeoutDefer;
185 var cancelFn = window.cancelAnimationFrame ||
186 getPrefixed('CancelAnimationFrame') ||
187 getPrefixed('CancelRequestAnimationFrame') ||
188 function (id) { window.clearTimeout(id); };
191 L.Util.requestAnimFrame = function (fn, context, immediate, element) {
192 fn = L.bind(fn, context);
194 if (immediate && requestFn === timeoutDefer) {
197 return requestFn.call(window, fn, element);
201 L.Util.cancelAnimFrame = function (id) {
203 cancelFn.call(window, id);
209 // shortcuts for most used utility functions
210 L.extend = L.Util.extend;
211 L.bind = L.Util.bind;
212 L.stamp = L.Util.stamp;
213 L.setOptions = L.Util.setOptions;
217 * L.Class powers the OOP facilities of the library.
218 * Thanks to John Resig and Dean Edwards for inspiration!
221 L.Class = function () {};
223 L.Class.extend = function (props) {
225 // extended class with the new prototype
226 var NewClass = function () {
228 // call the constructor
229 if (this.initialize) {
230 this.initialize.apply(this, arguments);
233 // call all constructor hooks
234 if (this._initHooks) {
235 this.callInitHooks();
239 // instantiate class without calling constructor
240 var F = function () {};
241 F.prototype = this.prototype;
244 proto.constructor = NewClass;
246 NewClass.prototype = proto;
248 //inherit parent's statics
249 for (var i in this) {
250 if (this.hasOwnProperty(i) && i !== 'prototype') {
251 NewClass[i] = this[i];
255 // mix static properties into the class
257 L.extend(NewClass, props.statics);
258 delete props.statics;
261 // mix includes into the prototype
262 if (props.includes) {
263 L.Util.extend.apply(null, [proto].concat(props.includes));
264 delete props.includes;
268 if (props.options && proto.options) {
269 props.options = L.extend({}, proto.options, props.options);
272 // mix given properties into the prototype
273 L.extend(proto, props);
275 proto._initHooks = [];
278 // jshint camelcase: false
279 NewClass.__super__ = parent.prototype;
281 // add method for calling all hooks
282 proto.callInitHooks = function () {
284 if (this._initHooksCalled) { return; }
286 if (parent.prototype.callInitHooks) {
287 parent.prototype.callInitHooks.call(this);
290 this._initHooksCalled = true;
292 for (var i = 0, len = proto._initHooks.length; i < len; i++) {
293 proto._initHooks[i].call(this);
301 // method for adding properties to prototype
302 L.Class.include = function (props) {
303 L.extend(this.prototype, props);
306 // merge new default options to the Class
307 L.Class.mergeOptions = function (options) {
308 L.extend(this.prototype.options, options);
311 // add a constructor hook
312 L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
313 var args = Array.prototype.slice.call(arguments, 1);
315 var init = typeof fn === 'function' ? fn : function () {
316 this[fn].apply(this, args);
319 this.prototype._initHooks = this.prototype._initHooks || [];
320 this.prototype._initHooks.push(init);
325 * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
328 var eventsKey = '_leaflet_events';
334 addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
336 // types can be a map of types/handlers
337 if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
339 var events = this[eventsKey] = this[eventsKey] || {},
340 contextId = context && L.stamp(context),
341 i, len, event, type, indexKey, indexLenKey, typeIndex;
343 // types can be a string of space-separated words
344 types = L.Util.splitWords(types);
346 for (i = 0, len = types.length; i < len; i++) {
349 context: context || this
354 // store listeners of a particular context in a separate hash (if it has an id)
355 // gives a major performance boost when removing thousands of map layers
357 indexKey = type + '_idx';
358 indexLenKey = indexKey + '_len';
360 typeIndex = events[indexKey] = events[indexKey] || {};
362 if (!typeIndex[contextId]) {
363 typeIndex[contextId] = [];
365 // keep track of the number of keys in the index to quickly check if it's empty
366 events[indexLenKey] = (events[indexLenKey] || 0) + 1;
369 typeIndex[contextId].push(event);
373 events[type] = events[type] || [];
374 events[type].push(event);
381 hasEventListeners: function (type) { // (String) -> Boolean
382 var events = this[eventsKey];
383 return !!events && ((type in events && events[type].length > 0) ||
384 (type + '_idx' in events && events[type + '_idx_len'] > 0));
387 removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
389 if (!this[eventsKey]) {
394 return this.clearAllEventListeners();
397 if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
399 var events = this[eventsKey],
400 contextId = context && L.stamp(context),
401 i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
403 types = L.Util.splitWords(types);
405 for (i = 0, len = types.length; i < len; i++) {
407 indexKey = type + '_idx';
408 indexLenKey = indexKey + '_len';
410 typeIndex = events[indexKey];
413 // clear all listeners for a type if function isn't specified
415 delete events[indexKey];
418 listeners = context && typeIndex ? typeIndex[contextId] : events[type];
421 for (j = listeners.length - 1; j >= 0; j--) {
422 if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
423 removed = listeners.splice(j, 1);
424 // set the old action to a no-op, because it is possible
425 // that the listener is being iterated over as part of a dispatch
426 removed[0].action = L.Util.falseFn;
430 if (context && typeIndex && (listeners.length === 0)) {
431 delete typeIndex[contextId];
432 events[indexLenKey]--;
441 clearAllEventListeners: function () {
442 delete this[eventsKey];
446 fireEvent: function (type, data) { // (String[, Object])
447 if (!this.hasEventListeners(type)) {
451 var event = L.Util.extend({}, data, { type: type, target: this });
453 var events = this[eventsKey],
454 listeners, i, len, typeIndex, contextId;
457 // make sure adding/removing listeners inside other listeners won't cause infinite loop
458 listeners = events[type].slice();
460 for (i = 0, len = listeners.length; i < len; i++) {
461 listeners[i].action.call(listeners[i].context || this, event);
465 // fire event for the context-indexed listeners as well
466 typeIndex = events[type + '_idx'];
468 for (contextId in typeIndex) {
469 listeners = typeIndex[contextId].slice();
472 for (i = 0, len = listeners.length; i < len; i++) {
473 listeners[i].action.call(listeners[i].context || this, event);
481 addOneTimeEventListener: function (types, fn, context) {
483 if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
485 var handler = L.bind(function () {
487 .removeEventListener(types, fn, context)
488 .removeEventListener(types, handler, context);
492 .addEventListener(types, fn, context)
493 .addEventListener(types, handler, context);
497 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
498 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
499 L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
500 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
504 * L.Browser handles different browser and feature detections for internal Leaflet use.
509 var ie = !!window.ActiveXObject,
510 ie6 = ie && !window.XMLHttpRequest,
511 ie7 = ie && !document.querySelector,
512 ielt9 = ie && !document.addEventListener,
514 // terrible browser detection to work around Safari / iOS / Android browser bugs
515 ua = navigator.userAgent.toLowerCase(),
516 webkit = ua.indexOf('webkit') !== -1,
517 chrome = ua.indexOf('chrome') !== -1,
518 phantomjs = ua.indexOf('phantom') !== -1,
519 android = ua.indexOf('android') !== -1,
520 android23 = ua.search('android [23]') !== -1,
522 mobile = typeof orientation !== undefined + '',
523 msTouch = window.navigator && window.navigator.msPointerEnabled &&
524 window.navigator.msMaxTouchPoints,
525 retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
526 ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
527 window.matchMedia('(min-resolution:144dpi)').matches),
529 doc = document.documentElement,
530 ie3d = ie && ('transition' in doc.style),
531 webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
532 gecko3d = 'MozPerspective' in doc.style,
533 opera3d = 'OTransition' in doc.style,
534 any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
537 // PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch.
538 // https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151
540 var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
542 var startName = 'ontouchstart';
544 // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.MsTouch) or WebKit, etc.
545 if (msTouch || (startName in doc)) {
550 var div = document.createElement('div'),
553 if (!div.setAttribute) {
556 div.setAttribute(startName, 'return;');
558 if (typeof div[startName] === 'function') {
562 div.removeAttribute(startName);
577 android23: android23,
588 mobileWebkit: mobile && webkit,
589 mobileWebkit3d: mobile && webkit3d,
590 mobileOpera: mobile && window.opera,
602 * L.Point represents a point with x and y coordinates.
605 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
606 this.x = (round ? Math.round(x) : x);
607 this.y = (round ? Math.round(y) : y);
610 L.Point.prototype = {
613 return new L.Point(this.x, this.y);
616 // non-destructive, returns a new point
617 add: function (point) {
618 return this.clone()._add(L.point(point));
621 // destructive, used directly for performance in situations where it's safe to modify existing point
622 _add: function (point) {
628 subtract: function (point) {
629 return this.clone()._subtract(L.point(point));
632 _subtract: function (point) {
638 divideBy: function (num) {
639 return this.clone()._divideBy(num);
642 _divideBy: function (num) {
648 multiplyBy: function (num) {
649 return this.clone()._multiplyBy(num);
652 _multiplyBy: function (num) {
659 return this.clone()._round();
662 _round: function () {
663 this.x = Math.round(this.x);
664 this.y = Math.round(this.y);
669 return this.clone()._floor();
672 _floor: function () {
673 this.x = Math.floor(this.x);
674 this.y = Math.floor(this.y);
678 distanceTo: function (point) {
679 point = L.point(point);
681 var x = point.x - this.x,
682 y = point.y - this.y;
684 return Math.sqrt(x * x + y * y);
687 equals: function (point) {
688 point = L.point(point);
690 return point.x === this.x &&
694 contains: function (point) {
695 point = L.point(point);
697 return Math.abs(point.x) <= Math.abs(this.x) &&
698 Math.abs(point.y) <= Math.abs(this.y);
701 toString: function () {
703 L.Util.formatNum(this.x) + ', ' +
704 L.Util.formatNum(this.y) + ')';
708 L.point = function (x, y, round) {
709 if (x instanceof L.Point) {
712 if (L.Util.isArray(x)) {
713 return new L.Point(x[0], x[1]);
715 if (x === undefined || x === null) {
718 return new L.Point(x, y, round);
723 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
726 L.Bounds = function (a, b) { //(Point, Point) or Point[]
729 var points = b ? [a, b] : a;
731 for (var i = 0, len = points.length; i < len; i++) {
732 this.extend(points[i]);
736 L.Bounds.prototype = {
737 // extend the bounds to contain the given point
738 extend: function (point) { // (Point)
739 point = L.point(point);
741 if (!this.min && !this.max) {
742 this.min = point.clone();
743 this.max = point.clone();
745 this.min.x = Math.min(point.x, this.min.x);
746 this.max.x = Math.max(point.x, this.max.x);
747 this.min.y = Math.min(point.y, this.min.y);
748 this.max.y = Math.max(point.y, this.max.y);
753 getCenter: function (round) { // (Boolean) -> Point
755 (this.min.x + this.max.x) / 2,
756 (this.min.y + this.max.y) / 2, round);
759 getBottomLeft: function () { // -> Point
760 return new L.Point(this.min.x, this.max.y);
763 getTopRight: function () { // -> Point
764 return new L.Point(this.max.x, this.min.y);
767 getSize: function () {
768 return this.max.subtract(this.min);
771 contains: function (obj) { // (Bounds) or (Point) -> Boolean
774 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
780 if (obj instanceof L.Bounds) {
787 return (min.x >= this.min.x) &&
788 (max.x <= this.max.x) &&
789 (min.y >= this.min.y) &&
790 (max.y <= this.max.y);
793 intersects: function (bounds) { // (Bounds) -> Boolean
794 bounds = L.bounds(bounds);
800 xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
801 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
803 return xIntersects && yIntersects;
806 isValid: function () {
807 return !!(this.min && this.max);
811 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
812 if (!a || a instanceof L.Bounds) {
815 return new L.Bounds(a, b);
820 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
823 L.Transformation = function (a, b, c, d) {
830 L.Transformation.prototype = {
831 transform: function (point, scale) { // (Point, Number) -> Point
832 return this._transform(point.clone(), scale);
835 // destructive transform (faster)
836 _transform: function (point, scale) {
838 point.x = scale * (this._a * point.x + this._b);
839 point.y = scale * (this._c * point.y + this._d);
843 untransform: function (point, scale) {
846 (point.x / scale - this._b) / this._a,
847 (point.y / scale - this._d) / this._c);
853 * L.DomUtil contains various utility functions for working with DOM.
858 return (typeof id === 'string' ? document.getElementById(id) : id);
861 getStyle: function (el, style) {
863 var value = el.style[style];
865 if (!value && el.currentStyle) {
866 value = el.currentStyle[style];
869 if ((!value || value === 'auto') && document.defaultView) {
870 var css = document.defaultView.getComputedStyle(el, null);
871 value = css ? css[style] : null;
874 return value === 'auto' ? null : value;
877 getViewportOffset: function (element) {
882 docBody = document.body,
883 docEl = document.documentElement,
888 top += el.offsetTop || 0;
889 left += el.offsetLeft || 0;
892 top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
893 left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
895 pos = L.DomUtil.getStyle(el, 'position');
897 if (el.offsetParent === docBody && pos === 'absolute') { break; }
899 if (pos === 'fixed') {
900 top += docBody.scrollTop || docEl.scrollTop || 0;
901 left += docBody.scrollLeft || docEl.scrollLeft || 0;
905 if (pos === 'relative' && !el.offsetLeft) {
906 var width = L.DomUtil.getStyle(el, 'width'),
907 maxWidth = L.DomUtil.getStyle(el, 'max-width'),
908 r = el.getBoundingClientRect();
910 if (width !== 'none' || maxWidth !== 'none') {
911 left += r.left + el.clientLeft;
914 //calculate full y offset since we're breaking out of the loop
915 top += r.top + (docBody.scrollTop || docEl.scrollTop || 0);
920 el = el.offsetParent;
927 if (el === docBody) { break; }
929 top -= el.scrollTop || 0;
930 left -= el.scrollLeft || 0;
932 // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
933 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
934 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
935 left += el.scrollWidth - el.clientWidth;
937 // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
938 // need to add it back in if it is visible; scrollbar is on the left as we are RTL
939 if (ie7 && L.DomUtil.getStyle(el, 'overflow-y') !== 'hidden' &&
940 L.DomUtil.getStyle(el, 'overflow') !== 'hidden') {
948 return new L.Point(left, top);
951 documentIsLtr: function () {
952 if (!L.DomUtil._docIsLtrCached) {
953 L.DomUtil._docIsLtrCached = true;
954 L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
956 return L.DomUtil._docIsLtr;
959 create: function (tagName, className, container) {
961 var el = document.createElement(tagName);
962 el.className = className;
965 container.appendChild(el);
971 hasClass: function (el, name) {
972 return (el.className.length > 0) &&
973 new RegExp('(^|\\s)' + name + '(\\s|$)').test(el.className);
976 addClass: function (el, name) {
977 if (!L.DomUtil.hasClass(el, name)) {
978 el.className += (el.className ? ' ' : '') + name;
982 removeClass: function (el, name) {
983 el.className = L.Util.trim((' ' + el.className + ' ').replace(' ' + name + ' ', ' '));
986 setOpacity: function (el, value) {
988 if ('opacity' in el.style) {
989 el.style.opacity = value;
991 } else if ('filter' in el.style) {
994 filterName = 'DXImageTransform.Microsoft.Alpha';
996 // filters collection throws an error if we try to retrieve a filter that doesn't exist
998 filter = el.filters.item(filterName);
1000 // don't set opacity to 1 if we haven't already set an opacity,
1001 // it isn't needed and breaks transparent pngs.
1002 if (value === 1) { return; }
1005 value = Math.round(value * 100);
1008 filter.Enabled = (value !== 100);
1009 filter.Opacity = value;
1011 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
1016 testProp: function (props) {
1018 var style = document.documentElement.style;
1020 for (var i = 0; i < props.length; i++) {
1021 if (props[i] in style) {
1028 getTranslateString: function (point) {
1029 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
1030 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
1031 // (same speed either way), Opera 12 doesn't support translate3d
1033 var is3d = L.Browser.webkit3d,
1034 open = 'translate' + (is3d ? '3d' : '') + '(',
1035 close = (is3d ? ',0' : '') + ')';
1037 return open + point.x + 'px,' + point.y + 'px' + close;
1040 getScaleString: function (scale, origin) {
1042 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
1043 scaleStr = ' scale(' + scale + ') ';
1045 return preTranslateStr + scaleStr;
1048 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
1050 // jshint camelcase: false
1051 el._leaflet_pos = point;
1053 if (!disable3D && L.Browser.any3d) {
1054 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
1056 // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
1057 if (L.Browser.mobileWebkit3d) {
1058 el.style.WebkitBackfaceVisibility = 'hidden';
1061 el.style.left = point.x + 'px';
1062 el.style.top = point.y + 'px';
1066 getPosition: function (el) {
1067 // this method is only used for elements previously positioned using setPosition,
1068 // so it's safe to cache the position for performance
1070 // jshint camelcase: false
1071 return el._leaflet_pos;
1076 // prefix style property names
1078 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
1079 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
1081 // webkitTransition comes first because some browser versions that drop vendor prefix don't do
1082 // the same for the transitionend event, in particular the Android 4.1 stock browser
1084 L.DomUtil.TRANSITION = L.DomUtil.testProp(
1085 ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
1087 L.DomUtil.TRANSITION_END =
1088 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
1089 L.DomUtil.TRANSITION + 'End' : 'transitionend';
1092 var userSelectProperty = L.DomUtil.testProp(
1093 ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
1095 L.extend(L.DomUtil, {
1096 disableTextSelection: function () {
1097 L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
1098 if (userSelectProperty) {
1099 var style = document.documentElement.style;
1100 this._userSelect = style[userSelectProperty];
1101 style[userSelectProperty] = 'none';
1105 enableTextSelection: function () {
1106 L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
1107 if (userSelectProperty) {
1108 document.documentElement.style[userSelectProperty] = this._userSelect;
1109 delete this._userSelect;
1113 disableImageDrag: function () {
1114 L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
1117 enableImageDrag: function () {
1118 L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
1125 * L.LatLng represents a geographical point with latitude and longitude coordinates.
1128 L.LatLng = function (rawLat, rawLng) { // (Number, Number)
1129 var lat = parseFloat(rawLat),
1130 lng = parseFloat(rawLng);
1132 if (isNaN(lat) || isNaN(lng)) {
1133 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
1140 L.extend(L.LatLng, {
1141 DEG_TO_RAD: Math.PI / 180,
1142 RAD_TO_DEG: 180 / Math.PI,
1143 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
1146 L.LatLng.prototype = {
1147 equals: function (obj) { // (LatLng) -> Boolean
1148 if (!obj) { return false; }
1150 obj = L.latLng(obj);
1152 var margin = Math.max(
1153 Math.abs(this.lat - obj.lat),
1154 Math.abs(this.lng - obj.lng));
1156 return margin <= L.LatLng.MAX_MARGIN;
1159 toString: function (precision) { // (Number) -> String
1161 L.Util.formatNum(this.lat, precision) + ', ' +
1162 L.Util.formatNum(this.lng, precision) + ')';
1165 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1166 // TODO move to projection code, LatLng shouldn't know about Earth
1167 distanceTo: function (other) { // (LatLng) -> Number
1168 other = L.latLng(other);
1170 var R = 6378137, // earth radius in meters
1171 d2r = L.LatLng.DEG_TO_RAD,
1172 dLat = (other.lat - this.lat) * d2r,
1173 dLon = (other.lng - this.lng) * d2r,
1174 lat1 = this.lat * d2r,
1175 lat2 = other.lat * d2r,
1176 sin1 = Math.sin(dLat / 2),
1177 sin2 = Math.sin(dLon / 2);
1179 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1181 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1184 wrap: function (a, b) { // (Number, Number) -> LatLng
1190 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1192 return new L.LatLng(this.lat, lng);
1196 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1197 if (a instanceof L.LatLng) {
1200 if (L.Util.isArray(a)) {
1201 return new L.LatLng(a[0], a[1]);
1203 if (a === undefined || a === null) {
1206 if (typeof a === 'object' && 'lat' in a) {
1207 return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
1209 return new L.LatLng(a, b);
1215 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1218 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1219 if (!southWest) { return; }
1221 var latlngs = northEast ? [southWest, northEast] : southWest;
1223 for (var i = 0, len = latlngs.length; i < len; i++) {
1224 this.extend(latlngs[i]);
1228 L.LatLngBounds.prototype = {
1229 // extend the bounds to contain the given point or bounds
1230 extend: function (obj) { // (LatLng) or (LatLngBounds)
1231 if (!obj) { return this; }
1233 if (typeof obj[0] === 'number' || typeof obj[0] === 'string' || obj instanceof L.LatLng) {
1234 obj = L.latLng(obj);
1236 obj = L.latLngBounds(obj);
1239 if (obj instanceof L.LatLng) {
1240 if (!this._southWest && !this._northEast) {
1241 this._southWest = new L.LatLng(obj.lat, obj.lng);
1242 this._northEast = new L.LatLng(obj.lat, obj.lng);
1244 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1245 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1247 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1248 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1250 } else if (obj instanceof L.LatLngBounds) {
1251 this.extend(obj._southWest);
1252 this.extend(obj._northEast);
1257 // extend the bounds by a percentage
1258 pad: function (bufferRatio) { // (Number) -> LatLngBounds
1259 var sw = this._southWest,
1260 ne = this._northEast,
1261 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1262 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1264 return new L.LatLngBounds(
1265 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1266 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1269 getCenter: function () { // -> LatLng
1270 return new L.LatLng(
1271 (this._southWest.lat + this._northEast.lat) / 2,
1272 (this._southWest.lng + this._northEast.lng) / 2);
1275 getSouthWest: function () {
1276 return this._southWest;
1279 getNorthEast: function () {
1280 return this._northEast;
1283 getNorthWest: function () {
1284 return new L.LatLng(this.getNorth(), this.getWest());
1287 getSouthEast: function () {
1288 return new L.LatLng(this.getSouth(), this.getEast());
1291 getWest: function () {
1292 return this._southWest.lng;
1295 getSouth: function () {
1296 return this._southWest.lat;
1299 getEast: function () {
1300 return this._northEast.lng;
1303 getNorth: function () {
1304 return this._northEast.lat;
1307 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1308 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1309 obj = L.latLng(obj);
1311 obj = L.latLngBounds(obj);
1314 var sw = this._southWest,
1315 ne = this._northEast,
1318 if (obj instanceof L.LatLngBounds) {
1319 sw2 = obj.getSouthWest();
1320 ne2 = obj.getNorthEast();
1325 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1326 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1329 intersects: function (bounds) { // (LatLngBounds)
1330 bounds = L.latLngBounds(bounds);
1332 var sw = this._southWest,
1333 ne = this._northEast,
1334 sw2 = bounds.getSouthWest(),
1335 ne2 = bounds.getNorthEast(),
1337 latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1338 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1340 return latIntersects && lngIntersects;
1343 toBBoxString: function () {
1344 return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
1347 equals: function (bounds) { // (LatLngBounds)
1348 if (!bounds) { return false; }
1350 bounds = L.latLngBounds(bounds);
1352 return this._southWest.equals(bounds.getSouthWest()) &&
1353 this._northEast.equals(bounds.getNorthEast());
1356 isValid: function () {
1357 return !!(this._southWest && this._northEast);
1361 //TODO International date line?
1363 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1364 if (!a || a instanceof L.LatLngBounds) {
1367 return new L.LatLngBounds(a, b);
1372 * L.Projection contains various geographical projections used by CRS classes.
1379 * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1382 L.Projection.SphericalMercator = {
1383 MAX_LATITUDE: 85.0511287798,
1385 project: function (latlng) { // (LatLng) -> Point
1386 var d = L.LatLng.DEG_TO_RAD,
1387 max = this.MAX_LATITUDE,
1388 lat = Math.max(Math.min(max, latlng.lat), -max),
1392 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1394 return new L.Point(x, y);
1397 unproject: function (point) { // (Point, Boolean) -> LatLng
1398 var d = L.LatLng.RAD_TO_DEG,
1400 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1402 return new L.LatLng(lat, lng);
1408 * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1411 L.Projection.LonLat = {
1412 project: function (latlng) {
1413 return new L.Point(latlng.lng, latlng.lat);
1416 unproject: function (point) {
1417 return new L.LatLng(point.y, point.x);
1423 * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1427 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1428 var projectedPoint = this.projection.project(latlng),
1429 scale = this.scale(zoom);
1431 return this.transformation._transform(projectedPoint, scale);
1434 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1435 var scale = this.scale(zoom),
1436 untransformedPoint = this.transformation.untransform(point, scale);
1438 return this.projection.unproject(untransformedPoint);
1441 project: function (latlng) {
1442 return this.projection.project(latlng);
1445 scale: function (zoom) {
1446 return 256 * Math.pow(2, zoom);
1452 * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1455 L.CRS.Simple = L.extend({}, L.CRS, {
1456 projection: L.Projection.LonLat,
1457 transformation: new L.Transformation(1, 0, -1, 0),
1459 scale: function (zoom) {
1460 return Math.pow(2, zoom);
1466 * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1467 * and is used by Leaflet by default.
1470 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1473 projection: L.Projection.SphericalMercator,
1474 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1476 project: function (latlng) { // (LatLng) -> Point
1477 var projectedPoint = this.projection.project(latlng),
1478 earthRadius = 6378137;
1479 return projectedPoint.multiplyBy(earthRadius);
1483 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1489 * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1492 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1495 projection: L.Projection.LonLat,
1496 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1501 * L.Map is the central class of the API - it is used to create a map.
1504 L.Map = L.Class.extend({
1506 includes: L.Mixin.Events,
1509 crs: L.CRS.EPSG3857,
1517 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1519 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1522 initialize: function (id, options) { // (HTMLElement or String, Object)
1523 options = L.setOptions(this, options);
1525 this._initContainer(id);
1529 if (options.maxBounds) {
1530 this.setMaxBounds(options.maxBounds);
1533 if (options.center && options.zoom !== undefined) {
1534 this.setView(L.latLng(options.center), options.zoom, {reset: true});
1537 this._handlers = [];
1540 this._zoomBoundLayers = {};
1541 this._tileLayersNum = 0;
1543 this.callInitHooks();
1545 this._addLayers(options.layers);
1549 // public methods that modify map state
1551 // replaced by animation-powered implementation in Map.PanAnimation.js
1552 setView: function (center, zoom) {
1553 this._resetView(L.latLng(center), this._limitZoom(zoom));
1557 setZoom: function (zoom, options) {
1558 return this.setView(this.getCenter(), zoom, {zoom: options});
1561 zoomIn: function (delta, options) {
1562 return this.setZoom(this._zoom + (delta || 1), options);
1565 zoomOut: function (delta, options) {
1566 return this.setZoom(this._zoom - (delta || 1), options);
1569 setZoomAround: function (latlng, zoom, options) {
1570 var scale = this.getZoomScale(zoom),
1571 viewHalf = this.getSize().divideBy(2),
1572 containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
1574 centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
1575 newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
1577 return this.setView(newCenter, zoom, {zoom: options});
1580 fitBounds: function (bounds, options) {
1582 options = options || {};
1583 bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
1585 var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
1586 paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
1588 zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
1589 paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
1591 swPoint = this.project(bounds.getSouthWest(), zoom),
1592 nePoint = this.project(bounds.getNorthEast(), zoom),
1593 center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
1595 return this.setView(center, zoom, options);
1598 fitWorld: function (options) {
1599 return this.fitBounds([[-90, -180], [90, 180]], options);
1602 panTo: function (center, options) { // (LatLng)
1603 return this.setView(center, this._zoom, {pan: options});
1606 panBy: function (offset) { // (Point)
1607 // replaced with animated panBy in Map.Animation.js
1608 this.fire('movestart');
1610 this._rawPanBy(L.point(offset));
1613 return this.fire('moveend');
1616 setMaxBounds: function (bounds, options) {
1617 bounds = L.latLngBounds(bounds);
1619 this.options.maxBounds = bounds;
1622 this._boundsMinZoom = null;
1623 this.off('moveend', this._panInsideMaxBounds, this);
1627 var minZoom = this.getBoundsZoom(bounds, true);
1629 this._boundsMinZoom = minZoom;
1632 if (this._zoom < minZoom) {
1633 this.setView(bounds.getCenter(), minZoom, options);
1635 this.panInsideBounds(bounds);
1639 this.on('moveend', this._panInsideMaxBounds, this);
1644 panInsideBounds: function (bounds) {
1645 bounds = L.latLngBounds(bounds);
1647 var viewBounds = this.getPixelBounds(),
1648 viewSw = viewBounds.getBottomLeft(),
1649 viewNe = viewBounds.getTopRight(),
1650 sw = this.project(bounds.getSouthWest()),
1651 ne = this.project(bounds.getNorthEast()),
1655 if (viewNe.y < ne.y) { // north
1656 dy = Math.ceil(ne.y - viewNe.y);
1658 if (viewNe.x > ne.x) { // east
1659 dx = Math.floor(ne.x - viewNe.x);
1661 if (viewSw.y > sw.y) { // south
1662 dy = Math.floor(sw.y - viewSw.y);
1664 if (viewSw.x < sw.x) { // west
1665 dx = Math.ceil(sw.x - viewSw.x);
1669 return this.panBy([dx, dy]);
1675 addLayer: function (layer) {
1676 // TODO method is too big, refactor
1678 var id = L.stamp(layer);
1680 if (this._layers[id]) { return this; }
1682 this._layers[id] = layer;
1684 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1685 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1686 this._zoomBoundLayers[id] = layer;
1687 this._updateZoomLevels();
1690 // TODO looks ugly, refactor!!!
1691 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1692 this._tileLayersNum++;
1693 this._tileLayersToLoad++;
1694 layer.on('load', this._onTileLayerLoad, this);
1698 this._layerAdd(layer);
1704 removeLayer: function (layer) {
1705 var id = L.stamp(layer);
1707 if (!this._layers[id]) { return; }
1710 layer.onRemove(this);
1713 delete this._layers[id];
1716 this.fire('layerremove', {layer: layer});
1719 if (this._zoomBoundLayers[id]) {
1720 delete this._zoomBoundLayers[id];
1721 this._updateZoomLevels();
1724 // TODO looks ugly, refactor
1725 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1726 this._tileLayersNum--;
1727 this._tileLayersToLoad--;
1728 layer.off('load', this._onTileLayerLoad, this);
1734 hasLayer: function (layer) {
1735 if (!layer) { return false; }
1737 return (L.stamp(layer) in this._layers);
1740 eachLayer: function (method, context) {
1741 for (var i in this._layers) {
1742 method.call(context, this._layers[i]);
1747 invalidateSize: function (options) {
1748 options = L.extend({
1751 }, options === true ? {animate: true} : options);
1753 var oldSize = this.getSize();
1754 this._sizeChanged = true;
1755 this._initialCenter = null;
1757 if (this.options.maxBounds) {
1758 this.setMaxBounds(this.options.maxBounds);
1761 if (!this._loaded) { return this; }
1763 var newSize = this.getSize(),
1764 offset = oldSize.subtract(newSize).divideBy(2).round();
1766 if (!offset.x && !offset.y) { return this; }
1768 if (options.animate && options.pan) {
1773 this._rawPanBy(offset);
1778 // make sure moveend is not fired too often on resize
1779 clearTimeout(this._sizeTimer);
1780 this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1783 return this.fire('resize', {
1789 // TODO handler.addTo
1790 addHandler: function (name, HandlerClass) {
1791 if (!HandlerClass) { return; }
1793 var handler = this[name] = new HandlerClass(this);
1795 this._handlers.push(handler);
1797 if (this.options[name]) {
1804 remove: function () {
1806 this.fire('unload');
1809 this._initEvents('off');
1811 delete this._container._leaflet;
1814 if (this._clearControlPos) {
1815 this._clearControlPos();
1818 this._clearHandlers();
1824 // public methods for getting map state
1826 getCenter: function () { // (Boolean) -> LatLng
1827 this._checkIfLoaded();
1829 if (this._initialCenter && !this._moved()) {
1830 return this._initialCenter;
1832 return this.layerPointToLatLng(this._getCenterLayerPoint());
1835 getZoom: function () {
1839 getBounds: function () {
1840 var bounds = this.getPixelBounds(),
1841 sw = this.unproject(bounds.getBottomLeft()),
1842 ne = this.unproject(bounds.getTopRight());
1844 return new L.LatLngBounds(sw, ne);
1847 getMinZoom: function () {
1848 var z1 = this._layersMinZoom === undefined ? -Infinity : this._layersMinZoom,
1849 z2 = this._boundsMinZoom === undefined ? -Infinity : this._boundsMinZoom;
1850 return this.options.minZoom === undefined ? Math.max(z1, z2) : this.options.minZoom;
1853 getMaxZoom: function () {
1854 return this.options.maxZoom === undefined ?
1855 (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
1856 this.options.maxZoom;
1859 getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1860 bounds = L.latLngBounds(bounds);
1862 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1863 maxZoom = this.getMaxZoom(),
1864 size = this.getSize(),
1866 nw = bounds.getNorthWest(),
1867 se = bounds.getSouthEast(),
1869 zoomNotFound = true,
1872 padding = L.point(padding || [0, 0]);
1876 boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1877 zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1879 } while (zoomNotFound && zoom <= maxZoom);
1881 if (zoomNotFound && inside) {
1885 return inside ? zoom : zoom - 1;
1888 getSize: function () {
1889 if (!this._size || this._sizeChanged) {
1890 this._size = new L.Point(
1891 this._container.clientWidth,
1892 this._container.clientHeight);
1894 this._sizeChanged = false;
1896 return this._size.clone();
1899 getPixelBounds: function () {
1900 var topLeftPoint = this._getTopLeftPoint();
1901 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1904 getPixelOrigin: function () {
1905 this._checkIfLoaded();
1906 return this._initialTopLeftPoint;
1909 getPanes: function () {
1913 getContainer: function () {
1914 return this._container;
1918 // TODO replace with universal implementation after refactoring projections
1920 getZoomScale: function (toZoom) {
1921 var crs = this.options.crs;
1922 return crs.scale(toZoom) / crs.scale(this._zoom);
1925 getScaleZoom: function (scale) {
1926 return this._zoom + (Math.log(scale) / Math.LN2);
1930 // conversion methods
1932 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1933 zoom = zoom === undefined ? this._zoom : zoom;
1934 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1937 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1938 zoom = zoom === undefined ? this._zoom : zoom;
1939 return this.options.crs.pointToLatLng(L.point(point), zoom);
1942 layerPointToLatLng: function (point) { // (Point)
1943 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1944 return this.unproject(projectedPoint);
1947 latLngToLayerPoint: function (latlng) { // (LatLng)
1948 var projectedPoint = this.project(L.latLng(latlng))._round();
1949 return projectedPoint._subtract(this.getPixelOrigin());
1952 containerPointToLayerPoint: function (point) { // (Point)
1953 return L.point(point).subtract(this._getMapPanePos());
1956 layerPointToContainerPoint: function (point) { // (Point)
1957 return L.point(point).add(this._getMapPanePos());
1960 containerPointToLatLng: function (point) {
1961 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1962 return this.layerPointToLatLng(layerPoint);
1965 latLngToContainerPoint: function (latlng) {
1966 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1969 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1970 return L.DomEvent.getMousePosition(e, this._container);
1973 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1974 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1977 mouseEventToLatLng: function (e) { // (MouseEvent)
1978 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1982 // map initialization methods
1984 _initContainer: function (id) {
1985 var container = this._container = L.DomUtil.get(id);
1988 throw new Error('Map container not found.');
1989 } else if (container._leaflet) {
1990 throw new Error('Map container is already initialized.');
1993 container._leaflet = true;
1996 _initLayout: function () {
1997 var container = this._container;
1999 L.DomUtil.addClass(container, 'leaflet-container' +
2000 (L.Browser.touch ? ' leaflet-touch' : '') +
2001 (L.Browser.retina ? ' leaflet-retina' : '') +
2002 (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
2004 var position = L.DomUtil.getStyle(container, 'position');
2006 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
2007 container.style.position = 'relative';
2012 if (this._initControlPos) {
2013 this._initControlPos();
2017 _initPanes: function () {
2018 var panes = this._panes = {};
2020 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2022 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2023 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2024 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2025 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2026 panes.markerPane = this._createPane('leaflet-marker-pane');
2027 panes.popupPane = this._createPane('leaflet-popup-pane');
2029 var zoomHide = ' leaflet-zoom-hide';
2031 if (!this.options.markerZoomAnimation) {
2032 L.DomUtil.addClass(panes.markerPane, zoomHide);
2033 L.DomUtil.addClass(panes.shadowPane, zoomHide);
2034 L.DomUtil.addClass(panes.popupPane, zoomHide);
2038 _createPane: function (className, container) {
2039 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2042 _clearPanes: function () {
2043 this._container.removeChild(this._mapPane);
2046 _addLayers: function (layers) {
2047 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2049 for (var i = 0, len = layers.length; i < len; i++) {
2050 this.addLayer(layers[i]);
2055 // private methods that modify map state
2057 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2059 var zoomChanged = (this._zoom !== zoom);
2061 if (!afterZoomAnim) {
2062 this.fire('movestart');
2065 this.fire('zoomstart');
2070 this._initialCenter = center;
2072 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2074 if (!preserveMapOffset) {
2075 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2077 this._initialTopLeftPoint._add(this._getMapPanePos());
2080 this._tileLayersToLoad = this._tileLayersNum;
2082 var loading = !this._loaded;
2083 this._loaded = true;
2087 this.eachLayer(this._layerAdd, this);
2090 this.fire('viewreset', {hard: !preserveMapOffset});
2094 if (zoomChanged || afterZoomAnim) {
2095 this.fire('zoomend');
2098 this.fire('moveend', {hard: !preserveMapOffset});
2101 _rawPanBy: function (offset) {
2102 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2105 _getZoomSpan: function () {
2106 return this.getMaxZoom() - this.getMinZoom();
2109 _updateZoomLevels: function () {
2112 maxZoom = -Infinity,
2113 oldZoomSpan = this._getZoomSpan();
2115 for (i in this._zoomBoundLayers) {
2116 var layer = this._zoomBoundLayers[i];
2117 if (!isNaN(layer.options.minZoom)) {
2118 minZoom = Math.min(minZoom, layer.options.minZoom);
2120 if (!isNaN(layer.options.maxZoom)) {
2121 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2125 if (i === undefined) { // we have no tilelayers
2126 this._layersMaxZoom = this._layersMinZoom = undefined;
2128 this._layersMaxZoom = maxZoom;
2129 this._layersMinZoom = minZoom;
2132 if (oldZoomSpan !== this._getZoomSpan()) {
2133 this.fire('zoomlevelschange');
2137 _panInsideMaxBounds: function () {
2138 this.panInsideBounds(this.options.maxBounds);
2141 _checkIfLoaded: function () {
2142 if (!this._loaded) {
2143 throw new Error('Set map center and zoom first.');
2149 _initEvents: function (onOff) {
2150 if (!L.DomEvent) { return; }
2152 onOff = onOff || 'on';
2154 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2156 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2157 'mouseleave', 'mousemove', 'contextmenu'],
2160 for (i = 0, len = events.length; i < len; i++) {
2161 L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2164 if (this.options.trackResize) {
2165 L.DomEvent[onOff](window, 'resize', this._onResize, this);
2169 _onResize: function () {
2170 L.Util.cancelAnimFrame(this._resizeRequest);
2171 this._resizeRequest = L.Util.requestAnimFrame(
2172 this.invalidateSize, this, false, this._container);
2175 _onMouseClick: function (e) {
2176 if (!this._loaded || (!e._simulated && this.dragging && this.dragging.moved()) ||
2177 L.DomEvent._skipped(e)) { return; }
2179 this.fire('preclick');
2180 this._fireMouseEvent(e);
2183 _fireMouseEvent: function (e) {
2184 if (!this._loaded || L.DomEvent._skipped(e)) { return; }
2188 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2190 if (!this.hasEventListeners(type)) { return; }
2192 if (type === 'contextmenu') {
2193 L.DomEvent.preventDefault(e);
2196 var containerPoint = this.mouseEventToContainerPoint(e),
2197 layerPoint = this.containerPointToLayerPoint(containerPoint),
2198 latlng = this.layerPointToLatLng(layerPoint);
2202 layerPoint: layerPoint,
2203 containerPoint: containerPoint,
2208 _onTileLayerLoad: function () {
2209 this._tileLayersToLoad--;
2210 if (this._tileLayersNum && !this._tileLayersToLoad) {
2211 this.fire('tilelayersload');
2215 _clearHandlers: function () {
2216 for (var i = 0, len = this._handlers.length; i < len; i++) {
2217 this._handlers[i].disable();
2221 whenReady: function (callback, context) {
2223 callback.call(context || this, this);
2225 this.on('load', callback, context);
2230 _layerAdd: function (layer) {
2232 this.fire('layeradd', {layer: layer});
2236 // private methods for getting map state
2238 _getMapPanePos: function () {
2239 return L.DomUtil.getPosition(this._mapPane);
2242 _moved: function () {
2243 var pos = this._getMapPanePos();
2244 return pos && !pos.equals([0, 0]);
2247 _getTopLeftPoint: function () {
2248 return this.getPixelOrigin().subtract(this._getMapPanePos());
2251 _getNewTopLeftPoint: function (center, zoom) {
2252 var viewHalf = this.getSize()._divideBy(2);
2253 // TODO round on display, not calculation to increase precision?
2254 return this.project(center, zoom)._subtract(viewHalf)._round();
2257 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2258 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2259 return this.project(latlng, newZoom)._subtract(topLeft);
2262 // layer point of the current center
2263 _getCenterLayerPoint: function () {
2264 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2267 // offset of the specified place to the current center in pixels
2268 _getCenterOffset: function (latlng) {
2269 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2272 _limitZoom: function (zoom) {
2273 var min = this.getMinZoom(),
2274 max = this.getMaxZoom();
2276 return Math.max(min, Math.min(max, zoom));
2280 L.map = function (id, options) {
2281 return new L.Map(id, options);
2286 * Mercator projection that takes into account that the Earth is not a perfect sphere.
2287 * Less popular than spherical mercator; used by projections like EPSG:3395.
2290 L.Projection.Mercator = {
2291 MAX_LATITUDE: 85.0840591556,
2293 R_MINOR: 6356752.314245179,
2296 project: function (latlng) { // (LatLng) -> Point
2297 var d = L.LatLng.DEG_TO_RAD,
2298 max = this.MAX_LATITUDE,
2299 lat = Math.max(Math.min(max, latlng.lat), -max),
2302 x = latlng.lng * d * r,
2305 eccent = Math.sqrt(1.0 - tmp * tmp),
2306 con = eccent * Math.sin(y);
2308 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2310 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2311 y = -r * Math.log(ts);
2313 return new L.Point(x, y);
2316 unproject: function (point) { // (Point, Boolean) -> LatLng
2317 var d = L.LatLng.RAD_TO_DEG,
2320 lng = point.x * d / r,
2322 eccent = Math.sqrt(1 - (tmp * tmp)),
2323 ts = Math.exp(- point.y / r),
2324 phi = (Math.PI / 2) - 2 * Math.atan(ts),
2331 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2332 con = eccent * Math.sin(phi);
2333 dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2334 Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2338 return new L.LatLng(phi * d, lng);
2344 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2347 projection: L.Projection.Mercator,
2349 transformation: (function () {
2350 var m = L.Projection.Mercator,
2354 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
2360 * L.TileLayer is used for standard xyz-numbered tile layers.
2363 L.TileLayer = L.Class.extend({
2364 includes: L.Mixin.Events,
2375 /* (undefined works too)
2378 continuousWorld: false,
2381 detectRetina: false,
2385 unloadInvisibleTiles: L.Browser.mobile,
2386 updateWhenIdle: L.Browser.mobile
2389 initialize: function (url, options) {
2390 options = L.setOptions(this, options);
2392 // detecting retina displays, adjusting tileSize and zoom levels
2393 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2395 options.tileSize = Math.floor(options.tileSize / 2);
2396 options.zoomOffset++;
2398 if (options.minZoom > 0) {
2401 this.options.maxZoom--;
2404 if (options.bounds) {
2405 options.bounds = L.latLngBounds(options.bounds);
2410 var subdomains = this.options.subdomains;
2412 if (typeof subdomains === 'string') {
2413 this.options.subdomains = subdomains.split('');
2417 onAdd: function (map) {
2419 this._animated = map._zoomAnimated;
2421 // create a container div for tiles
2422 this._initContainer();
2424 // create an image to clone for tiles
2425 this._createTileProto();
2429 'viewreset': this._reset,
2430 'moveend': this._update
2433 if (this._animated) {
2435 'zoomanim': this._animateZoom,
2436 'zoomend': this._endZoomAnim
2440 if (!this.options.updateWhenIdle) {
2441 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2442 map.on('move', this._limitedUpdate, this);
2449 addTo: function (map) {
2454 onRemove: function (map) {
2455 this._container.parentNode.removeChild(this._container);
2458 'viewreset': this._reset,
2459 'moveend': this._update
2462 if (this._animated) {
2464 'zoomanim': this._animateZoom,
2465 'zoomend': this._endZoomAnim
2469 if (!this.options.updateWhenIdle) {
2470 map.off('move', this._limitedUpdate, this);
2473 this._container = null;
2477 bringToFront: function () {
2478 var pane = this._map._panes.tilePane;
2480 if (this._container) {
2481 pane.appendChild(this._container);
2482 this._setAutoZIndex(pane, Math.max);
2488 bringToBack: function () {
2489 var pane = this._map._panes.tilePane;
2491 if (this._container) {
2492 pane.insertBefore(this._container, pane.firstChild);
2493 this._setAutoZIndex(pane, Math.min);
2499 getAttribution: function () {
2500 return this.options.attribution;
2503 getContainer: function () {
2504 return this._container;
2507 setOpacity: function (opacity) {
2508 this.options.opacity = opacity;
2511 this._updateOpacity();
2517 setZIndex: function (zIndex) {
2518 this.options.zIndex = zIndex;
2519 this._updateZIndex();
2524 setUrl: function (url, noRedraw) {
2534 redraw: function () {
2536 this._reset({hard: true});
2542 _updateZIndex: function () {
2543 if (this._container && this.options.zIndex !== undefined) {
2544 this._container.style.zIndex = this.options.zIndex;
2548 _setAutoZIndex: function (pane, compare) {
2550 var layers = pane.children,
2551 edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2554 for (i = 0, len = layers.length; i < len; i++) {
2556 if (layers[i] !== this._container) {
2557 zIndex = parseInt(layers[i].style.zIndex, 10);
2559 if (!isNaN(zIndex)) {
2560 edgeZIndex = compare(edgeZIndex, zIndex);
2565 this.options.zIndex = this._container.style.zIndex =
2566 (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2569 _updateOpacity: function () {
2571 tiles = this._tiles;
2573 if (L.Browser.ielt9) {
2575 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2578 L.DomUtil.setOpacity(this._container, this.options.opacity);
2582 _initContainer: function () {
2583 var tilePane = this._map._panes.tilePane;
2585 if (!this._container) {
2586 this._container = L.DomUtil.create('div', 'leaflet-layer');
2588 this._updateZIndex();
2590 if (this._animated) {
2591 var className = 'leaflet-tile-container leaflet-zoom-animated';
2593 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2594 this._tileContainer = L.DomUtil.create('div', className, this._container);
2597 this._tileContainer = this._container;
2600 tilePane.appendChild(this._container);
2602 if (this.options.opacity < 1) {
2603 this._updateOpacity();
2608 _reset: function (e) {
2609 for (var key in this._tiles) {
2610 this.fire('tileunload', {tile: this._tiles[key]});
2614 this._tilesToLoad = 0;
2616 if (this.options.reuseTiles) {
2617 this._unusedTiles = [];
2620 this._tileContainer.innerHTML = '';
2622 if (this._animated && e && e.hard) {
2623 this._clearBgBuffer();
2626 this._initContainer();
2629 _update: function () {
2631 if (!this._map) { return; }
2633 var bounds = this._map.getPixelBounds(),
2634 zoom = this._map.getZoom(),
2635 tileSize = this.options.tileSize;
2637 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2641 var tileBounds = L.bounds(
2642 bounds.min.divideBy(tileSize)._floor(),
2643 bounds.max.divideBy(tileSize)._floor());
2645 this._addTilesFromCenterOut(tileBounds);
2647 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2648 this._removeOtherTiles(tileBounds);
2652 _addTilesFromCenterOut: function (bounds) {
2654 center = bounds.getCenter();
2658 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2659 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2660 point = new L.Point(i, j);
2662 if (this._tileShouldBeLoaded(point)) {
2668 var tilesToLoad = queue.length;
2670 if (tilesToLoad === 0) { return; }
2672 // load tiles in order of their distance to center
2673 queue.sort(function (a, b) {
2674 return a.distanceTo(center) - b.distanceTo(center);
2677 var fragment = document.createDocumentFragment();
2679 // if its the first batch of tiles to load
2680 if (!this._tilesToLoad) {
2681 this.fire('loading');
2684 this._tilesToLoad += tilesToLoad;
2686 for (i = 0; i < tilesToLoad; i++) {
2687 this._addTile(queue[i], fragment);
2690 this._tileContainer.appendChild(fragment);
2693 _tileShouldBeLoaded: function (tilePoint) {
2694 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2695 return false; // already loaded
2698 var options = this.options;
2700 if (!options.continuousWorld) {
2701 var limit = this._getWrapTileNum();
2703 // don't load if exceeds world bounds
2704 if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit)) ||
2705 tilePoint.y < 0 || tilePoint.y >= limit) { return false; }
2708 if (options.bounds) {
2709 var tileSize = options.tileSize,
2710 nwPoint = tilePoint.multiplyBy(tileSize),
2711 sePoint = nwPoint.add([tileSize, tileSize]),
2712 nw = this._map.unproject(nwPoint),
2713 se = this._map.unproject(sePoint);
2715 // TODO temporary hack, will be removed after refactoring projections
2716 // https://github.com/Leaflet/Leaflet/issues/1618
2717 if (!options.continuousWorld && !options.noWrap) {
2722 if (!options.bounds.intersects([nw, se])) { return false; }
2728 _removeOtherTiles: function (bounds) {
2729 var kArr, x, y, key;
2731 for (key in this._tiles) {
2732 kArr = key.split(':');
2733 x = parseInt(kArr[0], 10);
2734 y = parseInt(kArr[1], 10);
2736 // remove tile if it's out of bounds
2737 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2738 this._removeTile(key);
2743 _removeTile: function (key) {
2744 var tile = this._tiles[key];
2746 this.fire('tileunload', {tile: tile, url: tile.src});
2748 if (this.options.reuseTiles) {
2749 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2750 this._unusedTiles.push(tile);
2752 } else if (tile.parentNode === this._tileContainer) {
2753 this._tileContainer.removeChild(tile);
2756 // for https://github.com/CloudMade/Leaflet/issues/137
2757 if (!L.Browser.android) {
2759 tile.src = L.Util.emptyImageUrl;
2762 delete this._tiles[key];
2765 _addTile: function (tilePoint, container) {
2766 var tilePos = this._getTilePos(tilePoint);
2768 // get unused tile - or create a new tile
2769 var tile = this._getTile();
2772 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2773 Android 4 browser has display issues with top/left and requires transform instead
2774 Android 2 browser requires top/left or tiles disappear on load or first drag
2775 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2776 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2778 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2780 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2782 this._loadTile(tile, tilePoint);
2784 if (tile.parentNode !== this._tileContainer) {
2785 container.appendChild(tile);
2789 _getZoomForUrl: function () {
2791 var options = this.options,
2792 zoom = this._map.getZoom();
2794 if (options.zoomReverse) {
2795 zoom = options.maxZoom - zoom;
2798 return zoom + options.zoomOffset;
2801 _getTilePos: function (tilePoint) {
2802 var origin = this._map.getPixelOrigin(),
2803 tileSize = this.options.tileSize;
2805 return tilePoint.multiplyBy(tileSize).subtract(origin);
2808 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2810 getTileUrl: function (tilePoint) {
2811 return L.Util.template(this._url, L.extend({
2812 s: this._getSubdomain(tilePoint),
2819 _getWrapTileNum: function () {
2820 // TODO refactor, limit is not valid for non-standard projections
2821 return Math.pow(2, this._getZoomForUrl());
2824 _adjustTilePoint: function (tilePoint) {
2826 var limit = this._getWrapTileNum();
2828 // wrap tile coordinates
2829 if (!this.options.continuousWorld && !this.options.noWrap) {
2830 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2833 if (this.options.tms) {
2834 tilePoint.y = limit - tilePoint.y - 1;
2837 tilePoint.z = this._getZoomForUrl();
2840 _getSubdomain: function (tilePoint) {
2841 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2842 return this.options.subdomains[index];
2845 _createTileProto: function () {
2846 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2847 img.style.width = img.style.height = this.options.tileSize + 'px';
2848 img.galleryimg = 'no';
2851 _getTile: function () {
2852 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2853 var tile = this._unusedTiles.pop();
2854 this._resetTile(tile);
2857 return this._createTile();
2860 // Override if data stored on a tile needs to be cleaned up before reuse
2861 _resetTile: function (/*tile*/) {},
2863 _createTile: function () {
2864 var tile = this._tileImg.cloneNode(false);
2865 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2867 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2868 L.DomUtil.setOpacity(tile, this.options.opacity);
2873 _loadTile: function (tile, tilePoint) {
2875 tile.onload = this._tileOnLoad;
2876 tile.onerror = this._tileOnError;
2878 this._adjustTilePoint(tilePoint);
2879 tile.src = this.getTileUrl(tilePoint);
2882 _tileLoaded: function () {
2883 this._tilesToLoad--;
2884 if (!this._tilesToLoad) {
2887 if (this._animated) {
2888 // clear scaled tiles after all new tiles are loaded (for performance)
2889 clearTimeout(this._clearBgBufferTimer);
2890 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2895 _tileOnLoad: function () {
2896 var layer = this._layer;
2898 //Only if we are loading an actual image
2899 if (this.src !== L.Util.emptyImageUrl) {
2900 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2902 layer.fire('tileload', {
2908 layer._tileLoaded();
2911 _tileOnError: function () {
2912 var layer = this._layer;
2914 layer.fire('tileerror', {
2919 var newUrl = layer.options.errorTileUrl;
2924 layer._tileLoaded();
2928 L.tileLayer = function (url, options) {
2929 return new L.TileLayer(url, options);
2934 * L.TileLayer.WMS is used for putting WMS tile layers on the map.
2937 L.TileLayer.WMS = L.TileLayer.extend({
2945 format: 'image/jpeg',
2949 initialize: function (url, options) { // (String, Object)
2953 var wmsParams = L.extend({}, this.defaultWmsParams),
2954 tileSize = options.tileSize || this.options.tileSize;
2956 if (options.detectRetina && L.Browser.retina) {
2957 wmsParams.width = wmsParams.height = tileSize * 2;
2959 wmsParams.width = wmsParams.height = tileSize;
2962 for (var i in options) {
2963 // all keys that are not TileLayer options go to WMS params
2964 if (!this.options.hasOwnProperty(i) && i !== 'crs') {
2965 wmsParams[i] = options[i];
2969 this.wmsParams = wmsParams;
2971 L.setOptions(this, options);
2974 onAdd: function (map) {
2976 this._crs = this.options.crs || map.options.crs;
2978 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2979 this.wmsParams[projectionKey] = this._crs.code;
2981 L.TileLayer.prototype.onAdd.call(this, map);
2984 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
2986 var map = this._map,
2987 tileSize = this.options.tileSize,
2989 nwPoint = tilePoint.multiplyBy(tileSize),
2990 sePoint = nwPoint.add([tileSize, tileSize]),
2992 nw = this._crs.project(map.unproject(nwPoint, zoom)),
2993 se = this._crs.project(map.unproject(sePoint, zoom)),
2995 bbox = [nw.x, se.y, se.x, nw.y].join(','),
2997 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
2999 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
3002 setParams: function (params, noRedraw) {
3004 L.extend(this.wmsParams, params);
3014 L.tileLayer.wms = function (url, options) {
3015 return new L.TileLayer.WMS(url, options);
3020 * L.TileLayer.Canvas is a class that you can use as a base for creating
3021 * dynamically drawn Canvas-based tile layers.
3024 L.TileLayer.Canvas = L.TileLayer.extend({
3029 initialize: function (options) {
3030 L.setOptions(this, options);
3033 redraw: function () {
3035 this._reset({hard: true});
3039 for (var i in this._tiles) {
3040 this._redrawTile(this._tiles[i]);
3045 _redrawTile: function (tile) {
3046 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3049 _createTileProto: function () {
3050 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
3051 proto.width = proto.height = this.options.tileSize;
3054 _createTile: function () {
3055 var tile = this._canvasProto.cloneNode(false);
3056 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3060 _loadTile: function (tile, tilePoint) {
3062 tile._tilePoint = tilePoint;
3064 this._redrawTile(tile);
3066 if (!this.options.async) {
3067 this.tileDrawn(tile);
3071 drawTile: function (/*tile, tilePoint*/) {
3072 // override with rendering code
3075 tileDrawn: function (tile) {
3076 this._tileOnLoad.call(tile);
3081 L.tileLayer.canvas = function (options) {
3082 return new L.TileLayer.Canvas(options);
3087 * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3090 L.ImageOverlay = L.Class.extend({
3091 includes: L.Mixin.Events,
3097 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3099 this._bounds = L.latLngBounds(bounds);
3101 L.setOptions(this, options);
3104 onAdd: function (map) {
3111 map._panes.overlayPane.appendChild(this._image);
3113 map.on('viewreset', this._reset, this);
3115 if (map.options.zoomAnimation && L.Browser.any3d) {
3116 map.on('zoomanim', this._animateZoom, this);
3122 onRemove: function (map) {
3123 map.getPanes().overlayPane.removeChild(this._image);
3125 map.off('viewreset', this._reset, this);
3127 if (map.options.zoomAnimation) {
3128 map.off('zoomanim', this._animateZoom, this);
3132 addTo: function (map) {
3137 setOpacity: function (opacity) {
3138 this.options.opacity = opacity;
3139 this._updateOpacity();
3143 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3144 bringToFront: function () {
3146 this._map._panes.overlayPane.appendChild(this._image);
3151 bringToBack: function () {
3152 var pane = this._map._panes.overlayPane;
3154 pane.insertBefore(this._image, pane.firstChild);
3159 _initImage: function () {
3160 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3162 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3163 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3165 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3168 this._updateOpacity();
3170 //TODO createImage util method to remove duplication
3171 L.extend(this._image, {
3173 onselectstart: L.Util.falseFn,
3174 onmousemove: L.Util.falseFn,
3175 onload: L.bind(this._onImageLoad, this),
3180 _animateZoom: function (e) {
3181 var map = this._map,
3182 image = this._image,
3183 scale = map.getZoomScale(e.zoom),
3184 nw = this._bounds.getNorthWest(),
3185 se = this._bounds.getSouthEast(),
3187 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3188 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3189 origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3191 image.style[L.DomUtil.TRANSFORM] =
3192 L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3195 _reset: function () {
3196 var image = this._image,
3197 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3198 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3200 L.DomUtil.setPosition(image, topLeft);
3202 image.style.width = size.x + 'px';
3203 image.style.height = size.y + 'px';
3206 _onImageLoad: function () {
3210 _updateOpacity: function () {
3211 L.DomUtil.setOpacity(this._image, this.options.opacity);
3215 L.imageOverlay = function (url, bounds, options) {
3216 return new L.ImageOverlay(url, bounds, options);
3221 * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3224 L.Icon = L.Class.extend({
3227 iconUrl: (String) (required)
3228 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3229 iconSize: (Point) (can be set through CSS)
3230 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3231 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3232 shadowUrl: (String) (no shadow by default)
3233 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3235 shadowAnchor: (Point)
3240 initialize: function (options) {
3241 L.setOptions(this, options);
3244 createIcon: function (oldIcon) {
3245 return this._createIcon('icon', oldIcon);
3248 createShadow: function (oldIcon) {
3249 return this._createIcon('shadow', oldIcon);
3252 _createIcon: function (name, oldIcon) {
3253 var src = this._getIconUrl(name);
3256 if (name === 'icon') {
3257 throw new Error('iconUrl not set in Icon options (see the docs).');
3263 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3264 img = this._createImg(src);
3266 img = this._createImg(src, oldIcon);
3268 this._setIconStyles(img, name);
3273 _setIconStyles: function (img, name) {
3274 var options = this.options,
3275 size = L.point(options[name + 'Size']),
3278 if (name === 'shadow') {
3279 anchor = L.point(options.shadowAnchor || options.iconAnchor);
3281 anchor = L.point(options.iconAnchor);
3284 if (!anchor && size) {
3285 anchor = size.divideBy(2, true);
3288 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3291 img.style.marginLeft = (-anchor.x) + 'px';
3292 img.style.marginTop = (-anchor.y) + 'px';
3296 img.style.width = size.x + 'px';
3297 img.style.height = size.y + 'px';
3301 _createImg: function (src, el) {
3303 if (!L.Browser.ie6) {
3305 el = document.createElement('img');
3310 el = document.createElement('div');
3313 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
3318 _getIconUrl: function (name) {
3319 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3320 return this.options[name + 'RetinaUrl'];
3322 return this.options[name + 'Url'];
3326 L.icon = function (options) {
3327 return new L.Icon(options);
3332 * L.Icon.Default is the blue marker icon used by default in Leaflet.
3335 L.Icon.Default = L.Icon.extend({
3339 iconAnchor: [12, 41],
3340 popupAnchor: [1, -34],
3342 shadowSize: [41, 41]
3345 _getIconUrl: function (name) {
3346 var key = name + 'Url';
3348 if (this.options[key]) {
3349 return this.options[key];
3352 if (L.Browser.retina && name === 'icon') {
3356 var path = L.Icon.Default.imagePath;
3359 throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3362 return path + '/marker-' + name + '.png';
3366 L.Icon.Default.imagePath = (function () {
3367 var scripts = document.getElementsByTagName('script'),
3368 leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3370 var i, len, src, matches, path;
3372 for (i = 0, len = scripts.length; i < len; i++) {
3373 src = scripts[i].src;
3374 matches = src.match(leafletRe);
3377 path = src.split(leafletRe)[0];
3378 return (path ? path + '/' : '') + 'images';
3385 * L.Marker is used to display clickable/draggable icons on the map.
3388 L.Marker = L.Class.extend({
3390 includes: L.Mixin.Events,
3393 icon: new L.Icon.Default(),
3404 initialize: function (latlng, options) {
3405 L.setOptions(this, options);
3406 this._latlng = L.latLng(latlng);
3409 onAdd: function (map) {
3412 map.on('viewreset', this.update, this);
3417 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3418 map.on('zoomanim', this._animateZoom, this);
3422 addTo: function (map) {
3427 onRemove: function (map) {
3428 if (this.dragging) {
3429 this.dragging.disable();
3433 this._removeShadow();
3435 this.fire('remove');
3438 'viewreset': this.update,
3439 'zoomanim': this._animateZoom
3445 getLatLng: function () {
3446 return this._latlng;
3449 setLatLng: function (latlng) {
3450 this._latlng = L.latLng(latlng);
3454 return this.fire('move', { latlng: this._latlng });
3457 setZIndexOffset: function (offset) {
3458 this.options.zIndexOffset = offset;
3464 setIcon: function (icon) {
3466 this.options.icon = icon;
3476 update: function () {
3478 var pos = this._map.latLngToLayerPoint(this._latlng).round();
3485 _initIcon: function () {
3486 var options = this.options,
3488 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3489 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3491 var icon = options.icon.createIcon(this._icon),
3494 // if we're not reusing the icon, remove the old one and init new one
3495 if (icon !== this._icon) {
3501 if (options.title) {
3502 icon.title = options.title;
3506 L.DomUtil.addClass(icon, classToAdd);
3508 if (options.keyboard) {
3509 icon.tabIndex = '0';
3514 this._initInteraction();
3516 if (options.riseOnHover) {
3518 .on(icon, 'mouseover', this._bringToFront, this)
3519 .on(icon, 'mouseout', this._resetZIndex, this);
3522 var newShadow = options.icon.createShadow(this._shadow),
3525 if (newShadow !== this._shadow) {
3526 this._removeShadow();
3531 L.DomUtil.addClass(newShadow, classToAdd);
3533 this._shadow = newShadow;
3536 if (options.opacity < 1) {
3537 this._updateOpacity();
3541 var panes = this._map._panes;
3544 panes.markerPane.appendChild(this._icon);
3547 if (newShadow && addShadow) {
3548 panes.shadowPane.appendChild(this._shadow);
3552 _removeIcon: function () {
3553 if (this.options.riseOnHover) {
3555 .off(this._icon, 'mouseover', this._bringToFront)
3556 .off(this._icon, 'mouseout', this._resetZIndex);
3559 this._map._panes.markerPane.removeChild(this._icon);
3564 _removeShadow: function () {
3566 this._map._panes.shadowPane.removeChild(this._shadow);
3568 this._shadow = null;
3571 _setPos: function (pos) {
3572 L.DomUtil.setPosition(this._icon, pos);
3575 L.DomUtil.setPosition(this._shadow, pos);
3578 this._zIndex = pos.y + this.options.zIndexOffset;
3580 this._resetZIndex();
3583 _updateZIndex: function (offset) {
3584 this._icon.style.zIndex = this._zIndex + offset;
3587 _animateZoom: function (opt) {
3588 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3593 _initInteraction: function () {
3595 if (!this.options.clickable) { return; }
3597 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3599 var icon = this._icon,
3600 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3602 L.DomUtil.addClass(icon, 'leaflet-clickable');
3603 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3604 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3606 for (var i = 0; i < events.length; i++) {
3607 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3610 if (L.Handler.MarkerDrag) {
3611 this.dragging = new L.Handler.MarkerDrag(this);
3613 if (this.options.draggable) {
3614 this.dragging.enable();
3619 _onMouseClick: function (e) {
3620 var wasDragged = this.dragging && this.dragging.moved();
3622 if (this.hasEventListeners(e.type) || wasDragged) {
3623 L.DomEvent.stopPropagation(e);
3626 if (wasDragged) { return; }
3628 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3632 latlng: this._latlng
3636 _onKeyPress: function (e) {
3637 if (e.keyCode === 13) {
3638 this.fire('click', {
3640 latlng: this._latlng
3645 _fireMouseEvent: function (e) {
3649 latlng: this._latlng
3652 // TODO proper custom event propagation
3653 // this line will always be called if marker is in a FeatureGroup
3654 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3655 L.DomEvent.preventDefault(e);
3657 if (e.type !== 'mousedown') {
3658 L.DomEvent.stopPropagation(e);
3660 L.DomEvent.preventDefault(e);
3664 setOpacity: function (opacity) {
3665 this.options.opacity = opacity;
3667 this._updateOpacity();
3673 _updateOpacity: function () {
3674 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3676 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3680 _bringToFront: function () {
3681 this._updateZIndex(this.options.riseOffset);
3684 _resetZIndex: function () {
3685 this._updateZIndex(0);
3689 L.marker = function (latlng, options) {
3690 return new L.Marker(latlng, options);
3695 * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3696 * to use with L.Marker.
3699 L.DivIcon = L.Icon.extend({
3701 iconSize: [12, 12], // also can be set through CSS
3704 popupAnchor: (Point)
3708 className: 'leaflet-div-icon',
3712 createIcon: function (oldIcon) {
3713 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3714 options = this.options;
3716 if (options.html !== false) {
3717 div.innerHTML = options.html;
3722 if (options.bgPos) {
3723 div.style.backgroundPosition =
3724 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3727 this._setIconStyles(div, 'icon');
3731 createShadow: function () {
3736 L.divIcon = function (options) {
3737 return new L.DivIcon(options);
3742 * L.Popup is used for displaying popups on the map.
3745 L.Map.mergeOptions({
3746 closePopupOnClick: true
3749 L.Popup = L.Class.extend({
3750 includes: L.Mixin.Events,
3759 autoPanPadding: [5, 5],
3765 initialize: function (options, source) {
3766 L.setOptions(this, options);
3768 this._source = source;
3769 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3770 this._isOpen = false;
3773 onAdd: function (map) {
3776 if (!this._container) {
3779 this._updateContent();
3781 var animFade = map.options.fadeAnimation;
3784 L.DomUtil.setOpacity(this._container, 0);
3786 map._panes.popupPane.appendChild(this._container);
3788 map.on(this._getEvents(), this);
3793 L.DomUtil.setOpacity(this._container, 1);
3798 map.fire('popupopen', {popup: this});
3801 this._source.fire('popupopen', {popup: this});
3805 addTo: function (map) {
3810 openOn: function (map) {
3811 map.openPopup(this);
3815 onRemove: function (map) {
3816 map._panes.popupPane.removeChild(this._container);
3818 L.Util.falseFn(this._container.offsetWidth); // force reflow
3820 map.off(this._getEvents(), this);
3822 if (map.options.fadeAnimation) {
3823 L.DomUtil.setOpacity(this._container, 0);
3830 map.fire('popupclose', {popup: this});
3833 this._source.fire('popupclose', {popup: this});
3837 setLatLng: function (latlng) {
3838 this._latlng = L.latLng(latlng);
3843 setContent: function (content) {
3844 this._content = content;
3849 _getEvents: function () {
3851 viewreset: this._updatePosition
3854 if (this._animated) {
3855 events.zoomanim = this._zoomAnimation;
3857 if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
3858 events.preclick = this._close;
3860 if (this.options.keepInView) {
3861 events.moveend = this._adjustPan;
3867 _close: function () {
3869 this._map.closePopup(this);
3873 _initLayout: function () {
3874 var prefix = 'leaflet-popup',
3875 containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
3876 (this._animated ? 'animated' : 'hide'),
3877 container = this._container = L.DomUtil.create('div', containerClass),
3880 if (this.options.closeButton) {
3881 closeButton = this._closeButton =
3882 L.DomUtil.create('a', prefix + '-close-button', container);
3883 closeButton.href = '#close';
3884 closeButton.innerHTML = '×';
3885 L.DomEvent.disableClickPropagation(closeButton);
3887 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3890 var wrapper = this._wrapper =
3891 L.DomUtil.create('div', prefix + '-content-wrapper', container);
3892 L.DomEvent.disableClickPropagation(wrapper);
3894 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3895 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
3896 L.DomEvent.on(this._contentNode, 'MozMousePixelScroll', L.DomEvent.stopPropagation);
3897 L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
3898 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3899 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3902 _update: function () {
3903 if (!this._map) { return; }
3905 this._container.style.visibility = 'hidden';
3907 this._updateContent();
3908 this._updateLayout();
3909 this._updatePosition();
3911 this._container.style.visibility = '';
3916 _updateContent: function () {
3917 if (!this._content) { return; }
3919 if (typeof this._content === 'string') {
3920 this._contentNode.innerHTML = this._content;
3922 while (this._contentNode.hasChildNodes()) {
3923 this._contentNode.removeChild(this._contentNode.firstChild);
3925 this._contentNode.appendChild(this._content);
3927 this.fire('contentupdate');
3930 _updateLayout: function () {
3931 var container = this._contentNode,
3932 style = container.style;
3935 style.whiteSpace = 'nowrap';
3937 var width = container.offsetWidth;
3938 width = Math.min(width, this.options.maxWidth);
3939 width = Math.max(width, this.options.minWidth);
3941 style.width = (width + 1) + 'px';
3942 style.whiteSpace = '';
3946 var height = container.offsetHeight,
3947 maxHeight = this.options.maxHeight,
3948 scrolledClass = 'leaflet-popup-scrolled';
3950 if (maxHeight && height > maxHeight) {
3951 style.height = maxHeight + 'px';
3952 L.DomUtil.addClass(container, scrolledClass);
3954 L.DomUtil.removeClass(container, scrolledClass);
3957 this._containerWidth = this._container.offsetWidth;
3960 _updatePosition: function () {
3961 if (!this._map) { return; }
3963 var pos = this._map.latLngToLayerPoint(this._latlng),
3964 animated = this._animated,
3965 offset = L.point(this.options.offset);
3968 L.DomUtil.setPosition(this._container, pos);
3971 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
3972 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
3974 // bottom position the popup in case the height of the popup changes (images loading etc)
3975 this._container.style.bottom = this._containerBottom + 'px';
3976 this._container.style.left = this._containerLeft + 'px';
3979 _zoomAnimation: function (opt) {
3980 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3982 L.DomUtil.setPosition(this._container, pos);
3985 _adjustPan: function () {
3986 if (!this.options.autoPan) { return; }
3988 var map = this._map,
3989 containerHeight = this._container.offsetHeight,
3990 containerWidth = this._containerWidth,
3992 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
3994 if (this._animated) {
3995 layerPos._add(L.DomUtil.getPosition(this._container));
3998 var containerPos = map.layerPointToContainerPoint(layerPos),
3999 padding = L.point(this.options.autoPanPadding),
4000 size = map.getSize(),
4004 if (containerPos.x + containerWidth > size.x) { // right
4005 dx = containerPos.x + containerWidth - size.x + padding.x;
4007 if (containerPos.x - dx < 0) { // left
4008 dx = containerPos.x - padding.x;
4010 if (containerPos.y + containerHeight > size.y) { // bottom
4011 dy = containerPos.y + containerHeight - size.y + padding.y;
4013 if (containerPos.y - dy < 0) { // top
4014 dy = containerPos.y - padding.y;
4019 .fire('autopanstart')
4024 _onCloseButtonClick: function (e) {
4030 L.popup = function (options, source) {
4031 return new L.Popup(options, source);
4036 openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
4039 if (!(popup instanceof L.Popup)) {
4040 var content = popup;
4042 popup = new L.Popup(options)
4044 .setContent(content);
4046 popup._isOpen = true;
4048 this._popup = popup;
4049 return this.addLayer(popup);
4052 closePopup: function (popup) {
4053 if (!popup || popup === this._popup) {
4054 popup = this._popup;
4058 this.removeLayer(popup);
4059 popup._isOpen = false;
4067 * Popup extension to L.Marker, adding popup-related methods.
4071 openPopup: function () {
4072 if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
4073 this._popup.setLatLng(this._latlng);
4074 this._map.openPopup(this._popup);
4080 closePopup: function () {
4082 this._popup._close();
4087 togglePopup: function () {
4089 if (this._popup._isOpen) {
4098 bindPopup: function (content, options) {
4099 var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
4101 anchor = anchor.add(L.Popup.prototype.options.offset);
4103 if (options && options.offset) {
4104 anchor = anchor.add(options.offset);
4107 options = L.extend({offset: anchor}, options);
4111 .on('click', this.togglePopup, this)
4112 .on('remove', this.closePopup, this)
4113 .on('move', this._movePopup, this);
4116 if (content instanceof L.Popup) {
4117 L.setOptions(content, options);
4118 this._popup = content;
4120 this._popup = new L.Popup(options, this)
4121 .setContent(content);
4127 setPopupContent: function (content) {
4129 this._popup.setContent(content);
4134 unbindPopup: function () {
4138 .off('click', this.togglePopup)
4139 .off('remove', this.closePopup)
4140 .off('move', this._movePopup);
4145 _movePopup: function (e) {
4146 this._popup.setLatLng(e.latlng);
4152 * L.LayerGroup is a class to combine several layers into one so that
4153 * you can manipulate the group (e.g. add/remove it) as one layer.
4156 L.LayerGroup = L.Class.extend({
4157 initialize: function (layers) {
4163 for (i = 0, len = layers.length; i < len; i++) {
4164 this.addLayer(layers[i]);
4169 addLayer: function (layer) {
4170 var id = this.getLayerId(layer);
4172 this._layers[id] = layer;
4175 this._map.addLayer(layer);
4181 removeLayer: function (layer) {
4182 var id = layer in this._layers ? layer : this.getLayerId(layer);
4184 if (this._map && this._layers[id]) {
4185 this._map.removeLayer(this._layers[id]);
4188 delete this._layers[id];
4193 hasLayer: function (layer) {
4194 if (!layer) { return false; }
4196 return (layer in this._layers || this.getLayerId(layer) in this._layers);
4199 clearLayers: function () {
4200 this.eachLayer(this.removeLayer, this);
4204 invoke: function (methodName) {
4205 var args = Array.prototype.slice.call(arguments, 1),
4208 for (i in this._layers) {
4209 layer = this._layers[i];
4211 if (layer[methodName]) {
4212 layer[methodName].apply(layer, args);
4219 onAdd: function (map) {
4221 this.eachLayer(map.addLayer, map);
4224 onRemove: function (map) {
4225 this.eachLayer(map.removeLayer, map);
4229 addTo: function (map) {
4234 eachLayer: function (method, context) {
4235 for (var i in this._layers) {
4236 method.call(context, this._layers[i]);
4241 getLayer: function (id) {
4242 return this._layers[id];
4245 getLayers: function () {
4248 for (var i in this._layers) {
4249 layers.push(this._layers[i]);
4254 setZIndex: function (zIndex) {
4255 return this.invoke('setZIndex', zIndex);
4258 getLayerId: function (layer) {
4259 return L.stamp(layer);
4263 L.layerGroup = function (layers) {
4264 return new L.LayerGroup(layers);
4269 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
4270 * shared between a group of interactive layers (like vectors or markers).
4273 L.FeatureGroup = L.LayerGroup.extend({
4274 includes: L.Mixin.Events,
4277 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
4280 addLayer: function (layer) {
4281 if (this.hasLayer(layer)) {
4285 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4287 L.LayerGroup.prototype.addLayer.call(this, layer);
4289 if (this._popupContent && layer.bindPopup) {
4290 layer.bindPopup(this._popupContent, this._popupOptions);
4293 return this.fire('layeradd', {layer: layer});
4296 removeLayer: function (layer) {
4297 if (!this.hasLayer(layer)) {
4300 if (layer in this._layers) {
4301 layer = this._layers[layer];
4304 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4306 L.LayerGroup.prototype.removeLayer.call(this, layer);
4308 if (this._popupContent) {
4309 this.invoke('unbindPopup');
4312 return this.fire('layerremove', {layer: layer});
4315 bindPopup: function (content, options) {
4316 this._popupContent = content;
4317 this._popupOptions = options;
4318 return this.invoke('bindPopup', content, options);
4321 setStyle: function (style) {
4322 return this.invoke('setStyle', style);
4325 bringToFront: function () {
4326 return this.invoke('bringToFront');
4329 bringToBack: function () {
4330 return this.invoke('bringToBack');
4333 getBounds: function () {
4334 var bounds = new L.LatLngBounds();
4336 this.eachLayer(function (layer) {
4337 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
4343 _propagateEvent: function (e) {
4349 this.fire(e.type, e);
4353 L.featureGroup = function (layers) {
4354 return new L.FeatureGroup(layers);
4359 * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
4362 L.Path = L.Class.extend({
4363 includes: [L.Mixin.Events],
4366 // how much to extend the clip area around the map view
4367 // (relative to its size, e.g. 0.5 is half the screen in each direction)
4368 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
4369 CLIP_PADDING: (function () {
4370 var max = L.Browser.mobile ? 1280 : 2000,
4371 target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
4372 return Math.max(0, Math.min(0.5, target));
4384 fillColor: null, //same as color by default
4390 initialize: function (options) {
4391 L.setOptions(this, options);
4394 onAdd: function (map) {
4397 if (!this._container) {
4398 this._initElements();
4402 this.projectLatlngs();
4405 if (this._container) {
4406 this._map._pathRoot.appendChild(this._container);
4412 'viewreset': this.projectLatlngs,
4413 'moveend': this._updatePath
4417 addTo: function (map) {
4422 onRemove: function (map) {
4423 map._pathRoot.removeChild(this._container);
4425 // Need to fire remove event before we set _map to null as the event hooks might need the object
4426 this.fire('remove');
4429 if (L.Browser.vml) {
4430 this._container = null;
4431 this._stroke = null;
4436 'viewreset': this.projectLatlngs,
4437 'moveend': this._updatePath
4441 projectLatlngs: function () {
4442 // do all projection stuff here
4445 setStyle: function (style) {
4446 L.setOptions(this, style);
4448 if (this._container) {
4449 this._updateStyle();
4455 redraw: function () {
4457 this.projectLatlngs();
4465 _updatePathViewport: function () {
4466 var p = L.Path.CLIP_PADDING,
4467 size = this.getSize(),
4468 panePos = L.DomUtil.getPosition(this._mapPane),
4469 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4470 max = min.add(size.multiplyBy(1 + p * 2)._round());
4472 this._pathViewport = new L.Bounds(min, max);
4478 * Extends L.Path with SVG-specific rendering code.
4481 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4483 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4485 L.Path = L.Path.extend({
4490 bringToFront: function () {
4491 var root = this._map._pathRoot,
4492 path = this._container;
4494 if (path && root.lastChild !== path) {
4495 root.appendChild(path);
4500 bringToBack: function () {
4501 var root = this._map._pathRoot,
4502 path = this._container,
4503 first = root.firstChild;
4505 if (path && first !== path) {
4506 root.insertBefore(path, first);
4511 getPathString: function () {
4512 // form path string here
4515 _createElement: function (name) {
4516 return document.createElementNS(L.Path.SVG_NS, name);
4519 _initElements: function () {
4520 this._map._initPathRoot();
4525 _initPath: function () {
4526 this._container = this._createElement('g');
4528 this._path = this._createElement('path');
4529 this._container.appendChild(this._path);
4532 _initStyle: function () {
4533 if (this.options.stroke) {
4534 this._path.setAttribute('stroke-linejoin', 'round');
4535 this._path.setAttribute('stroke-linecap', 'round');
4537 if (this.options.fill) {
4538 this._path.setAttribute('fill-rule', 'evenodd');
4540 if (this.options.pointerEvents) {
4541 this._path.setAttribute('pointer-events', this.options.pointerEvents);
4543 if (!this.options.clickable && !this.options.pointerEvents) {
4544 this._path.setAttribute('pointer-events', 'none');
4546 this._updateStyle();
4549 _updateStyle: function () {
4550 if (this.options.stroke) {
4551 this._path.setAttribute('stroke', this.options.color);
4552 this._path.setAttribute('stroke-opacity', this.options.opacity);
4553 this._path.setAttribute('stroke-width', this.options.weight);
4554 if (this.options.dashArray) {
4555 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4557 this._path.removeAttribute('stroke-dasharray');
4560 this._path.setAttribute('stroke', 'none');
4562 if (this.options.fill) {
4563 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4564 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4566 this._path.setAttribute('fill', 'none');
4570 _updatePath: function () {
4571 var str = this.getPathString();
4573 // fix webkit empty string parsing bug
4576 this._path.setAttribute('d', str);
4579 // TODO remove duplication with L.Map
4580 _initEvents: function () {
4581 if (this.options.clickable) {
4582 if (L.Browser.svg || !L.Browser.vml) {
4583 this._path.setAttribute('class', 'leaflet-clickable');
4586 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4588 var events = ['dblclick', 'mousedown', 'mouseover',
4589 'mouseout', 'mousemove', 'contextmenu'];
4590 for (var i = 0; i < events.length; i++) {
4591 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4596 _onMouseClick: function (e) {
4597 if (this._map.dragging && this._map.dragging.moved()) { return; }
4599 this._fireMouseEvent(e);
4602 _fireMouseEvent: function (e) {
4603 if (!this.hasEventListeners(e.type)) { return; }
4605 var map = this._map,
4606 containerPoint = map.mouseEventToContainerPoint(e),
4607 layerPoint = map.containerPointToLayerPoint(containerPoint),
4608 latlng = map.layerPointToLatLng(layerPoint);
4612 layerPoint: layerPoint,
4613 containerPoint: containerPoint,
4617 if (e.type === 'contextmenu') {
4618 L.DomEvent.preventDefault(e);
4620 if (e.type !== 'mousemove') {
4621 L.DomEvent.stopPropagation(e);
4627 _initPathRoot: function () {
4628 if (!this._pathRoot) {
4629 this._pathRoot = L.Path.prototype._createElement('svg');
4630 this._panes.overlayPane.appendChild(this._pathRoot);
4632 if (this.options.zoomAnimation && L.Browser.any3d) {
4633 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
4636 'zoomanim': this._animatePathZoom,
4637 'zoomend': this._endPathZoom
4640 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
4643 this.on('moveend', this._updateSvgViewport);
4644 this._updateSvgViewport();
4648 _animatePathZoom: function (e) {
4649 var scale = this.getZoomScale(e.zoom),
4650 offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4652 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4653 L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4655 this._pathZooming = true;
4658 _endPathZoom: function () {
4659 this._pathZooming = false;
4662 _updateSvgViewport: function () {
4664 if (this._pathZooming) {
4665 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4666 // When the zoom animation ends we will be updated again anyway
4667 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4671 this._updatePathViewport();
4673 var vp = this._pathViewport,
4676 width = max.x - min.x,
4677 height = max.y - min.y,
4678 root = this._pathRoot,
4679 pane = this._panes.overlayPane;
4681 // Hack to make flicker on drag end on mobile webkit less irritating
4682 if (L.Browser.mobileWebkit) {
4683 pane.removeChild(root);
4686 L.DomUtil.setPosition(root, min);
4687 root.setAttribute('width', width);
4688 root.setAttribute('height', height);
4689 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4691 if (L.Browser.mobileWebkit) {
4692 pane.appendChild(root);
4699 * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4704 bindPopup: function (content, options) {
4706 if (content instanceof L.Popup) {
4707 this._popup = content;
4709 if (!this._popup || options) {
4710 this._popup = new L.Popup(options, this);
4712 this._popup.setContent(content);
4715 if (!this._popupHandlersAdded) {
4717 .on('click', this._openPopup, this)
4718 .on('remove', this.closePopup, this);
4720 this._popupHandlersAdded = true;
4726 unbindPopup: function () {
4730 .off('click', this._openPopup)
4731 .off('remove', this.closePopup);
4733 this._popupHandlersAdded = false;
4738 openPopup: function (latlng) {
4741 // open the popup from one of the path's points if not specified
4742 latlng = latlng || this._latlng ||
4743 this._latlngs[Math.floor(this._latlngs.length / 2)];
4745 this._openPopup({latlng: latlng});
4751 closePopup: function () {
4753 this._popup._close();
4758 _openPopup: function (e) {
4759 this._popup.setLatLng(e.latlng);
4760 this._map.openPopup(this._popup);
4766 * Vector rendering for IE6-8 through VML.
4767 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4770 L.Browser.vml = !L.Browser.svg && (function () {
4772 var div = document.createElement('div');
4773 div.innerHTML = '<v:shape adj="1"/>';
4775 var shape = div.firstChild;
4776 shape.style.behavior = 'url(#default#VML)';
4778 return shape && (typeof shape.adj === 'object');
4785 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4791 _createElement: (function () {
4793 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4794 return function (name) {
4795 return document.createElement('<lvml:' + name + ' class="lvml">');
4798 return function (name) {
4799 return document.createElement(
4800 '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4805 _initPath: function () {
4806 var container = this._container = this._createElement('shape');
4807 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4808 if (this.options.clickable) {
4809 L.DomUtil.addClass(container, 'leaflet-clickable');
4811 container.coordsize = '1 1';
4813 this._path = this._createElement('path');
4814 container.appendChild(this._path);
4816 this._map._pathRoot.appendChild(container);
4819 _initStyle: function () {
4820 this._updateStyle();
4823 _updateStyle: function () {
4824 var stroke = this._stroke,
4826 options = this.options,
4827 container = this._container;
4829 container.stroked = options.stroke;
4830 container.filled = options.fill;
4832 if (options.stroke) {
4834 stroke = this._stroke = this._createElement('stroke');
4835 stroke.endcap = 'round';
4836 container.appendChild(stroke);
4838 stroke.weight = options.weight + 'px';
4839 stroke.color = options.color;
4840 stroke.opacity = options.opacity;
4842 if (options.dashArray) {
4843 stroke.dashStyle = options.dashArray instanceof Array ?
4844 options.dashArray.join(' ') :
4845 options.dashArray.replace(/( *, *)/g, ' ');
4847 stroke.dashStyle = '';
4850 } else if (stroke) {
4851 container.removeChild(stroke);
4852 this._stroke = null;
4857 fill = this._fill = this._createElement('fill');
4858 container.appendChild(fill);
4860 fill.color = options.fillColor || options.color;
4861 fill.opacity = options.fillOpacity;
4864 container.removeChild(fill);
4869 _updatePath: function () {
4870 var style = this._container.style;
4872 style.display = 'none';
4873 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4878 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4879 _initPathRoot: function () {
4880 if (this._pathRoot) { return; }
4882 var root = this._pathRoot = document.createElement('div');
4883 root.className = 'leaflet-vml-container';
4884 this._panes.overlayPane.appendChild(root);
4886 this.on('moveend', this._updatePathViewport);
4887 this._updatePathViewport();
4893 * Vector rendering for all browsers that support canvas.
4896 L.Browser.canvas = (function () {
4897 return !!document.createElement('canvas').getContext;
4900 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4902 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4907 redraw: function () {
4909 this.projectLatlngs();
4910 this._requestUpdate();
4915 setStyle: function (style) {
4916 L.setOptions(this, style);
4919 this._updateStyle();
4920 this._requestUpdate();
4925 onRemove: function (map) {
4927 .off('viewreset', this.projectLatlngs, this)
4928 .off('moveend', this._updatePath, this);
4930 if (this.options.clickable) {
4931 this._map.off('click', this._onClick, this);
4932 this._map.off('mousemove', this._onMouseMove, this);
4935 this._requestUpdate();
4940 _requestUpdate: function () {
4941 if (this._map && !L.Path._updateRequest) {
4942 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4946 _fireMapMoveEnd: function () {
4947 L.Path._updateRequest = null;
4948 this.fire('moveend');
4951 _initElements: function () {
4952 this._map._initPathRoot();
4953 this._ctx = this._map._canvasCtx;
4956 _updateStyle: function () {
4957 var options = this.options;
4959 if (options.stroke) {
4960 this._ctx.lineWidth = options.weight;
4961 this._ctx.strokeStyle = options.color;
4964 this._ctx.fillStyle = options.fillColor || options.color;
4968 _drawPath: function () {
4969 var i, j, len, len2, point, drawMethod;
4971 this._ctx.beginPath();
4973 for (i = 0, len = this._parts.length; i < len; i++) {
4974 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4975 point = this._parts[i][j];
4976 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4978 this._ctx[drawMethod](point.x, point.y);
4980 // TODO refactor ugly hack
4981 if (this instanceof L.Polygon) {
4982 this._ctx.closePath();
4987 _checkIfEmpty: function () {
4988 return !this._parts.length;
4991 _updatePath: function () {
4992 if (this._checkIfEmpty()) { return; }
4994 var ctx = this._ctx,
4995 options = this.options;
4999 this._updateStyle();
5002 ctx.globalAlpha = options.fillOpacity;
5006 if (options.stroke) {
5007 ctx.globalAlpha = options.opacity;
5013 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
5016 _initEvents: function () {
5017 if (this.options.clickable) {
5019 this._map.on('mousemove', this._onMouseMove, this);
5020 this._map.on('click', this._onClick, this);
5024 _onClick: function (e) {
5025 if (this._containsPoint(e.layerPoint)) {
5026 this.fire('click', e);
5030 _onMouseMove: function (e) {
5031 if (!this._map || this._map._animatingZoom) { return; }
5033 // TODO don't do on each move
5034 if (this._containsPoint(e.layerPoint)) {
5035 this._ctx.canvas.style.cursor = 'pointer';
5036 this._mouseInside = true;
5037 this.fire('mouseover', e);
5039 } else if (this._mouseInside) {
5040 this._ctx.canvas.style.cursor = '';
5041 this._mouseInside = false;
5042 this.fire('mouseout', e);
5047 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
5048 _initPathRoot: function () {
5049 var root = this._pathRoot,
5053 root = this._pathRoot = document.createElement('canvas');
5054 root.style.position = 'absolute';
5055 ctx = this._canvasCtx = root.getContext('2d');
5057 ctx.lineCap = 'round';
5058 ctx.lineJoin = 'round';
5060 this._panes.overlayPane.appendChild(root);
5062 if (this.options.zoomAnimation) {
5063 this._pathRoot.className = 'leaflet-zoom-animated';
5064 this.on('zoomanim', this._animatePathZoom);
5065 this.on('zoomend', this._endPathZoom);
5067 this.on('moveend', this._updateCanvasViewport);
5068 this._updateCanvasViewport();
5072 _updateCanvasViewport: function () {
5073 // don't redraw while zooming. See _updateSvgViewport for more details
5074 if (this._pathZooming) { return; }
5075 this._updatePathViewport();
5077 var vp = this._pathViewport,
5079 size = vp.max.subtract(min),
5080 root = this._pathRoot;
5082 //TODO check if this works properly on mobile webkit
5083 L.DomUtil.setPosition(root, min);
5084 root.width = size.x;
5085 root.height = size.y;
5086 root.getContext('2d').translate(-min.x, -min.y);
5092 * L.LineUtil contains different utility functions for line segments
5093 * and polylines (clipping, simplification, distances, etc.)
5096 /*jshint bitwise:false */ // allow bitwise oprations for this file
5100 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
5101 // Improves rendering performance dramatically by lessening the number of points to draw.
5103 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
5104 if (!tolerance || !points.length) {
5105 return points.slice();
5108 var sqTolerance = tolerance * tolerance;
5110 // stage 1: vertex reduction
5111 points = this._reducePoints(points, sqTolerance);
5113 // stage 2: Douglas-Peucker simplification
5114 points = this._simplifyDP(points, sqTolerance);
5119 // distance from a point to a segment between two points
5120 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5121 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
5124 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5125 return this._sqClosestPointOnSegment(p, p1, p2);
5128 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
5129 _simplifyDP: function (points, sqTolerance) {
5131 var len = points.length,
5132 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
5133 markers = new ArrayConstructor(len);
5135 markers[0] = markers[len - 1] = 1;
5137 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
5142 for (i = 0; i < len; i++) {
5144 newPoints.push(points[i]);
5151 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
5156 for (i = first + 1; i <= last - 1; i++) {
5157 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
5159 if (sqDist > maxSqDist) {
5165 if (maxSqDist > sqTolerance) {
5168 this._simplifyDPStep(points, markers, sqTolerance, first, index);
5169 this._simplifyDPStep(points, markers, sqTolerance, index, last);
5173 // reduce points that are too close to each other to a single point
5174 _reducePoints: function (points, sqTolerance) {
5175 var reducedPoints = [points[0]];
5177 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
5178 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
5179 reducedPoints.push(points[i]);
5183 if (prev < len - 1) {
5184 reducedPoints.push(points[len - 1]);
5186 return reducedPoints;
5189 // Cohen-Sutherland line clipping algorithm.
5190 // Used to avoid rendering parts of a polyline that are not currently visible.
5192 clipSegment: function (a, b, bounds, useLastCode) {
5193 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
5194 codeB = this._getBitCode(b, bounds),
5196 codeOut, p, newCode;
5198 // save 2nd code to avoid calculating it on the next segment
5199 this._lastCode = codeB;
5202 // if a,b is inside the clip window (trivial accept)
5203 if (!(codeA | codeB)) {
5205 // if a,b is outside the clip window (trivial reject)
5206 } else if (codeA & codeB) {
5210 codeOut = codeA || codeB;
5211 p = this._getEdgeIntersection(a, b, codeOut, bounds);
5212 newCode = this._getBitCode(p, bounds);
5214 if (codeOut === codeA) {
5225 _getEdgeIntersection: function (a, b, code, bounds) {
5231 if (code & 8) { // top
5232 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
5233 } else if (code & 4) { // bottom
5234 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
5235 } else if (code & 2) { // right
5236 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
5237 } else if (code & 1) { // left
5238 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
5242 _getBitCode: function (/*Point*/ p, bounds) {
5245 if (p.x < bounds.min.x) { // left
5247 } else if (p.x > bounds.max.x) { // right
5250 if (p.y < bounds.min.y) { // bottom
5252 } else if (p.y > bounds.max.y) { // top
5259 // square distance (to avoid unnecessary Math.sqrt calls)
5260 _sqDist: function (p1, p2) {
5261 var dx = p2.x - p1.x,
5263 return dx * dx + dy * dy;
5266 // return closest point on segment or distance to that point
5267 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
5272 dot = dx * dx + dy * dy,
5276 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
5290 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
5296 * L.Polyline is used to display polylines on a map.
5299 L.Polyline = L.Path.extend({
5300 initialize: function (latlngs, options) {
5301 L.Path.prototype.initialize.call(this, options);
5303 this._latlngs = this._convertLatLngs(latlngs);
5307 // how much to simplify the polyline on each zoom level
5308 // more = better performance and smoother look, less = more accurate
5313 projectLatlngs: function () {
5314 this._originalPoints = [];
5316 for (var i = 0, len = this._latlngs.length; i < len; i++) {
5317 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
5321 getPathString: function () {
5322 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
5323 str += this._getPathPartStr(this._parts[i]);
5328 getLatLngs: function () {
5329 return this._latlngs;
5332 setLatLngs: function (latlngs) {
5333 this._latlngs = this._convertLatLngs(latlngs);
5334 return this.redraw();
5337 addLatLng: function (latlng) {
5338 this._latlngs.push(L.latLng(latlng));
5339 return this.redraw();
5342 spliceLatLngs: function () { // (Number index, Number howMany)
5343 var removed = [].splice.apply(this._latlngs, arguments);
5344 this._convertLatLngs(this._latlngs, true);
5349 closestLayerPoint: function (p) {
5350 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
5352 for (var j = 0, jLen = parts.length; j < jLen; j++) {
5353 var points = parts[j];
5354 for (var i = 1, len = points.length; i < len; i++) {
5357 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
5358 if (sqDist < minDistance) {
5359 minDistance = sqDist;
5360 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
5365 minPoint.distance = Math.sqrt(minDistance);
5370 getBounds: function () {
5371 return new L.LatLngBounds(this.getLatLngs());
5374 _convertLatLngs: function (latlngs, overwrite) {
5375 var i, len, target = overwrite ? latlngs : [];
5377 for (i = 0, len = latlngs.length; i < len; i++) {
5378 if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
5381 target[i] = L.latLng(latlngs[i]);
5386 _initEvents: function () {
5387 L.Path.prototype._initEvents.call(this);
5390 _getPathPartStr: function (points) {
5391 var round = L.Path.VML;
5393 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
5398 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
5403 _clipPoints: function () {
5404 var points = this._originalPoints,
5405 len = points.length,
5408 if (this.options.noClip) {
5409 this._parts = [points];
5415 var parts = this._parts,
5416 vp = this._map._pathViewport,
5419 for (i = 0, k = 0; i < len - 1; i++) {
5420 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
5425 parts[k] = parts[k] || [];
5426 parts[k].push(segment[0]);
5428 // if segment goes out of screen, or it's the last one, it's the end of the line part
5429 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
5430 parts[k].push(segment[1]);
5436 // simplify each clipped part of the polyline
5437 _simplifyPoints: function () {
5438 var parts = this._parts,
5441 for (var i = 0, len = parts.length; i < len; i++) {
5442 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
5446 _updatePath: function () {
5447 if (!this._map) { return; }
5450 this._simplifyPoints();
5452 L.Path.prototype._updatePath.call(this);
5456 L.polyline = function (latlngs, options) {
5457 return new L.Polyline(latlngs, options);
5462 * L.PolyUtil contains utility functions for polygons (clipping, etc.).
5465 /*jshint bitwise:false */ // allow bitwise operations here
5470 * Sutherland-Hodgeman polygon clipping algorithm.
5471 * Used to avoid rendering parts of a polygon that are not currently visible.
5473 L.PolyUtil.clipPolygon = function (points, bounds) {
5475 edges = [1, 4, 2, 8],
5481 for (i = 0, len = points.length; i < len; i++) {
5482 points[i]._code = lu._getBitCode(points[i], bounds);
5485 // for each edge (left, bottom, right, top)
5486 for (k = 0; k < 4; k++) {
5490 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5494 // if a is inside the clip window
5495 if (!(a._code & edge)) {
5496 // if b is outside the clip window (a->b goes out of screen)
5497 if (b._code & edge) {
5498 p = lu._getEdgeIntersection(b, a, edge, bounds);
5499 p._code = lu._getBitCode(p, bounds);
5500 clippedPoints.push(p);
5502 clippedPoints.push(a);
5504 // else if b is inside the clip window (a->b enters the screen)
5505 } else if (!(b._code & edge)) {
5506 p = lu._getEdgeIntersection(b, a, edge, bounds);
5507 p._code = lu._getBitCode(p, bounds);
5508 clippedPoints.push(p);
5511 points = clippedPoints;
5519 * L.Polygon is used to display polygons on a map.
5522 L.Polygon = L.Polyline.extend({
5527 initialize: function (latlngs, options) {
5530 L.Polyline.prototype.initialize.call(this, latlngs, options);
5532 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5533 this._latlngs = this._convertLatLngs(latlngs[0]);
5534 this._holes = latlngs.slice(1);
5536 for (i = 0, len = this._holes.length; i < len; i++) {
5537 hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
5538 if (hole[0].equals(hole[hole.length - 1])) {
5544 // filter out last point if its equal to the first one
5545 latlngs = this._latlngs;
5547 if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
5552 projectLatlngs: function () {
5553 L.Polyline.prototype.projectLatlngs.call(this);
5555 // project polygon holes points
5556 // TODO move this logic to Polyline to get rid of duplication
5557 this._holePoints = [];
5559 if (!this._holes) { return; }
5561 var i, j, len, len2;
5563 for (i = 0, len = this._holes.length; i < len; i++) {
5564 this._holePoints[i] = [];
5566 for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5567 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5572 _clipPoints: function () {
5573 var points = this._originalPoints,
5576 this._parts = [points].concat(this._holePoints);
5578 if (this.options.noClip) { return; }
5580 for (var i = 0, len = this._parts.length; i < len; i++) {
5581 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5582 if (clipped.length) {
5583 newParts.push(clipped);
5587 this._parts = newParts;
5590 _getPathPartStr: function (points) {
5591 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5592 return str + (L.Browser.svg ? 'z' : 'x');
5596 L.polygon = function (latlngs, options) {
5597 return new L.Polygon(latlngs, options);
5602 * Contains L.MultiPolyline and L.MultiPolygon layers.
5606 function createMulti(Klass) {
5608 return L.FeatureGroup.extend({
5610 initialize: function (latlngs, options) {
5612 this._options = options;
5613 this.setLatLngs(latlngs);
5616 setLatLngs: function (latlngs) {
5618 len = latlngs.length;
5620 this.eachLayer(function (layer) {
5622 layer.setLatLngs(latlngs[i++]);
5624 this.removeLayer(layer);
5629 this.addLayer(new Klass(latlngs[i++], this._options));
5635 getLatLngs: function () {
5638 this.eachLayer(function (layer) {
5639 latlngs.push(layer.getLatLngs());
5647 L.MultiPolyline = createMulti(L.Polyline);
5648 L.MultiPolygon = createMulti(L.Polygon);
5650 L.multiPolyline = function (latlngs, options) {
5651 return new L.MultiPolyline(latlngs, options);
5654 L.multiPolygon = function (latlngs, options) {
5655 return new L.MultiPolygon(latlngs, options);
5661 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5664 L.Rectangle = L.Polygon.extend({
5665 initialize: function (latLngBounds, options) {
5666 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5669 setBounds: function (latLngBounds) {
5670 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5673 _boundsToLatLngs: function (latLngBounds) {
5674 latLngBounds = L.latLngBounds(latLngBounds);
5676 latLngBounds.getSouthWest(),
5677 latLngBounds.getNorthWest(),
5678 latLngBounds.getNorthEast(),
5679 latLngBounds.getSouthEast()
5684 L.rectangle = function (latLngBounds, options) {
5685 return new L.Rectangle(latLngBounds, options);
5690 * L.Circle is a circle overlay (with a certain radius in meters).
5693 L.Circle = L.Path.extend({
5694 initialize: function (latlng, radius, options) {
5695 L.Path.prototype.initialize.call(this, options);
5697 this._latlng = L.latLng(latlng);
5698 this._mRadius = radius;
5705 setLatLng: function (latlng) {
5706 this._latlng = L.latLng(latlng);
5707 return this.redraw();
5710 setRadius: function (radius) {
5711 this._mRadius = radius;
5712 return this.redraw();
5715 projectLatlngs: function () {
5716 var lngRadius = this._getLngRadius(),
5717 latlng = this._latlng,
5718 pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
5720 this._point = this._map.latLngToLayerPoint(latlng);
5721 this._radius = Math.max(this._point.x - pointLeft.x, 1);
5724 getBounds: function () {
5725 var lngRadius = this._getLngRadius(),
5726 latRadius = (this._mRadius / 40075017) * 360,
5727 latlng = this._latlng;
5729 return new L.LatLngBounds(
5730 [latlng.lat - latRadius, latlng.lng - lngRadius],
5731 [latlng.lat + latRadius, latlng.lng + lngRadius]);
5734 getLatLng: function () {
5735 return this._latlng;
5738 getPathString: function () {
5739 var p = this._point,
5742 if (this._checkIfEmpty()) {
5746 if (L.Browser.svg) {
5747 return 'M' + p.x + ',' + (p.y - r) +
5748 'A' + r + ',' + r + ',0,1,1,' +
5749 (p.x - 0.1) + ',' + (p.y - r) + ' z';
5753 return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
5757 getRadius: function () {
5758 return this._mRadius;
5761 // TODO Earth hardcoded, move into projection code!
5763 _getLatRadius: function () {
5764 return (this._mRadius / 40075017) * 360;
5767 _getLngRadius: function () {
5768 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5771 _checkIfEmpty: function () {
5775 var vp = this._map._pathViewport,
5779 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5780 p.x + r < vp.min.x || p.y + r < vp.min.y;
5784 L.circle = function (latlng, radius, options) {
5785 return new L.Circle(latlng, radius, options);
5790 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5793 L.CircleMarker = L.Circle.extend({
5799 initialize: function (latlng, options) {
5800 L.Circle.prototype.initialize.call(this, latlng, null, options);
5801 this._radius = this.options.radius;
5804 projectLatlngs: function () {
5805 this._point = this._map.latLngToLayerPoint(this._latlng);
5808 _updateStyle : function () {
5809 L.Circle.prototype._updateStyle.call(this);
5810 this.setRadius(this.options.radius);
5813 setRadius: function (radius) {
5814 this.options.radius = this._radius = radius;
5815 return this.redraw();
5819 L.circleMarker = function (latlng, options) {
5820 return new L.CircleMarker(latlng, options);
5825 * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
5828 L.Polyline.include(!L.Path.CANVAS ? {} : {
5829 _containsPoint: function (p, closed) {
5830 var i, j, k, len, len2, dist, part,
5831 w = this.options.weight / 2;
5833 if (L.Browser.touch) {
5834 w += 10; // polyline click tolerance on touch devices
5837 for (i = 0, len = this._parts.length; i < len; i++) {
5838 part = this._parts[i];
5839 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5840 if (!closed && (j === 0)) {
5844 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5857 * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
5860 L.Polygon.include(!L.Path.CANVAS ? {} : {
5861 _containsPoint: function (p) {
5867 // TODO optimization: check if within bounds first
5869 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5870 // click on polygon border
5874 // ray casting algorithm for detecting if point is in polygon
5876 for (i = 0, len = this._parts.length; i < len; i++) {
5877 part = this._parts[i];
5879 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5883 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5884 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5896 * Extends L.Circle with Canvas-specific code.
5899 L.Circle.include(!L.Path.CANVAS ? {} : {
5900 _drawPath: function () {
5901 var p = this._point;
5902 this._ctx.beginPath();
5903 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5906 _containsPoint: function (p) {
5907 var center = this._point,
5908 w2 = this.options.stroke ? this.options.weight / 2 : 0;
5910 return (p.distanceTo(center) <= this._radius + w2);
5916 * CircleMarker canvas specific drawing parts.
5919 L.CircleMarker.include(!L.Path.CANVAS ? {} : {
5920 _updateStyle: function () {
5921 L.Path.prototype._updateStyle.call(this);
5927 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
5930 L.GeoJSON = L.FeatureGroup.extend({
5932 initialize: function (geojson, options) {
5933 L.setOptions(this, options);
5938 this.addData(geojson);
5942 addData: function (geojson) {
5943 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
5947 for (i = 0, len = features.length; i < len; i++) {
5948 // Only add this if geometry or geometries are set and not null
5949 feature = features[i];
5950 if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
5951 this.addData(features[i]);
5957 var options = this.options;
5959 if (options.filter && !options.filter(geojson)) { return; }
5961 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng);
5962 layer.feature = L.GeoJSON.asFeature(geojson);
5964 layer.defaultOptions = layer.options;
5965 this.resetStyle(layer);
5967 if (options.onEachFeature) {
5968 options.onEachFeature(geojson, layer);
5971 return this.addLayer(layer);
5974 resetStyle: function (layer) {
5975 var style = this.options.style;
5977 // reset any custom styles
5978 L.Util.extend(layer.options, layer.defaultOptions);
5980 this._setLayerStyle(layer, style);
5984 setStyle: function (style) {
5985 this.eachLayer(function (layer) {
5986 this._setLayerStyle(layer, style);
5990 _setLayerStyle: function (layer, style) {
5991 if (typeof style === 'function') {
5992 style = style(layer.feature);
5994 if (layer.setStyle) {
5995 layer.setStyle(style);
6000 L.extend(L.GeoJSON, {
6001 geometryToLayer: function (geojson, pointToLayer, coordsToLatLng) {
6002 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
6003 coords = geometry.coordinates,
6005 latlng, latlngs, i, len, layer;
6007 coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
6009 switch (geometry.type) {
6011 latlng = coordsToLatLng(coords);
6012 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6015 for (i = 0, len = coords.length; i < len; i++) {
6016 latlng = coordsToLatLng(coords[i]);
6017 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6020 return new L.FeatureGroup(layers);
6023 latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
6024 return new L.Polyline(latlngs);
6027 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6028 return new L.Polygon(latlngs);
6030 case 'MultiLineString':
6031 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6032 return new L.MultiPolyline(latlngs);
6034 case 'MultiPolygon':
6035 latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
6036 return new L.MultiPolygon(latlngs);
6038 case 'GeometryCollection':
6039 for (i = 0, len = geometry.geometries.length; i < len; i++) {
6041 layer = this.geometryToLayer({
6042 geometry: geometry.geometries[i],
6044 properties: geojson.properties
6045 }, pointToLayer, coordsToLatLng);
6049 return new L.FeatureGroup(layers);
6052 throw new Error('Invalid GeoJSON object.');
6056 coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
6057 return new L.LatLng(coords[1], coords[0]);
6060 coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
6064 for (i = 0, len = coords.length; i < len; i++) {
6065 latlng = levelsDeep ?
6066 this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
6067 (coordsToLatLng || this.coordsToLatLng)(coords[i]);
6069 latlngs.push(latlng);
6075 latLngToCoords: function (latLng) {
6076 return [latLng.lng, latLng.lat];
6079 latLngsToCoords: function (latLngs) {
6082 for (var i = 0, len = latLngs.length; i < len; i++) {
6083 coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
6089 getFeature: function (layer, newGeometry) {
6090 return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
6093 asFeature: function (geoJSON) {
6094 if (geoJSON.type === 'Feature') {
6106 var PointToGeoJSON = {
6107 toGeoJSON: function () {
6108 return L.GeoJSON.getFeature(this, {
6110 coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
6115 L.Marker.include(PointToGeoJSON);
6116 L.Circle.include(PointToGeoJSON);
6117 L.CircleMarker.include(PointToGeoJSON);
6119 L.Polyline.include({
6120 toGeoJSON: function () {
6121 return L.GeoJSON.getFeature(this, {
6123 coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
6129 toGeoJSON: function () {
6130 var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
6133 coords[0].push(coords[0][0]);
6136 for (i = 0, len = this._holes.length; i < len; i++) {
6137 hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
6143 return L.GeoJSON.getFeature(this, {
6151 function includeMulti(Klass, type) {
6153 toGeoJSON: function () {
6156 this.eachLayer(function (layer) {
6157 coords.push(layer.toGeoJSON().geometry.coordinates);
6160 return L.GeoJSON.getFeature(this, {
6168 includeMulti(L.MultiPolyline, 'MultiLineString');
6169 includeMulti(L.MultiPolygon, 'MultiPolygon');
6172 L.LayerGroup.include({
6173 toGeoJSON: function () {
6176 this.eachLayer(function (layer) {
6177 if (layer.toGeoJSON) {
6178 features.push(L.GeoJSON.asFeature(layer.toGeoJSON()));
6183 type: 'FeatureCollection',
6189 L.geoJson = function (geojson, options) {
6190 return new L.GeoJSON(geojson, options);
6195 * L.DomEvent contains functions for working with DOM events.
6199 /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
6200 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
6202 var id = L.stamp(fn),
6203 key = '_leaflet_' + type + id,
6204 handler, originalHandler, newType;
6206 if (obj[key]) { return this; }
6208 handler = function (e) {
6209 return fn.call(context || obj, e || L.DomEvent._getEvent());
6212 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6213 return this.addMsTouchListener(obj, type, handler, id);
6215 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
6216 this.addDoubleTapListener(obj, handler, id);
6219 if ('addEventListener' in obj) {
6221 if (type === 'mousewheel') {
6222 obj.addEventListener('DOMMouseScroll', handler, false);
6223 obj.addEventListener(type, handler, false);
6225 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6227 originalHandler = handler;
6228 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
6230 handler = function (e) {
6231 if (!L.DomEvent._checkMouse(obj, e)) { return; }
6232 return originalHandler(e);
6235 obj.addEventListener(newType, handler, false);
6237 } else if (type === 'click' && L.Browser.android) {
6238 originalHandler = handler;
6239 handler = function (e) {
6240 return L.DomEvent._filterClick(e, originalHandler);
6243 obj.addEventListener(type, handler, false);
6245 obj.addEventListener(type, handler, false);
6248 } else if ('attachEvent' in obj) {
6249 obj.attachEvent('on' + type, handler);
6257 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
6259 var id = L.stamp(fn),
6260 key = '_leaflet_' + type + id,
6263 if (!handler) { return this; }
6265 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6266 this.removeMsTouchListener(obj, type, id);
6267 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
6268 this.removeDoubleTapListener(obj, id);
6270 } else if ('removeEventListener' in obj) {
6272 if (type === 'mousewheel') {
6273 obj.removeEventListener('DOMMouseScroll', handler, false);
6274 obj.removeEventListener(type, handler, false);
6276 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6277 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
6279 obj.removeEventListener(type, handler, false);
6281 } else if ('detachEvent' in obj) {
6282 obj.detachEvent('on' + type, handler);
6290 stopPropagation: function (e) {
6292 if (e.stopPropagation) {
6293 e.stopPropagation();
6295 e.cancelBubble = true;
6300 disableClickPropagation: function (el) {
6301 var stop = L.DomEvent.stopPropagation;
6303 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6304 L.DomEvent.addListener(el, L.Draggable.START[i], stop);
6308 .addListener(el, 'click', L.DomEvent._fakeStop)
6309 .addListener(el, 'dblclick', stop);
6312 preventDefault: function (e) {
6314 if (e.preventDefault) {
6317 e.returnValue = false;
6322 stop: function (e) {
6323 return L.DomEvent.preventDefault(e).stopPropagation(e);
6326 getMousePosition: function (e, container) {
6328 var ie7 = L.Browser.ie7,
6329 body = document.body,
6330 docEl = document.documentElement,
6331 x = e.pageX ? e.pageX - body.scrollLeft - docEl.scrollLeft: e.clientX,
6332 y = e.pageY ? e.pageY - body.scrollTop - docEl.scrollTop: e.clientY,
6333 pos = new L.Point(x, y),
6334 rect = container.getBoundingClientRect(),
6335 left = rect.left - container.clientLeft,
6336 top = rect.top - container.clientTop;
6338 // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
6339 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
6340 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
6341 left += container.scrollWidth - container.clientWidth;
6343 // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
6344 // need to add it back in if it is visible; scrollbar is on the left as we are RTL
6345 if (ie7 && L.DomUtil.getStyle(container, 'overflow-y') !== 'hidden' &&
6346 L.DomUtil.getStyle(container, 'overflow') !== 'hidden') {
6351 return pos._subtract(new L.Point(left, top));
6354 getWheelDelta: function (e) {
6359 delta = e.wheelDelta / 120;
6362 delta = -e.detail / 3;
6369 _fakeStop: function (e) {
6370 // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
6371 L.DomEvent._skipEvents[e.type] = true;
6374 _skipped: function (e) {
6375 var skipped = this._skipEvents[e.type];
6376 // reset when checking, as it's only used in map container and propagates outside of the map
6377 this._skipEvents[e.type] = false;
6381 // check if element really left/entered the event target (for mouseenter/mouseleave)
6382 _checkMouse: function (el, e) {
6384 var related = e.relatedTarget;
6386 if (!related) { return true; }
6389 while (related && (related !== el)) {
6390 related = related.parentNode;
6395 return (related !== el);
6398 _getEvent: function () { // evil magic for IE
6399 /*jshint noarg:false */
6400 var e = window.event;
6402 var caller = arguments.callee.caller;
6404 e = caller['arguments'][0];
6405 if (e && window.Event === e.constructor) {
6408 caller = caller.caller;
6414 // this is a horrible workaround for a bug in Android where a single touch triggers two click events
6415 _filterClick: function (e, handler) {
6416 var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
6417 elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
6419 // are they closer together than 1000ms yet more than 100ms?
6420 // Android typically triggers them ~300ms apart while multiple listeners
6421 // on the same event should be triggered far faster;
6422 // or check if click is simulated on the element, and if it is, reject any non-simulated events
6424 if ((elapsed && elapsed > 100 && elapsed < 1000) || (e.target._simulatedClick && !e._simulated)) {
6428 L.DomEvent._lastClick = timeStamp;
6434 L.DomEvent.on = L.DomEvent.addListener;
6435 L.DomEvent.off = L.DomEvent.removeListener;
6439 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
6442 L.Draggable = L.Class.extend({
6443 includes: L.Mixin.Events,
6446 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
6448 mousedown: 'mouseup',
6449 touchstart: 'touchend',
6450 MSPointerDown: 'touchend'
6453 mousedown: 'mousemove',
6454 touchstart: 'touchmove',
6455 MSPointerDown: 'touchmove'
6459 initialize: function (element, dragStartTarget) {
6460 this._element = element;
6461 this._dragStartTarget = dragStartTarget || element;
6464 enable: function () {
6465 if (this._enabled) { return; }
6467 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6468 L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6471 this._enabled = true;
6474 disable: function () {
6475 if (!this._enabled) { return; }
6477 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6478 L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6481 this._enabled = false;
6482 this._moved = false;
6485 _onDown: function (e) {
6486 if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
6489 .stopPropagation(e);
6491 if (L.Draggable._disabled) { return; }
6493 L.DomUtil.disableImageDrag();
6494 L.DomUtil.disableTextSelection();
6496 var first = e.touches ? e.touches[0] : e,
6499 // if touching a link, highlight it
6500 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
6501 L.DomUtil.addClass(el, 'leaflet-active');
6504 this._moved = false;
6506 if (this._moving) { return; }
6508 this._startPoint = new L.Point(first.clientX, first.clientY);
6509 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
6512 .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
6513 .on(document, L.Draggable.END[e.type], this._onUp, this);
6516 _onMove: function (e) {
6517 if (e.touches && e.touches.length > 1) { return; }
6519 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
6520 newPoint = new L.Point(first.clientX, first.clientY),
6521 offset = newPoint.subtract(this._startPoint);
6523 if (!offset.x && !offset.y) { return; }
6525 L.DomEvent.preventDefault(e);
6528 this.fire('dragstart');
6531 this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
6533 if (!L.Browser.touch) {
6534 L.DomUtil.addClass(document.body, 'leaflet-dragging');
6538 this._newPos = this._startPos.add(offset);
6539 this._moving = true;
6541 L.Util.cancelAnimFrame(this._animRequest);
6542 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
6545 _updatePosition: function () {
6546 this.fire('predrag');
6547 L.DomUtil.setPosition(this._element, this._newPos);
6551 _onUp: function () {
6552 if (!L.Browser.touch) {
6553 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
6556 for (var i in L.Draggable.MOVE) {
6558 .off(document, L.Draggable.MOVE[i], this._onMove)
6559 .off(document, L.Draggable.END[i], this._onUp);
6562 L.DomUtil.enableImageDrag();
6563 L.DomUtil.enableTextSelection();
6566 // ensure drag is not fired after dragend
6567 L.Util.cancelAnimFrame(this._animRequest);
6569 this.fire('dragend');
6572 this._moving = false;
6578 L.Handler is a base class for handler classes that are used internally to inject
6579 interaction features like dragging to classes like Map and Marker.
6582 L.Handler = L.Class.extend({
6583 initialize: function (map) {
6587 enable: function () {
6588 if (this._enabled) { return; }
6590 this._enabled = true;
6594 disable: function () {
6595 if (!this._enabled) { return; }
6597 this._enabled = false;
6601 enabled: function () {
6602 return !!this._enabled;
6608 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
6611 L.Map.mergeOptions({
6614 inertia: !L.Browser.android23,
6615 inertiaDeceleration: 3400, // px/s^2
6616 inertiaMaxSpeed: Infinity, // px/s
6617 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
6618 easeLinearity: 0.25,
6620 // TODO refactor, move to CRS
6621 worldCopyJump: false
6624 L.Map.Drag = L.Handler.extend({
6625 addHooks: function () {
6626 if (!this._draggable) {
6627 var map = this._map;
6629 this._draggable = new L.Draggable(map._mapPane, map._container);
6631 this._draggable.on({
6632 'dragstart': this._onDragStart,
6633 'drag': this._onDrag,
6634 'dragend': this._onDragEnd
6637 if (map.options.worldCopyJump) {
6638 this._draggable.on('predrag', this._onPreDrag, this);
6639 map.on('viewreset', this._onViewReset, this);
6641 this._onViewReset();
6644 this._draggable.enable();
6647 removeHooks: function () {
6648 this._draggable.disable();
6651 moved: function () {
6652 return this._draggable && this._draggable._moved;
6655 _onDragStart: function () {
6656 var map = this._map;
6659 map._panAnim.stop();
6666 if (map.options.inertia) {
6667 this._positions = [];
6672 _onDrag: function () {
6673 if (this._map.options.inertia) {
6674 var time = this._lastTime = +new Date(),
6675 pos = this._lastPos = this._draggable._newPos;
6677 this._positions.push(pos);
6678 this._times.push(time);
6680 if (time - this._times[0] > 200) {
6681 this._positions.shift();
6682 this._times.shift();
6691 _onViewReset: function () {
6692 // TODO fix hardcoded Earth values
6693 var pxCenter = this._map.getSize()._divideBy(2),
6694 pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
6696 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6697 this._worldWidth = this._map.project([0, 180]).x;
6700 _onPreDrag: function () {
6701 // TODO refactor to be able to adjust map pane position after zoom
6702 var worldWidth = this._worldWidth,
6703 halfWidth = Math.round(worldWidth / 2),
6704 dx = this._initialWorldOffset,
6705 x = this._draggable._newPos.x,
6706 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6707 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6708 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6710 this._draggable._newPos.x = newX;
6713 _onDragEnd: function () {
6714 var map = this._map,
6715 options = map.options,
6716 delay = +new Date() - this._lastTime,
6718 noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6720 map.fire('dragend');
6723 map.fire('moveend');
6727 var direction = this._lastPos.subtract(this._positions[0]),
6728 duration = (this._lastTime + delay - this._times[0]) / 1000,
6729 ease = options.easeLinearity,
6731 speedVector = direction.multiplyBy(ease / duration),
6732 speed = speedVector.distanceTo([0, 0]),
6734 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6735 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6737 decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6738 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6740 if (!offset.x || !offset.y) {
6741 map.fire('moveend');
6744 L.Util.requestAnimFrame(function () {
6746 duration: decelerationDuration,
6747 easeLinearity: ease,
6756 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6760 * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6763 L.Map.mergeOptions({
6764 doubleClickZoom: true
6767 L.Map.DoubleClickZoom = L.Handler.extend({
6768 addHooks: function () {
6769 this._map.on('dblclick', this._onDoubleClick, this);
6772 removeHooks: function () {
6773 this._map.off('dblclick', this._onDoubleClick, this);
6776 _onDoubleClick: function (e) {
6777 var map = this._map,
6778 zoom = map.getZoom() + 1;
6780 if (map.options.doubleClickZoom === 'center') {
6783 map.setZoomAround(e.containerPoint, zoom);
6788 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
6792 * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
6795 L.Map.mergeOptions({
6796 scrollWheelZoom: true
6799 L.Map.ScrollWheelZoom = L.Handler.extend({
6800 addHooks: function () {
6801 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
6802 L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6806 removeHooks: function () {
6807 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
6808 L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6811 _onWheelScroll: function (e) {
6812 var delta = L.DomEvent.getWheelDelta(e);
6814 this._delta += delta;
6815 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
6817 if (!this._startTime) {
6818 this._startTime = +new Date();
6821 var left = Math.max(40 - (+new Date() - this._startTime), 0);
6823 clearTimeout(this._timer);
6824 this._timer = setTimeout(L.bind(this._performZoom, this), left);
6826 L.DomEvent.preventDefault(e);
6827 L.DomEvent.stopPropagation(e);
6830 _performZoom: function () {
6831 var map = this._map,
6832 delta = this._delta,
6833 zoom = map.getZoom();
6835 delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
6836 delta = Math.max(Math.min(delta, 4), -4);
6837 delta = map._limitZoom(zoom + delta) - zoom;
6840 this._startTime = null;
6842 if (!delta) { return; }
6844 if (map.options.scrollWheelZoom === 'center') {
6845 map.setZoom(zoom + delta);
6847 map.setZoomAround(this._lastMousePos, zoom + delta);
6852 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
6856 * Extends the event handling code with double tap support for mobile browsers.
6859 L.extend(L.DomEvent, {
6861 _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
6862 _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
6864 // inspired by Zepto touch code by Thomas Fuchs
6865 addDoubleTapListener: function (obj, handler, id) {
6871 touchstart = this._touchstart,
6872 touchend = this._touchend,
6873 trackedTouches = [];
6875 function onTouchStart(e) {
6878 if (L.Browser.msTouch) {
6879 trackedTouches.push(e.pointerId);
6880 count = trackedTouches.length;
6882 count = e.touches.length;
6888 var now = Date.now(),
6889 delta = now - (last || now);
6891 touch = e.touches ? e.touches[0] : e;
6892 doubleTap = (delta > 0 && delta <= delay);
6896 function onTouchEnd(e) {
6897 if (L.Browser.msTouch) {
6898 var idx = trackedTouches.indexOf(e.pointerId);
6902 trackedTouches.splice(idx, 1);
6906 if (L.Browser.msTouch) {
6907 // work around .type being readonly with MSPointer* events
6911 // jshint forin:false
6912 for (var i in touch) {
6914 if (typeof prop === 'function') {
6915 newTouch[i] = prop.bind(touch);
6922 touch.type = 'dblclick';
6927 obj[pre + touchstart + id] = onTouchStart;
6928 obj[pre + touchend + id] = onTouchEnd;
6930 // on msTouch we need to listen on the document, otherwise a drag starting on the map and moving off screen
6931 // will not come through to us, so we will lose track of how many touches are ongoing
6932 var endElement = L.Browser.msTouch ? document.documentElement : obj;
6934 obj.addEventListener(touchstart, onTouchStart, false);
6935 endElement.addEventListener(touchend, onTouchEnd, false);
6937 if (L.Browser.msTouch) {
6938 endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
6944 removeDoubleTapListener: function (obj, id) {
6945 var pre = '_leaflet_';
6947 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
6948 (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(
6949 this._touchend, obj[pre + this._touchend + id], false);
6951 if (L.Browser.msTouch) {
6952 document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
6961 * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
6964 L.extend(L.DomEvent, {
6967 _msDocumentListener: false,
6969 // Provides a touch events wrapper for msPointer events.
6970 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
6972 addMsTouchListener: function (obj, type, handler, id) {
6976 return this.addMsTouchListenerStart(obj, type, handler, id);
6978 return this.addMsTouchListenerEnd(obj, type, handler, id);
6980 return this.addMsTouchListenerMove(obj, type, handler, id);
6982 throw 'Unknown touch event type';
6986 addMsTouchListenerStart: function (obj, type, handler, id) {
6987 var pre = '_leaflet_',
6988 touches = this._msTouches;
6990 var cb = function (e) {
6992 var alreadyInArray = false;
6993 for (var i = 0; i < touches.length; i++) {
6994 if (touches[i].pointerId === e.pointerId) {
6995 alreadyInArray = true;
6999 if (!alreadyInArray) {
7003 e.touches = touches.slice();
7004 e.changedTouches = [e];
7009 obj[pre + 'touchstart' + id] = cb;
7010 obj.addEventListener('MSPointerDown', cb, false);
7012 // need to also listen for end events to keep the _msTouches list accurate
7013 // this needs to be on the body and never go away
7014 if (!this._msDocumentListener) {
7015 var internalCb = function (e) {
7016 for (var i = 0; i < touches.length; i++) {
7017 if (touches[i].pointerId === e.pointerId) {
7018 touches.splice(i, 1);
7023 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
7024 document.documentElement.addEventListener('MSPointerUp', internalCb, false);
7025 document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
7027 this._msDocumentListener = true;
7033 addMsTouchListenerMove: function (obj, type, handler, id) {
7034 var pre = '_leaflet_',
7035 touches = this._msTouches;
7039 // don't fire touch moves when mouse isn't down
7040 if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) { return; }
7042 for (var i = 0; i < touches.length; i++) {
7043 if (touches[i].pointerId === e.pointerId) {
7049 e.touches = touches.slice();
7050 e.changedTouches = [e];
7055 obj[pre + 'touchmove' + id] = cb;
7056 obj.addEventListener('MSPointerMove', cb, false);
7061 addMsTouchListenerEnd: function (obj, type, handler, id) {
7062 var pre = '_leaflet_',
7063 touches = this._msTouches;
7065 var cb = function (e) {
7066 for (var i = 0; i < touches.length; i++) {
7067 if (touches[i].pointerId === e.pointerId) {
7068 touches.splice(i, 1);
7073 e.touches = touches.slice();
7074 e.changedTouches = [e];
7079 obj[pre + 'touchend' + id] = cb;
7080 obj.addEventListener('MSPointerUp', cb, false);
7081 obj.addEventListener('MSPointerCancel', cb, false);
7086 removeMsTouchListener: function (obj, type, id) {
7087 var pre = '_leaflet_',
7088 cb = obj[pre + type + id];
7092 obj.removeEventListener('MSPointerDown', cb, false);
7095 obj.removeEventListener('MSPointerMove', cb, false);
7098 obj.removeEventListener('MSPointerUp', cb, false);
7099 obj.removeEventListener('MSPointerCancel', cb, false);
7109 * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
7112 L.Map.mergeOptions({
7113 touchZoom: L.Browser.touch && !L.Browser.android23
7116 L.Map.TouchZoom = L.Handler.extend({
7117 addHooks: function () {
7118 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
7121 removeHooks: function () {
7122 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
7125 _onTouchStart: function (e) {
7126 var map = this._map;
7128 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
7130 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7131 p2 = map.mouseEventToLayerPoint(e.touches[1]),
7132 viewCenter = map._getCenterLayerPoint();
7134 this._startCenter = p1.add(p2)._divideBy(2);
7135 this._startDist = p1.distanceTo(p2);
7137 this._moved = false;
7138 this._zooming = true;
7140 this._centerOffset = viewCenter.subtract(this._startCenter);
7143 map._panAnim.stop();
7147 .on(document, 'touchmove', this._onTouchMove, this)
7148 .on(document, 'touchend', this._onTouchEnd, this);
7150 L.DomEvent.preventDefault(e);
7153 _onTouchMove: function (e) {
7154 var map = this._map;
7156 if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
7158 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7159 p2 = map.mouseEventToLayerPoint(e.touches[1]);
7161 this._scale = p1.distanceTo(p2) / this._startDist;
7162 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
7164 if (this._scale === 1) { return; }
7167 L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
7176 L.Util.cancelAnimFrame(this._animRequest);
7177 this._animRequest = L.Util.requestAnimFrame(
7178 this._updateOnMove, this, true, this._map._container);
7180 L.DomEvent.preventDefault(e);
7183 _updateOnMove: function () {
7184 var map = this._map,
7185 origin = this._getScaleOrigin(),
7186 center = map.layerPointToLatLng(origin),
7187 zoom = map.getScaleZoom(this._scale);
7189 map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta);
7192 _onTouchEnd: function () {
7193 if (!this._moved || !this._zooming) {
7194 this._zooming = false;
7198 var map = this._map;
7200 this._zooming = false;
7201 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
7202 L.Util.cancelAnimFrame(this._animRequest);
7205 .off(document, 'touchmove', this._onTouchMove)
7206 .off(document, 'touchend', this._onTouchEnd);
7208 var origin = this._getScaleOrigin(),
7209 center = map.layerPointToLatLng(origin),
7211 oldZoom = map.getZoom(),
7212 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
7213 roundZoomDelta = (floatZoomDelta > 0 ?
7214 Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
7216 zoom = map._limitZoom(oldZoom + roundZoomDelta),
7217 scale = map.getZoomScale(zoom) / this._scale;
7219 map._animateZoom(center, zoom, origin, scale);
7222 _getScaleOrigin: function () {
7223 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
7224 return this._startCenter.add(centerOffset);
7228 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
7232 * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
7235 L.Map.mergeOptions({
7240 L.Map.Tap = L.Handler.extend({
7241 addHooks: function () {
7242 L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
7245 removeHooks: function () {
7246 L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
7249 _onDown: function (e) {
7250 if (!e.touches) { return; }
7252 L.DomEvent.preventDefault(e);
7254 this._fireClick = true;
7256 // don't simulate click or track longpress if more than 1 touch
7257 if (e.touches.length > 1) {
7258 this._fireClick = false;
7259 clearTimeout(this._holdTimeout);
7263 var first = e.touches[0],
7266 this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
7268 // if touching a link, highlight it
7269 if (el.tagName.toLowerCase() === 'a') {
7270 L.DomUtil.addClass(el, 'leaflet-active');
7273 // simulate long hold but setting a timeout
7274 this._holdTimeout = setTimeout(L.bind(function () {
7275 if (this._isTapValid()) {
7276 this._fireClick = false;
7278 this._simulateEvent('contextmenu', first);
7283 .on(document, 'touchmove', this._onMove, this)
7284 .on(document, 'touchend', this._onUp, this);
7287 _onUp: function (e) {
7288 clearTimeout(this._holdTimeout);
7291 .off(document, 'touchmove', this._onMove, this)
7292 .off(document, 'touchend', this._onUp, this);
7294 if (this._fireClick && e && e.changedTouches) {
7296 var first = e.changedTouches[0],
7299 if (el.tagName.toLowerCase() === 'a') {
7300 L.DomUtil.removeClass(el, 'leaflet-active');
7303 // simulate click if the touch didn't move too much
7304 if (this._isTapValid()) {
7305 this._simulateEvent('click', first);
7310 _isTapValid: function () {
7311 return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
7314 _onMove: function (e) {
7315 var first = e.touches[0];
7316 this._newPos = new L.Point(first.clientX, first.clientY);
7319 _simulateEvent: function (type, e) {
7320 var simulatedEvent = document.createEvent('MouseEvents');
7322 simulatedEvent._simulated = true;
7323 e.target._simulatedClick = true;
7325 simulatedEvent.initMouseEvent(
7326 type, true, true, window, 1,
7327 e.screenX, e.screenY,
7328 e.clientX, e.clientY,
7329 false, false, false, false, 0, null);
7331 e.target.dispatchEvent(simulatedEvent);
7335 if (L.Browser.touch && !L.Browser.msTouch) {
7336 L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
7341 * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
7342 * (zoom to a selected bounding box), enabled by default.
7345 L.Map.mergeOptions({
7349 L.Map.BoxZoom = L.Handler.extend({
7350 initialize: function (map) {
7352 this._container = map._container;
7353 this._pane = map._panes.overlayPane;
7356 addHooks: function () {
7357 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
7360 removeHooks: function () {
7361 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
7364 _onMouseDown: function (e) {
7365 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
7367 L.DomUtil.disableTextSelection();
7368 L.DomUtil.disableImageDrag();
7370 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
7372 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
7373 L.DomUtil.setPosition(this._box, this._startLayerPoint);
7375 //TODO refactor: move cursor to styles
7376 this._container.style.cursor = 'crosshair';
7379 .on(document, 'mousemove', this._onMouseMove, this)
7380 .on(document, 'mouseup', this._onMouseUp, this)
7381 .on(document, 'keydown', this._onKeyDown, this);
7383 this._map.fire('boxzoomstart');
7386 _onMouseMove: function (e) {
7387 var startPoint = this._startLayerPoint,
7390 layerPoint = this._map.mouseEventToLayerPoint(e),
7391 offset = layerPoint.subtract(startPoint),
7393 newPos = new L.Point(
7394 Math.min(layerPoint.x, startPoint.x),
7395 Math.min(layerPoint.y, startPoint.y));
7397 L.DomUtil.setPosition(box, newPos);
7399 // TODO refactor: remove hardcoded 4 pixels
7400 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
7401 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
7404 _finish: function () {
7405 this._pane.removeChild(this._box);
7406 this._container.style.cursor = '';
7408 L.DomUtil.enableTextSelection();
7409 L.DomUtil.enableImageDrag();
7412 .off(document, 'mousemove', this._onMouseMove)
7413 .off(document, 'mouseup', this._onMouseUp)
7414 .off(document, 'keydown', this._onKeyDown);
7417 _onMouseUp: function (e) {
7421 var map = this._map,
7422 layerPoint = map.mouseEventToLayerPoint(e);
7424 if (this._startLayerPoint.equals(layerPoint)) { return; }
7426 var bounds = new L.LatLngBounds(
7427 map.layerPointToLatLng(this._startLayerPoint),
7428 map.layerPointToLatLng(layerPoint));
7430 map.fitBounds(bounds);
7432 map.fire('boxzoomend', {
7433 boxZoomBounds: bounds
7437 _onKeyDown: function (e) {
7438 if (e.keyCode === 27) {
7444 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
7448 * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
7451 L.Map.mergeOptions({
7453 keyboardPanOffset: 80,
7454 keyboardZoomOffset: 1
7457 L.Map.Keyboard = L.Handler.extend({
7464 zoomIn: [187, 107, 61],
7465 zoomOut: [189, 109, 173]
7468 initialize: function (map) {
7471 this._setPanOffset(map.options.keyboardPanOffset);
7472 this._setZoomOffset(map.options.keyboardZoomOffset);
7475 addHooks: function () {
7476 var container = this._map._container;
7478 // make the container focusable by tabbing
7479 if (container.tabIndex === -1) {
7480 container.tabIndex = '0';
7484 .on(container, 'focus', this._onFocus, this)
7485 .on(container, 'blur', this._onBlur, this)
7486 .on(container, 'mousedown', this._onMouseDown, this);
7489 .on('focus', this._addHooks, this)
7490 .on('blur', this._removeHooks, this);
7493 removeHooks: function () {
7494 this._removeHooks();
7496 var container = this._map._container;
7499 .off(container, 'focus', this._onFocus, this)
7500 .off(container, 'blur', this._onBlur, this)
7501 .off(container, 'mousedown', this._onMouseDown, this);
7504 .off('focus', this._addHooks, this)
7505 .off('blur', this._removeHooks, this);
7508 _onMouseDown: function () {
7509 if (this._focused) { return; }
7511 var body = document.body,
7512 docEl = document.documentElement,
7513 top = body.scrollTop || docEl.scrollTop,
7514 left = body.scrollTop || docEl.scrollLeft;
7516 this._map._container.focus();
7518 window.scrollTo(left, top);
7521 _onFocus: function () {
7522 this._focused = true;
7523 this._map.fire('focus');
7526 _onBlur: function () {
7527 this._focused = false;
7528 this._map.fire('blur');
7531 _setPanOffset: function (pan) {
7532 var keys = this._panKeys = {},
7533 codes = this.keyCodes,
7536 for (i = 0, len = codes.left.length; i < len; i++) {
7537 keys[codes.left[i]] = [-1 * pan, 0];
7539 for (i = 0, len = codes.right.length; i < len; i++) {
7540 keys[codes.right[i]] = [pan, 0];
7542 for (i = 0, len = codes.down.length; i < len; i++) {
7543 keys[codes.down[i]] = [0, pan];
7545 for (i = 0, len = codes.up.length; i < len; i++) {
7546 keys[codes.up[i]] = [0, -1 * pan];
7550 _setZoomOffset: function (zoom) {
7551 var keys = this._zoomKeys = {},
7552 codes = this.keyCodes,
7555 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
7556 keys[codes.zoomIn[i]] = zoom;
7558 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
7559 keys[codes.zoomOut[i]] = -zoom;
7563 _addHooks: function () {
7564 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
7567 _removeHooks: function () {
7568 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
7571 _onKeyDown: function (e) {
7572 var key = e.keyCode,
7575 if (key in this._panKeys) {
7577 if (map._panAnim && map._panAnim._inProgress) { return; }
7579 map.panBy(this._panKeys[key]);
7581 if (map.options.maxBounds) {
7582 map.panInsideBounds(map.options.maxBounds);
7585 } else if (key in this._zoomKeys) {
7586 map.setZoom(map.getZoom() + this._zoomKeys[key]);
7596 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
7600 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
7603 L.Handler.MarkerDrag = L.Handler.extend({
7604 initialize: function (marker) {
7605 this._marker = marker;
7608 addHooks: function () {
7609 var icon = this._marker._icon;
7610 if (!this._draggable) {
7611 this._draggable = new L.Draggable(icon, icon);
7615 .on('dragstart', this._onDragStart, this)
7616 .on('drag', this._onDrag, this)
7617 .on('dragend', this._onDragEnd, this);
7618 this._draggable.enable();
7621 removeHooks: function () {
7623 .off('dragstart', this._onDragStart, this)
7624 .off('drag', this._onDrag, this)
7625 .off('dragend', this._onDragEnd, this);
7627 this._draggable.disable();
7630 moved: function () {
7631 return this._draggable && this._draggable._moved;
7634 _onDragStart: function () {
7641 _onDrag: function () {
7642 var marker = this._marker,
7643 shadow = marker._shadow,
7644 iconPos = L.DomUtil.getPosition(marker._icon),
7645 latlng = marker._map.layerPointToLatLng(iconPos);
7647 // update shadow position
7649 L.DomUtil.setPosition(shadow, iconPos);
7652 marker._latlng = latlng;
7655 .fire('move', {latlng: latlng})
7659 _onDragEnd: function () {
7668 * L.Control is a base class for implementing map controls. Handles positioning.
7669 * All other controls extend from this class.
7672 L.Control = L.Class.extend({
7674 position: 'topright'
7677 initialize: function (options) {
7678 L.setOptions(this, options);
7681 getPosition: function () {
7682 return this.options.position;
7685 setPosition: function (position) {
7686 var map = this._map;
7689 map.removeControl(this);
7692 this.options.position = position;
7695 map.addControl(this);
7701 getContainer: function () {
7702 return this._container;
7705 addTo: function (map) {
7708 var container = this._container = this.onAdd(map),
7709 pos = this.getPosition(),
7710 corner = map._controlCorners[pos];
7712 L.DomUtil.addClass(container, 'leaflet-control');
7714 if (pos.indexOf('bottom') !== -1) {
7715 corner.insertBefore(container, corner.firstChild);
7717 corner.appendChild(container);
7723 removeFrom: function (map) {
7724 var pos = this.getPosition(),
7725 corner = map._controlCorners[pos];
7727 corner.removeChild(this._container);
7730 if (this.onRemove) {
7738 L.control = function (options) {
7739 return new L.Control(options);
7743 // adds control-related methods to L.Map
7746 addControl: function (control) {
7747 control.addTo(this);
7751 removeControl: function (control) {
7752 control.removeFrom(this);
7756 _initControlPos: function () {
7757 var corners = this._controlCorners = {},
7759 container = this._controlContainer =
7760 L.DomUtil.create('div', l + 'control-container', this._container);
7762 function createCorner(vSide, hSide) {
7763 var className = l + vSide + ' ' + l + hSide;
7765 corners[vSide + hSide] = L.DomUtil.create('div', className, container);
7768 createCorner('top', 'left');
7769 createCorner('top', 'right');
7770 createCorner('bottom', 'left');
7771 createCorner('bottom', 'right');
7774 _clearControlPos: function () {
7775 this._container.removeChild(this._controlContainer);
7781 * L.Control.Zoom is used for the default zoom buttons on the map.
7784 L.Control.Zoom = L.Control.extend({
7789 onAdd: function (map) {
7790 var zoomName = 'leaflet-control-zoom',
7791 container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
7795 this._zoomInButton = this._createButton(
7796 '+', 'Zoom in', zoomName + '-in', container, this._zoomIn, this);
7797 this._zoomOutButton = this._createButton(
7798 '-', 'Zoom out', zoomName + '-out', container, this._zoomOut, this);
7800 map.on('zoomend zoomlevelschange', this._updateDisabled, this);
7805 onRemove: function (map) {
7806 map.off('zoomend zoomlevelschange', this._updateDisabled, this);
7809 _zoomIn: function (e) {
7810 this._map.zoomIn(e.shiftKey ? 3 : 1);
7813 _zoomOut: function (e) {
7814 this._map.zoomOut(e.shiftKey ? 3 : 1);
7817 _createButton: function (html, title, className, container, fn, context) {
7818 var link = L.DomUtil.create('a', className, container);
7819 link.innerHTML = html;
7823 var stop = L.DomEvent.stopPropagation;
7826 .on(link, 'click', stop)
7827 .on(link, 'mousedown', stop)
7828 .on(link, 'dblclick', stop)
7829 .on(link, 'click', L.DomEvent.preventDefault)
7830 .on(link, 'click', fn, context);
7835 _updateDisabled: function () {
7836 var map = this._map,
7837 className = 'leaflet-disabled';
7839 L.DomUtil.removeClass(this._zoomInButton, className);
7840 L.DomUtil.removeClass(this._zoomOutButton, className);
7842 if (map._zoom === map.getMinZoom()) {
7843 L.DomUtil.addClass(this._zoomOutButton, className);
7845 if (map._zoom === map.getMaxZoom()) {
7846 L.DomUtil.addClass(this._zoomInButton, className);
7851 L.Map.mergeOptions({
7855 L.Map.addInitHook(function () {
7856 if (this.options.zoomControl) {
7857 this.zoomControl = new L.Control.Zoom();
7858 this.addControl(this.zoomControl);
7862 L.control.zoom = function (options) {
7863 return new L.Control.Zoom(options);
7869 * L.Control.Attribution is used for displaying attribution on the map (added by default).
7872 L.Control.Attribution = L.Control.extend({
7874 position: 'bottomright',
7875 prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
7878 initialize: function (options) {
7879 L.setOptions(this, options);
7881 this._attributions = {};
7884 onAdd: function (map) {
7885 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
7886 L.DomEvent.disableClickPropagation(this._container);
7889 .on('layeradd', this._onLayerAdd, this)
7890 .on('layerremove', this._onLayerRemove, this);
7894 return this._container;
7897 onRemove: function (map) {
7899 .off('layeradd', this._onLayerAdd)
7900 .off('layerremove', this._onLayerRemove);
7904 setPrefix: function (prefix) {
7905 this.options.prefix = prefix;
7910 addAttribution: function (text) {
7911 if (!text) { return; }
7913 if (!this._attributions[text]) {
7914 this._attributions[text] = 0;
7916 this._attributions[text]++;
7923 removeAttribution: function (text) {
7924 if (!text) { return; }
7926 if (this._attributions[text]) {
7927 this._attributions[text]--;
7934 _update: function () {
7935 if (!this._map) { return; }
7939 for (var i in this._attributions) {
7940 if (this._attributions[i]) {
7945 var prefixAndAttribs = [];
7947 if (this.options.prefix) {
7948 prefixAndAttribs.push(this.options.prefix);
7950 if (attribs.length) {
7951 prefixAndAttribs.push(attribs.join(', '));
7954 this._container.innerHTML = prefixAndAttribs.join(' | ');
7957 _onLayerAdd: function (e) {
7958 if (e.layer.getAttribution) {
7959 this.addAttribution(e.layer.getAttribution());
7963 _onLayerRemove: function (e) {
7964 if (e.layer.getAttribution) {
7965 this.removeAttribution(e.layer.getAttribution());
7970 L.Map.mergeOptions({
7971 attributionControl: true
7974 L.Map.addInitHook(function () {
7975 if (this.options.attributionControl) {
7976 this.attributionControl = (new L.Control.Attribution()).addTo(this);
7980 L.control.attribution = function (options) {
7981 return new L.Control.Attribution(options);
7986 * L.Control.Scale is used for displaying metric/imperial scale on the map.
7989 L.Control.Scale = L.Control.extend({
7991 position: 'bottomleft',
7995 updateWhenIdle: false
7998 onAdd: function (map) {
8001 var className = 'leaflet-control-scale',
8002 container = L.DomUtil.create('div', className),
8003 options = this.options;
8005 this._addScales(options, className, container);
8007 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8008 map.whenReady(this._update, this);
8013 onRemove: function (map) {
8014 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8017 _addScales: function (options, className, container) {
8018 if (options.metric) {
8019 this._mScale = L.DomUtil.create('div', className + '-line', container);
8021 if (options.imperial) {
8022 this._iScale = L.DomUtil.create('div', className + '-line', container);
8026 _update: function () {
8027 var bounds = this._map.getBounds(),
8028 centerLat = bounds.getCenter().lat,
8029 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
8030 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
8032 size = this._map.getSize(),
8033 options = this.options,
8037 maxMeters = dist * (options.maxWidth / size.x);
8040 this._updateScales(options, maxMeters);
8043 _updateScales: function (options, maxMeters) {
8044 if (options.metric && maxMeters) {
8045 this._updateMetric(maxMeters);
8048 if (options.imperial && maxMeters) {
8049 this._updateImperial(maxMeters);
8053 _updateMetric: function (maxMeters) {
8054 var meters = this._getRoundNum(maxMeters);
8056 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
8057 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
8060 _updateImperial: function (maxMeters) {
8061 var maxFeet = maxMeters * 3.2808399,
8062 scale = this._iScale,
8063 maxMiles, miles, feet;
8065 if (maxFeet > 5280) {
8066 maxMiles = maxFeet / 5280;
8067 miles = this._getRoundNum(maxMiles);
8069 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
8070 scale.innerHTML = miles + ' mi';
8073 feet = this._getRoundNum(maxFeet);
8075 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
8076 scale.innerHTML = feet + ' ft';
8080 _getScaleWidth: function (ratio) {
8081 return Math.round(this.options.maxWidth * ratio) - 10;
8084 _getRoundNum: function (num) {
8085 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
8088 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
8094 L.control.scale = function (options) {
8095 return new L.Control.Scale(options);
8100 * L.Control.Layers is a control to allow users to switch between different layers on the map.
8103 L.Control.Layers = L.Control.extend({
8106 position: 'topright',
8110 initialize: function (baseLayers, overlays, options) {
8111 L.setOptions(this, options);
8114 this._lastZIndex = 0;
8115 this._handlingClick = false;
8117 for (var i in baseLayers) {
8118 this._addLayer(baseLayers[i], i);
8121 for (i in overlays) {
8122 this._addLayer(overlays[i], i, true);
8126 onAdd: function (map) {
8131 .on('layeradd', this._onLayerChange, this)
8132 .on('layerremove', this._onLayerChange, this);
8134 return this._container;
8137 onRemove: function (map) {
8139 .off('layeradd', this._onLayerChange)
8140 .off('layerremove', this._onLayerChange);
8143 addBaseLayer: function (layer, name) {
8144 this._addLayer(layer, name);
8149 addOverlay: function (layer, name) {
8150 this._addLayer(layer, name, true);
8155 removeLayer: function (layer) {
8156 var id = L.stamp(layer);
8157 delete this._layers[id];
8162 _initLayout: function () {
8163 var className = 'leaflet-control-layers',
8164 container = this._container = L.DomUtil.create('div', className);
8166 //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
8167 container.setAttribute('aria-haspopup', true);
8169 if (!L.Browser.touch) {
8170 L.DomEvent.disableClickPropagation(container);
8171 L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
8173 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
8176 var form = this._form = L.DomUtil.create('form', className + '-list');
8178 if (this.options.collapsed) {
8179 if (!L.Browser.android) {
8181 .on(container, 'mouseover', this._expand, this)
8182 .on(container, 'mouseout', this._collapse, this);
8184 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
8186 link.title = 'Layers';
8188 if (L.Browser.touch) {
8190 .on(link, 'click', L.DomEvent.stop)
8191 .on(link, 'click', this._expand, this);
8194 L.DomEvent.on(link, 'focus', this._expand, this);
8197 this._map.on('click', this._collapse, this);
8198 // TODO keyboard accessibility
8203 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
8204 this._separator = L.DomUtil.create('div', className + '-separator', form);
8205 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
8207 container.appendChild(form);
8210 _addLayer: function (layer, name, overlay) {
8211 var id = L.stamp(layer);
8213 this._layers[id] = {
8219 if (this.options.autoZIndex && layer.setZIndex) {
8221 layer.setZIndex(this._lastZIndex);
8225 _update: function () {
8226 if (!this._container) {
8230 this._baseLayersList.innerHTML = '';
8231 this._overlaysList.innerHTML = '';
8233 var baseLayersPresent = false,
8234 overlaysPresent = false,
8237 for (i in this._layers) {
8238 obj = this._layers[i];
8240 overlaysPresent = overlaysPresent || obj.overlay;
8241 baseLayersPresent = baseLayersPresent || !obj.overlay;
8244 this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
8247 _onLayerChange: function (e) {
8248 var obj = this._layers[L.stamp(e.layer)];
8250 if (!obj) { return; }
8252 if (!this._handlingClick) {
8256 var type = obj.overlay ?
8257 (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
8258 (e.type === 'layeradd' ? 'baselayerchange' : null);
8261 this._map.fire(type, obj);
8265 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
8266 _createRadioElement: function (name, checked) {
8268 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
8270 radioHtml += ' checked="checked"';
8274 var radioFragment = document.createElement('div');
8275 radioFragment.innerHTML = radioHtml;
8277 return radioFragment.firstChild;
8280 _addItem: function (obj) {
8281 var label = document.createElement('label'),
8283 checked = this._map.hasLayer(obj.layer);
8286 input = document.createElement('input');
8287 input.type = 'checkbox';
8288 input.className = 'leaflet-control-layers-selector';
8289 input.defaultChecked = checked;
8291 input = this._createRadioElement('leaflet-base-layers', checked);
8294 input.layerId = L.stamp(obj.layer);
8296 L.DomEvent.on(input, 'click', this._onInputClick, this);
8298 var name = document.createElement('span');
8299 name.innerHTML = ' ' + obj.name;
8301 label.appendChild(input);
8302 label.appendChild(name);
8304 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
8305 container.appendChild(label);
8310 _onInputClick: function () {
8312 inputs = this._form.getElementsByTagName('input'),
8313 inputsLen = inputs.length;
8315 this._handlingClick = true;
8317 for (i = 0; i < inputsLen; i++) {
8319 obj = this._layers[input.layerId];
8321 if (input.checked && !this._map.hasLayer(obj.layer)) {
8322 this._map.addLayer(obj.layer);
8324 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
8325 this._map.removeLayer(obj.layer);
8329 this._handlingClick = false;
8332 _expand: function () {
8333 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
8336 _collapse: function () {
8337 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
8341 L.control.layers = function (baseLayers, overlays, options) {
8342 return new L.Control.Layers(baseLayers, overlays, options);
8347 * L.PosAnimation is used by Leaflet internally for pan animations.
8350 L.PosAnimation = L.Class.extend({
8351 includes: L.Mixin.Events,
8353 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8357 this._inProgress = true;
8358 this._newPos = newPos;
8362 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
8363 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
8365 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8366 L.DomUtil.setPosition(el, newPos);
8368 // toggle reflow, Chrome flickers for some reason if you don't do this
8369 L.Util.falseFn(el.offsetWidth);
8371 // there's no native way to track value updates of transitioned properties, so we imitate this
8372 this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
8376 if (!this._inProgress) { return; }
8378 // if we just removed the transition property, the element would jump to its final position,
8379 // so we need to make it stay at the current position
8381 L.DomUtil.setPosition(this._el, this._getPos());
8382 this._onTransitionEnd();
8383 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
8386 _onStep: function () {
8387 var stepPos = this._getPos();
8389 this._onTransitionEnd();
8392 // jshint camelcase: false
8393 // make L.DomUtil.getPosition return intermediate position value during animation
8394 this._el._leaflet_pos = stepPos;
8399 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
8400 // we need to parse computed style (in case of transform it returns matrix string)
8402 _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
8404 _getPos: function () {
8405 var left, top, matches,
8407 style = window.getComputedStyle(el);
8409 if (L.Browser.any3d) {
8410 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
8411 if (!matches) { return; }
8412 left = parseFloat(matches[1]);
8413 top = parseFloat(matches[2]);
8415 left = parseFloat(style.left);
8416 top = parseFloat(style.top);
8419 return new L.Point(left, top, true);
8422 _onTransitionEnd: function () {
8423 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8425 if (!this._inProgress) { return; }
8426 this._inProgress = false;
8428 this._el.style[L.DomUtil.TRANSITION] = '';
8430 // jshint camelcase: false
8431 // make sure L.DomUtil.getPosition returns the final position value after animation
8432 this._el._leaflet_pos = this._newPos;
8434 clearInterval(this._stepTimer);
8436 this.fire('step').fire('end');
8443 * Extends L.Map to handle panning animations.
8448 setView: function (center, zoom, options) {
8450 zoom = this._limitZoom(zoom);
8451 center = L.latLng(center);
8452 options = options || {};
8454 if (this._panAnim) {
8455 this._panAnim.stop();
8458 if (this._loaded && !options.reset && options !== true) {
8460 if (options.animate !== undefined) {
8461 options.zoom = L.extend({animate: options.animate}, options.zoom);
8462 options.pan = L.extend({animate: options.animate}, options.pan);
8465 // try animating pan or zoom
8466 var animated = (this._zoom !== zoom) ?
8467 this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
8468 this._tryAnimatedPan(center, options.pan);
8471 // prevent resize handler call, the view will refresh after animation anyway
8472 clearTimeout(this._sizeTimer);
8477 // animation didn't start, just reset the map view
8478 this._resetView(center, zoom);
8483 panBy: function (offset, options) {
8484 offset = L.point(offset).round();
8485 options = options || {};
8487 if (!offset.x && !offset.y) {
8491 if (!this._panAnim) {
8492 this._panAnim = new L.PosAnimation();
8495 'step': this._onPanTransitionStep,
8496 'end': this._onPanTransitionEnd
8500 // don't fire movestart if animating inertia
8501 if (!options.noMoveStart) {
8502 this.fire('movestart');
8505 // animate pan unless animate: false specified
8506 if (options.animate !== false) {
8507 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
8509 var newPos = this._getMapPanePos().subtract(offset);
8510 this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
8512 this._rawPanBy(offset);
8513 this.fire('move').fire('moveend');
8519 _onPanTransitionStep: function () {
8523 _onPanTransitionEnd: function () {
8524 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
8525 this.fire('moveend');
8528 _tryAnimatedPan: function (center, options) {
8529 // difference between the new and current centers in pixels
8530 var offset = this._getCenterOffset(center)._floor();
8532 // don't animate too far unless animate: true specified in options
8533 if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
8535 this.panBy(offset, options);
8543 * L.PosAnimation fallback implementation that powers Leaflet pan animations
8544 * in browsers that don't support CSS3 Transitions.
8547 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8549 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8553 this._inProgress = true;
8554 this._duration = duration || 0.25;
8555 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8557 this._startPos = L.DomUtil.getPosition(el);
8558 this._offset = newPos.subtract(this._startPos);
8559 this._startTime = +new Date();
8567 if (!this._inProgress) { return; }
8573 _animate: function () {
8575 this._animId = L.Util.requestAnimFrame(this._animate, this);
8579 _step: function () {
8580 var elapsed = (+new Date()) - this._startTime,
8581 duration = this._duration * 1000;
8583 if (elapsed < duration) {
8584 this._runFrame(this._easeOut(elapsed / duration));
8591 _runFrame: function (progress) {
8592 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8593 L.DomUtil.setPosition(this._el, pos);
8598 _complete: function () {
8599 L.Util.cancelAnimFrame(this._animId);
8601 this._inProgress = false;
8605 _easeOut: function (t) {
8606 return 1 - Math.pow(1 - t, this._easeOutPower);
8612 * Extends L.Map to handle zoom animations.
8615 L.Map.mergeOptions({
8616 zoomAnimation: true,
8617 zoomAnimationThreshold: 4
8620 if (L.DomUtil.TRANSITION) {
8622 L.Map.addInitHook(function () {
8623 // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
8624 this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
8625 L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
8627 // zoom transitions run with the same duration for all layers, so if one of transitionend events
8628 // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
8629 if (this._zoomAnimated) {
8630 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8635 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8637 _catchTransitionEnd: function () {
8638 if (this._animatingZoom) {
8639 this._onZoomTransitionEnd();
8643 _nothingToAnimate: function () {
8644 return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
8647 _tryAnimatedZoom: function (center, zoom, options) {
8649 if (this._animatingZoom) { return true; }
8651 options = options || {};
8653 // don't animate if disabled, not supported or zoom difference is too large
8654 if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
8655 Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
8657 // offset is the pixel coords of the zoom origin relative to the current center
8658 var scale = this.getZoomScale(zoom),
8659 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
8660 origin = this._getCenterLayerPoint()._add(offset);
8662 // don't animate if the zoom origin isn't within one screen from the current center, unless forced
8663 if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
8669 this._animateZoom(center, zoom, origin, scale, null, true);
8674 _animateZoom: function (center, zoom, origin, scale, delta, backwards) {
8676 this._animatingZoom = true;
8678 // put transform transition on all layers with leaflet-zoom-animated class
8679 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8681 // remember what center/zoom to set after animation
8682 this._animateToCenter = center;
8683 this._animateToZoom = zoom;
8685 // disable any dragging during animation
8687 L.Draggable._disabled = true;
8690 this.fire('zoomanim', {
8696 backwards: backwards
8700 _onZoomTransitionEnd: function () {
8702 this._animatingZoom = false;
8704 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8706 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8709 L.Draggable._disabled = false;
8716 Zoom animation logic for L.TileLayer.
8719 L.TileLayer.include({
8720 _animateZoom: function (e) {
8721 if (!this._animating) {
8722 this._animating = true;
8723 this._prepareBgBuffer();
8726 var bg = this._bgBuffer,
8727 transform = L.DomUtil.TRANSFORM,
8728 initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
8729 scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
8731 bg.style[transform] = e.backwards ?
8732 scaleStr + ' ' + initialTransform :
8733 initialTransform + ' ' + scaleStr;
8736 _endZoomAnim: function () {
8737 var front = this._tileContainer,
8738 bg = this._bgBuffer;
8740 front.style.visibility = '';
8741 front.parentNode.appendChild(front); // Bring to fore
8744 L.Util.falseFn(bg.offsetWidth);
8746 this._animating = false;
8749 _clearBgBuffer: function () {
8750 var map = this._map;
8752 if (map && !map._animatingZoom && !map.touchZoom._zooming) {
8753 this._bgBuffer.innerHTML = '';
8754 this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
8758 _prepareBgBuffer: function () {
8760 var front = this._tileContainer,
8761 bg = this._bgBuffer;
8763 // if foreground layer doesn't have many tiles but bg layer does,
8764 // keep the existing bg layer and just zoom it some more
8766 var bgLoaded = this._getLoadedTilesPercentage(bg),
8767 frontLoaded = this._getLoadedTilesPercentage(front);
8769 if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
8771 front.style.visibility = 'hidden';
8772 this._stopLoadingImages(front);
8776 // prepare the buffer to become the front tile pane
8777 bg.style.visibility = 'hidden';
8778 bg.style[L.DomUtil.TRANSFORM] = '';
8780 // switch out the current layer to be the new bg layer (and vice-versa)
8781 this._tileContainer = bg;
8782 bg = this._bgBuffer = front;
8784 this._stopLoadingImages(bg);
8786 //prevent bg buffer from clearing right after zoom
8787 clearTimeout(this._clearBgBufferTimer);
8790 _getLoadedTilesPercentage: function (container) {
8791 var tiles = container.getElementsByTagName('img'),
8794 for (i = 0, len = tiles.length; i < len; i++) {
8795 if (tiles[i].complete) {
8802 // stops loading all tiles in the background layer
8803 _stopLoadingImages: function (container) {
8804 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
8807 for (i = 0, len = tiles.length; i < len; i++) {
8810 if (!tile.complete) {
8811 tile.onload = L.Util.falseFn;
8812 tile.onerror = L.Util.falseFn;
8813 tile.src = L.Util.emptyImageUrl;
8815 tile.parentNode.removeChild(tile);
8823 * Provides L.Map with convenient shortcuts for using browser geolocation features.
8827 _defaultLocateOptions: {
8833 enableHighAccuracy: false
8836 locate: function (/*Object*/ options) {
8838 options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
8840 if (!navigator.geolocation) {
8841 this._handleGeolocationError({
8843 message: 'Geolocation not supported.'
8848 var onResponse = L.bind(this._handleGeolocationResponse, this),
8849 onError = L.bind(this._handleGeolocationError, this);
8851 if (options.watch) {
8852 this._locationWatchId =
8853 navigator.geolocation.watchPosition(onResponse, onError, options);
8855 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
8860 stopLocate: function () {
8861 if (navigator.geolocation) {
8862 navigator.geolocation.clearWatch(this._locationWatchId);
8864 if (this._locateOptions) {
8865 this._locateOptions.setView = false;
8870 _handleGeolocationError: function (error) {
8872 message = error.message ||
8873 (c === 1 ? 'permission denied' :
8874 (c === 2 ? 'position unavailable' : 'timeout'));
8876 if (this._locateOptions.setView && !this._loaded) {
8880 this.fire('locationerror', {
8882 message: 'Geolocation error: ' + message + '.'
8886 _handleGeolocationResponse: function (pos) {
8887 var lat = pos.coords.latitude,
8888 lng = pos.coords.longitude,
8889 latlng = new L.LatLng(lat, lng),
8891 latAccuracy = 180 * pos.coords.accuracy / 40075017,
8892 lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
8894 bounds = L.latLngBounds(
8895 [lat - latAccuracy, lng - lngAccuracy],
8896 [lat + latAccuracy, lng + lngAccuracy]),
8898 options = this._locateOptions;
8900 if (options.setView) {
8901 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
8902 this.setView(latlng, zoom);
8910 for (var i in pos.coords) {
8911 if (typeof pos.coords[i] === 'number') {
8912 data[i] = pos.coords[i];
8916 this.fire('locationfound', data);
8921 }(window, document));