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 this; }
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);
1776 this.fire('move').fire('moveend');
1779 return this.fire('resize', {
1785 // TODO handler.addTo
1786 addHandler: function (name, HandlerClass) {
1787 if (!HandlerClass) { return; }
1789 var handler = this[name] = new HandlerClass(this);
1791 this._handlers.push(handler);
1793 if (this.options[name]) {
1800 remove: function () {
1802 this.fire('unload');
1805 this._initEvents('off');
1807 delete this._container._leaflet;
1810 if (this._clearControlPos) {
1811 this._clearControlPos();
1814 this._clearHandlers();
1820 // public methods for getting map state
1822 getCenter: function () { // (Boolean) -> LatLng
1823 this._checkIfLoaded();
1825 if (this._initialCenter && !this._moved()) {
1826 return this._initialCenter;
1828 return this.layerPointToLatLng(this._getCenterLayerPoint());
1831 getZoom: function () {
1835 getBounds: function () {
1836 var bounds = this.getPixelBounds(),
1837 sw = this.unproject(bounds.getBottomLeft()),
1838 ne = this.unproject(bounds.getTopRight());
1840 return new L.LatLngBounds(sw, ne);
1843 getMinZoom: function () {
1844 var z1 = this._layersMinZoom === undefined ? -Infinity : this._layersMinZoom,
1845 z2 = this._boundsMinZoom === undefined ? -Infinity : this._boundsMinZoom;
1846 return this.options.minZoom === undefined ? Math.max(z1, z2) : this.options.minZoom;
1849 getMaxZoom: function () {
1850 return this.options.maxZoom === undefined ?
1851 (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
1852 this.options.maxZoom;
1855 getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1856 bounds = L.latLngBounds(bounds);
1858 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1859 maxZoom = this.getMaxZoom(),
1860 size = this.getSize(),
1862 nw = bounds.getNorthWest(),
1863 se = bounds.getSouthEast(),
1865 zoomNotFound = true,
1868 padding = L.point(padding || [0, 0]);
1872 boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1873 zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1875 } while (zoomNotFound && zoom <= maxZoom);
1877 if (zoomNotFound && inside) {
1881 return inside ? zoom : zoom - 1;
1884 getSize: function () {
1885 if (!this._size || this._sizeChanged) {
1886 this._size = new L.Point(
1887 this._container.clientWidth,
1888 this._container.clientHeight);
1890 this._sizeChanged = false;
1892 return this._size.clone();
1895 getPixelBounds: function () {
1896 var topLeftPoint = this._getTopLeftPoint();
1897 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1900 getPixelOrigin: function () {
1901 this._checkIfLoaded();
1902 return this._initialTopLeftPoint;
1905 getPanes: function () {
1909 getContainer: function () {
1910 return this._container;
1914 // TODO replace with universal implementation after refactoring projections
1916 getZoomScale: function (toZoom) {
1917 var crs = this.options.crs;
1918 return crs.scale(toZoom) / crs.scale(this._zoom);
1921 getScaleZoom: function (scale) {
1922 return this._zoom + (Math.log(scale) / Math.LN2);
1926 // conversion methods
1928 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1929 zoom = zoom === undefined ? this._zoom : zoom;
1930 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1933 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1934 zoom = zoom === undefined ? this._zoom : zoom;
1935 return this.options.crs.pointToLatLng(L.point(point), zoom);
1938 layerPointToLatLng: function (point) { // (Point)
1939 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1940 return this.unproject(projectedPoint);
1943 latLngToLayerPoint: function (latlng) { // (LatLng)
1944 var projectedPoint = this.project(L.latLng(latlng))._round();
1945 return projectedPoint._subtract(this.getPixelOrigin());
1948 containerPointToLayerPoint: function (point) { // (Point)
1949 return L.point(point).subtract(this._getMapPanePos());
1952 layerPointToContainerPoint: function (point) { // (Point)
1953 return L.point(point).add(this._getMapPanePos());
1956 containerPointToLatLng: function (point) {
1957 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1958 return this.layerPointToLatLng(layerPoint);
1961 latLngToContainerPoint: function (latlng) {
1962 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1965 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1966 return L.DomEvent.getMousePosition(e, this._container);
1969 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1970 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1973 mouseEventToLatLng: function (e) { // (MouseEvent)
1974 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1978 // map initialization methods
1980 _initContainer: function (id) {
1981 var container = this._container = L.DomUtil.get(id);
1984 throw new Error('Map container not found.');
1985 } else if (container._leaflet) {
1986 throw new Error('Map container is already initialized.');
1989 container._leaflet = true;
1992 _initLayout: function () {
1993 var container = this._container;
1995 L.DomUtil.addClass(container, 'leaflet-container' +
1996 (L.Browser.touch ? ' leaflet-touch' : '') +
1997 (L.Browser.retina ? ' leaflet-retina' : '') +
1998 (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
2000 var position = L.DomUtil.getStyle(container, 'position');
2002 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
2003 container.style.position = 'relative';
2008 if (this._initControlPos) {
2009 this._initControlPos();
2013 _initPanes: function () {
2014 var panes = this._panes = {};
2016 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2018 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2019 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2020 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2021 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2022 panes.markerPane = this._createPane('leaflet-marker-pane');
2023 panes.popupPane = this._createPane('leaflet-popup-pane');
2025 var zoomHide = ' leaflet-zoom-hide';
2027 if (!this.options.markerZoomAnimation) {
2028 L.DomUtil.addClass(panes.markerPane, zoomHide);
2029 L.DomUtil.addClass(panes.shadowPane, zoomHide);
2030 L.DomUtil.addClass(panes.popupPane, zoomHide);
2034 _createPane: function (className, container) {
2035 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2038 _clearPanes: function () {
2039 this._container.removeChild(this._mapPane);
2042 _addLayers: function (layers) {
2043 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2045 for (var i = 0, len = layers.length; i < len; i++) {
2046 this.addLayer(layers[i]);
2051 // private methods that modify map state
2053 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2055 var zoomChanged = (this._zoom !== zoom);
2057 if (!afterZoomAnim) {
2058 this.fire('movestart');
2061 this.fire('zoomstart');
2066 this._initialCenter = center;
2068 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2070 if (!preserveMapOffset) {
2071 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2073 this._initialTopLeftPoint._add(this._getMapPanePos());
2076 this._tileLayersToLoad = this._tileLayersNum;
2078 var loading = !this._loaded;
2079 this._loaded = true;
2083 this.eachLayer(this._layerAdd, this);
2086 this.fire('viewreset', {hard: !preserveMapOffset});
2090 if (zoomChanged || afterZoomAnim) {
2091 this.fire('zoomend');
2094 this.fire('moveend', {hard: !preserveMapOffset});
2097 _rawPanBy: function (offset) {
2098 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2101 _getZoomSpan: function () {
2102 return this.getMaxZoom() - this.getMinZoom();
2105 _updateZoomLevels: function () {
2108 maxZoom = -Infinity,
2109 oldZoomSpan = this._getZoomSpan();
2111 for (i in this._zoomBoundLayers) {
2112 var layer = this._zoomBoundLayers[i];
2113 if (!isNaN(layer.options.minZoom)) {
2114 minZoom = Math.min(minZoom, layer.options.minZoom);
2116 if (!isNaN(layer.options.maxZoom)) {
2117 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2121 if (i === undefined) { // we have no tilelayers
2122 this._layersMaxZoom = this._layersMinZoom = undefined;
2124 this._layersMaxZoom = maxZoom;
2125 this._layersMinZoom = minZoom;
2128 if (oldZoomSpan !== this._getZoomSpan()) {
2129 this.fire('zoomlevelschange');
2133 _panInsideMaxBounds: function () {
2134 this.panInsideBounds(this.options.maxBounds);
2137 _checkIfLoaded: function () {
2138 if (!this._loaded) {
2139 throw new Error('Set map center and zoom first.');
2145 _initEvents: function (onOff) {
2146 if (!L.DomEvent) { return; }
2148 onOff = onOff || 'on';
2150 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2152 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2153 'mouseleave', 'mousemove', 'contextmenu'],
2156 for (i = 0, len = events.length; i < len; i++) {
2157 L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2160 if (this.options.trackResize) {
2161 L.DomEvent[onOff](window, 'resize', this._onResize, this);
2165 _onResize: function () {
2166 L.Util.cancelAnimFrame(this._resizeRequest);
2167 this._resizeRequest = L.Util.requestAnimFrame(
2168 this.invalidateSize, this, false, this._container);
2171 _onMouseClick: function (e) {
2172 if (!this._loaded || (!e._simulated && this.dragging && this.dragging.moved()) ||
2173 L.DomEvent._skipped(e)) { return; }
2175 this.fire('preclick');
2176 this._fireMouseEvent(e);
2179 _fireMouseEvent: function (e) {
2180 if (!this._loaded || L.DomEvent._skipped(e)) { return; }
2184 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2186 if (!this.hasEventListeners(type)) { return; }
2188 if (type === 'contextmenu') {
2189 L.DomEvent.preventDefault(e);
2192 var containerPoint = this.mouseEventToContainerPoint(e),
2193 layerPoint = this.containerPointToLayerPoint(containerPoint),
2194 latlng = this.layerPointToLatLng(layerPoint);
2198 layerPoint: layerPoint,
2199 containerPoint: containerPoint,
2204 _onTileLayerLoad: function () {
2205 this._tileLayersToLoad--;
2206 if (this._tileLayersNum && !this._tileLayersToLoad) {
2207 this.fire('tilelayersload');
2211 _clearHandlers: function () {
2212 for (var i = 0, len = this._handlers.length; i < len; i++) {
2213 this._handlers[i].disable();
2217 whenReady: function (callback, context) {
2219 callback.call(context || this, this);
2221 this.on('load', callback, context);
2226 _layerAdd: function (layer) {
2228 this.fire('layeradd', {layer: layer});
2232 // private methods for getting map state
2234 _getMapPanePos: function () {
2235 return L.DomUtil.getPosition(this._mapPane);
2238 _moved: function () {
2239 var pos = this._getMapPanePos();
2240 return pos && !pos.equals([0, 0]);
2243 _getTopLeftPoint: function () {
2244 return this.getPixelOrigin().subtract(this._getMapPanePos());
2247 _getNewTopLeftPoint: function (center, zoom) {
2248 var viewHalf = this.getSize()._divideBy(2);
2249 // TODO round on display, not calculation to increase precision?
2250 return this.project(center, zoom)._subtract(viewHalf)._round();
2253 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2254 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2255 return this.project(latlng, newZoom)._subtract(topLeft);
2258 // layer point of the current center
2259 _getCenterLayerPoint: function () {
2260 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2263 // offset of the specified place to the current center in pixels
2264 _getCenterOffset: function (latlng) {
2265 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2268 _limitZoom: function (zoom) {
2269 var min = this.getMinZoom(),
2270 max = this.getMaxZoom();
2272 return Math.max(min, Math.min(max, zoom));
2276 L.map = function (id, options) {
2277 return new L.Map(id, options);
2282 * Mercator projection that takes into account that the Earth is not a perfect sphere.
2283 * Less popular than spherical mercator; used by projections like EPSG:3395.
2286 L.Projection.Mercator = {
2287 MAX_LATITUDE: 85.0840591556,
2289 R_MINOR: 6356752.314245179,
2292 project: function (latlng) { // (LatLng) -> Point
2293 var d = L.LatLng.DEG_TO_RAD,
2294 max = this.MAX_LATITUDE,
2295 lat = Math.max(Math.min(max, latlng.lat), -max),
2298 x = latlng.lng * d * r,
2301 eccent = Math.sqrt(1.0 - tmp * tmp),
2302 con = eccent * Math.sin(y);
2304 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2306 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2307 y = -r * Math.log(ts);
2309 return new L.Point(x, y);
2312 unproject: function (point) { // (Point, Boolean) -> LatLng
2313 var d = L.LatLng.RAD_TO_DEG,
2316 lng = point.x * d / r,
2318 eccent = Math.sqrt(1 - (tmp * tmp)),
2319 ts = Math.exp(- point.y / r),
2320 phi = (Math.PI / 2) - 2 * Math.atan(ts),
2327 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2328 con = eccent * Math.sin(phi);
2329 dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2330 Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2334 return new L.LatLng(phi * d, lng);
2340 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2343 projection: L.Projection.Mercator,
2345 transformation: (function () {
2346 var m = L.Projection.Mercator,
2350 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
2356 * L.TileLayer is used for standard xyz-numbered tile layers.
2359 L.TileLayer = L.Class.extend({
2360 includes: L.Mixin.Events,
2371 /* (undefined works too)
2374 continuousWorld: false,
2377 detectRetina: false,
2381 unloadInvisibleTiles: L.Browser.mobile,
2382 updateWhenIdle: L.Browser.mobile
2385 initialize: function (url, options) {
2386 options = L.setOptions(this, options);
2388 // detecting retina displays, adjusting tileSize and zoom levels
2389 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2391 options.tileSize = Math.floor(options.tileSize / 2);
2392 options.zoomOffset++;
2394 if (options.minZoom > 0) {
2397 this.options.maxZoom--;
2400 if (options.bounds) {
2401 options.bounds = L.latLngBounds(options.bounds);
2406 var subdomains = this.options.subdomains;
2408 if (typeof subdomains === 'string') {
2409 this.options.subdomains = subdomains.split('');
2413 onAdd: function (map) {
2415 this._animated = map._zoomAnimated;
2417 // create a container div for tiles
2418 this._initContainer();
2420 // create an image to clone for tiles
2421 this._createTileProto();
2425 'viewreset': this._reset,
2426 'moveend': this._update
2429 if (this._animated) {
2431 'zoomanim': this._animateZoom,
2432 'zoomend': this._endZoomAnim
2436 if (!this.options.updateWhenIdle) {
2437 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2438 map.on('move', this._limitedUpdate, this);
2445 addTo: function (map) {
2450 onRemove: function (map) {
2451 this._container.parentNode.removeChild(this._container);
2454 'viewreset': this._reset,
2455 'moveend': this._update
2458 if (this._animated) {
2460 'zoomanim': this._animateZoom,
2461 'zoomend': this._endZoomAnim
2465 if (!this.options.updateWhenIdle) {
2466 map.off('move', this._limitedUpdate, this);
2469 this._container = null;
2473 bringToFront: function () {
2474 var pane = this._map._panes.tilePane;
2476 if (this._container) {
2477 pane.appendChild(this._container);
2478 this._setAutoZIndex(pane, Math.max);
2484 bringToBack: function () {
2485 var pane = this._map._panes.tilePane;
2487 if (this._container) {
2488 pane.insertBefore(this._container, pane.firstChild);
2489 this._setAutoZIndex(pane, Math.min);
2495 getAttribution: function () {
2496 return this.options.attribution;
2499 getContainer: function () {
2500 return this._container;
2503 setOpacity: function (opacity) {
2504 this.options.opacity = opacity;
2507 this._updateOpacity();
2513 setZIndex: function (zIndex) {
2514 this.options.zIndex = zIndex;
2515 this._updateZIndex();
2520 setUrl: function (url, noRedraw) {
2530 redraw: function () {
2532 this._reset({hard: true});
2538 _updateZIndex: function () {
2539 if (this._container && this.options.zIndex !== undefined) {
2540 this._container.style.zIndex = this.options.zIndex;
2544 _setAutoZIndex: function (pane, compare) {
2546 var layers = pane.children,
2547 edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2550 for (i = 0, len = layers.length; i < len; i++) {
2552 if (layers[i] !== this._container) {
2553 zIndex = parseInt(layers[i].style.zIndex, 10);
2555 if (!isNaN(zIndex)) {
2556 edgeZIndex = compare(edgeZIndex, zIndex);
2561 this.options.zIndex = this._container.style.zIndex =
2562 (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2565 _updateOpacity: function () {
2567 tiles = this._tiles;
2569 if (L.Browser.ielt9) {
2571 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2574 L.DomUtil.setOpacity(this._container, this.options.opacity);
2578 _initContainer: function () {
2579 var tilePane = this._map._panes.tilePane;
2581 if (!this._container) {
2582 this._container = L.DomUtil.create('div', 'leaflet-layer');
2584 this._updateZIndex();
2586 if (this._animated) {
2587 var className = 'leaflet-tile-container leaflet-zoom-animated';
2589 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2590 this._tileContainer = L.DomUtil.create('div', className, this._container);
2593 this._tileContainer = this._container;
2596 tilePane.appendChild(this._container);
2598 if (this.options.opacity < 1) {
2599 this._updateOpacity();
2604 _reset: function (e) {
2605 for (var key in this._tiles) {
2606 this.fire('tileunload', {tile: this._tiles[key]});
2610 this._tilesToLoad = 0;
2612 if (this.options.reuseTiles) {
2613 this._unusedTiles = [];
2616 this._tileContainer.innerHTML = '';
2618 if (this._animated && e && e.hard) {
2619 this._clearBgBuffer();
2622 this._initContainer();
2625 _update: function () {
2627 if (!this._map) { return; }
2629 var bounds = this._map.getPixelBounds(),
2630 zoom = this._map.getZoom(),
2631 tileSize = this.options.tileSize;
2633 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2637 var tileBounds = L.bounds(
2638 bounds.min.divideBy(tileSize)._floor(),
2639 bounds.max.divideBy(tileSize)._floor());
2641 this._addTilesFromCenterOut(tileBounds);
2643 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2644 this._removeOtherTiles(tileBounds);
2648 _addTilesFromCenterOut: function (bounds) {
2650 center = bounds.getCenter();
2654 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2655 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2656 point = new L.Point(i, j);
2658 if (this._tileShouldBeLoaded(point)) {
2664 var tilesToLoad = queue.length;
2666 if (tilesToLoad === 0) { return; }
2668 // load tiles in order of their distance to center
2669 queue.sort(function (a, b) {
2670 return a.distanceTo(center) - b.distanceTo(center);
2673 var fragment = document.createDocumentFragment();
2675 // if its the first batch of tiles to load
2676 if (!this._tilesToLoad) {
2677 this.fire('loading');
2680 this._tilesToLoad += tilesToLoad;
2682 for (i = 0; i < tilesToLoad; i++) {
2683 this._addTile(queue[i], fragment);
2686 this._tileContainer.appendChild(fragment);
2689 _tileShouldBeLoaded: function (tilePoint) {
2690 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2691 return false; // already loaded
2694 var options = this.options;
2696 if (!options.continuousWorld) {
2697 var limit = this._getWrapTileNum();
2699 // don't load if exceeds world bounds
2700 if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit)) ||
2701 tilePoint.y < 0 || tilePoint.y >= limit) { return false; }
2704 if (options.bounds) {
2705 var tileSize = options.tileSize,
2706 nwPoint = tilePoint.multiplyBy(tileSize),
2707 sePoint = nwPoint.add([tileSize, tileSize]),
2708 nw = this._map.unproject(nwPoint),
2709 se = this._map.unproject(sePoint);
2711 // TODO temporary hack, will be removed after refactoring projections
2712 // https://github.com/Leaflet/Leaflet/issues/1618
2713 if (!options.continuousWorld && !options.noWrap) {
2718 if (!options.bounds.intersects([nw, se])) { return false; }
2724 _removeOtherTiles: function (bounds) {
2725 var kArr, x, y, key;
2727 for (key in this._tiles) {
2728 kArr = key.split(':');
2729 x = parseInt(kArr[0], 10);
2730 y = parseInt(kArr[1], 10);
2732 // remove tile if it's out of bounds
2733 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2734 this._removeTile(key);
2739 _removeTile: function (key) {
2740 var tile = this._tiles[key];
2742 this.fire('tileunload', {tile: tile, url: tile.src});
2744 if (this.options.reuseTiles) {
2745 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2746 this._unusedTiles.push(tile);
2748 } else if (tile.parentNode === this._tileContainer) {
2749 this._tileContainer.removeChild(tile);
2752 // for https://github.com/CloudMade/Leaflet/issues/137
2753 if (!L.Browser.android) {
2755 tile.src = L.Util.emptyImageUrl;
2758 delete this._tiles[key];
2761 _addTile: function (tilePoint, container) {
2762 var tilePos = this._getTilePos(tilePoint);
2764 // get unused tile - or create a new tile
2765 var tile = this._getTile();
2768 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2769 Android 4 browser has display issues with top/left and requires transform instead
2770 Android 2 browser requires top/left or tiles disappear on load or first drag
2771 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2772 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2774 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2776 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2778 this._loadTile(tile, tilePoint);
2780 if (tile.parentNode !== this._tileContainer) {
2781 container.appendChild(tile);
2785 _getZoomForUrl: function () {
2787 var options = this.options,
2788 zoom = this._map.getZoom();
2790 if (options.zoomReverse) {
2791 zoom = options.maxZoom - zoom;
2794 return zoom + options.zoomOffset;
2797 _getTilePos: function (tilePoint) {
2798 var origin = this._map.getPixelOrigin(),
2799 tileSize = this.options.tileSize;
2801 return tilePoint.multiplyBy(tileSize).subtract(origin);
2804 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2806 getTileUrl: function (tilePoint) {
2807 return L.Util.template(this._url, L.extend({
2808 s: this._getSubdomain(tilePoint),
2815 _getWrapTileNum: function () {
2816 // TODO refactor, limit is not valid for non-standard projections
2817 return Math.pow(2, this._getZoomForUrl());
2820 _adjustTilePoint: function (tilePoint) {
2822 var limit = this._getWrapTileNum();
2824 // wrap tile coordinates
2825 if (!this.options.continuousWorld && !this.options.noWrap) {
2826 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2829 if (this.options.tms) {
2830 tilePoint.y = limit - tilePoint.y - 1;
2833 tilePoint.z = this._getZoomForUrl();
2836 _getSubdomain: function (tilePoint) {
2837 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2838 return this.options.subdomains[index];
2841 _createTileProto: function () {
2842 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2843 img.style.width = img.style.height = this.options.tileSize + 'px';
2844 img.galleryimg = 'no';
2847 _getTile: function () {
2848 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2849 var tile = this._unusedTiles.pop();
2850 this._resetTile(tile);
2853 return this._createTile();
2856 // Override if data stored on a tile needs to be cleaned up before reuse
2857 _resetTile: function (/*tile*/) {},
2859 _createTile: function () {
2860 var tile = this._tileImg.cloneNode(false);
2861 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2863 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2864 L.DomUtil.setOpacity(tile, this.options.opacity);
2869 _loadTile: function (tile, tilePoint) {
2871 tile.onload = this._tileOnLoad;
2872 tile.onerror = this._tileOnError;
2874 this._adjustTilePoint(tilePoint);
2875 tile.src = this.getTileUrl(tilePoint);
2878 _tileLoaded: function () {
2879 this._tilesToLoad--;
2880 if (!this._tilesToLoad) {
2883 if (this._animated) {
2884 // clear scaled tiles after all new tiles are loaded (for performance)
2885 clearTimeout(this._clearBgBufferTimer);
2886 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2891 _tileOnLoad: function () {
2892 var layer = this._layer;
2894 //Only if we are loading an actual image
2895 if (this.src !== L.Util.emptyImageUrl) {
2896 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2898 layer.fire('tileload', {
2904 layer._tileLoaded();
2907 _tileOnError: function () {
2908 var layer = this._layer;
2910 layer.fire('tileerror', {
2915 var newUrl = layer.options.errorTileUrl;
2920 layer._tileLoaded();
2924 L.tileLayer = function (url, options) {
2925 return new L.TileLayer(url, options);
2930 * L.TileLayer.WMS is used for putting WMS tile layers on the map.
2933 L.TileLayer.WMS = L.TileLayer.extend({
2941 format: 'image/jpeg',
2945 initialize: function (url, options) { // (String, Object)
2949 var wmsParams = L.extend({}, this.defaultWmsParams),
2950 tileSize = options.tileSize || this.options.tileSize;
2952 if (options.detectRetina && L.Browser.retina) {
2953 wmsParams.width = wmsParams.height = tileSize * 2;
2955 wmsParams.width = wmsParams.height = tileSize;
2958 for (var i in options) {
2959 // all keys that are not TileLayer options go to WMS params
2960 if (!this.options.hasOwnProperty(i) && i !== 'crs') {
2961 wmsParams[i] = options[i];
2965 this.wmsParams = wmsParams;
2967 L.setOptions(this, options);
2970 onAdd: function (map) {
2972 this._crs = this.options.crs || map.options.crs;
2974 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2975 this.wmsParams[projectionKey] = this._crs.code;
2977 L.TileLayer.prototype.onAdd.call(this, map);
2980 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
2982 var map = this._map,
2983 tileSize = this.options.tileSize,
2985 nwPoint = tilePoint.multiplyBy(tileSize),
2986 sePoint = nwPoint.add([tileSize, tileSize]),
2988 nw = this._crs.project(map.unproject(nwPoint, zoom)),
2989 se = this._crs.project(map.unproject(sePoint, zoom)),
2991 bbox = [nw.x, se.y, se.x, nw.y].join(','),
2993 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
2995 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
2998 setParams: function (params, noRedraw) {
3000 L.extend(this.wmsParams, params);
3010 L.tileLayer.wms = function (url, options) {
3011 return new L.TileLayer.WMS(url, options);
3016 * L.TileLayer.Canvas is a class that you can use as a base for creating
3017 * dynamically drawn Canvas-based tile layers.
3020 L.TileLayer.Canvas = L.TileLayer.extend({
3025 initialize: function (options) {
3026 L.setOptions(this, options);
3029 redraw: function () {
3031 this._reset({hard: true});
3035 for (var i in this._tiles) {
3036 this._redrawTile(this._tiles[i]);
3041 _redrawTile: function (tile) {
3042 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3045 _createTileProto: function () {
3046 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
3047 proto.width = proto.height = this.options.tileSize;
3050 _createTile: function () {
3051 var tile = this._canvasProto.cloneNode(false);
3052 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3056 _loadTile: function (tile, tilePoint) {
3058 tile._tilePoint = tilePoint;
3060 this._redrawTile(tile);
3062 if (!this.options.async) {
3063 this.tileDrawn(tile);
3067 drawTile: function (/*tile, tilePoint*/) {
3068 // override with rendering code
3071 tileDrawn: function (tile) {
3072 this._tileOnLoad.call(tile);
3077 L.tileLayer.canvas = function (options) {
3078 return new L.TileLayer.Canvas(options);
3083 * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3086 L.ImageOverlay = L.Class.extend({
3087 includes: L.Mixin.Events,
3093 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3095 this._bounds = L.latLngBounds(bounds);
3097 L.setOptions(this, options);
3100 onAdd: function (map) {
3107 map._panes.overlayPane.appendChild(this._image);
3109 map.on('viewreset', this._reset, this);
3111 if (map.options.zoomAnimation && L.Browser.any3d) {
3112 map.on('zoomanim', this._animateZoom, this);
3118 onRemove: function (map) {
3119 map.getPanes().overlayPane.removeChild(this._image);
3121 map.off('viewreset', this._reset, this);
3123 if (map.options.zoomAnimation) {
3124 map.off('zoomanim', this._animateZoom, this);
3128 addTo: function (map) {
3133 setOpacity: function (opacity) {
3134 this.options.opacity = opacity;
3135 this._updateOpacity();
3139 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3140 bringToFront: function () {
3142 this._map._panes.overlayPane.appendChild(this._image);
3147 bringToBack: function () {
3148 var pane = this._map._panes.overlayPane;
3150 pane.insertBefore(this._image, pane.firstChild);
3155 _initImage: function () {
3156 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3158 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3159 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3161 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3164 this._updateOpacity();
3166 //TODO createImage util method to remove duplication
3167 L.extend(this._image, {
3169 onselectstart: L.Util.falseFn,
3170 onmousemove: L.Util.falseFn,
3171 onload: L.bind(this._onImageLoad, this),
3176 _animateZoom: function (e) {
3177 var map = this._map,
3178 image = this._image,
3179 scale = map.getZoomScale(e.zoom),
3180 nw = this._bounds.getNorthWest(),
3181 se = this._bounds.getSouthEast(),
3183 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3184 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3185 origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3187 image.style[L.DomUtil.TRANSFORM] =
3188 L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3191 _reset: function () {
3192 var image = this._image,
3193 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3194 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3196 L.DomUtil.setPosition(image, topLeft);
3198 image.style.width = size.x + 'px';
3199 image.style.height = size.y + 'px';
3202 _onImageLoad: function () {
3206 _updateOpacity: function () {
3207 L.DomUtil.setOpacity(this._image, this.options.opacity);
3211 L.imageOverlay = function (url, bounds, options) {
3212 return new L.ImageOverlay(url, bounds, options);
3217 * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3220 L.Icon = L.Class.extend({
3223 iconUrl: (String) (required)
3224 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3225 iconSize: (Point) (can be set through CSS)
3226 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3227 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3228 shadowUrl: (String) (no shadow by default)
3229 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3231 shadowAnchor: (Point)
3236 initialize: function (options) {
3237 L.setOptions(this, options);
3240 createIcon: function (oldIcon) {
3241 return this._createIcon('icon', oldIcon);
3244 createShadow: function (oldIcon) {
3245 return this._createIcon('shadow', oldIcon);
3248 _createIcon: function (name, oldIcon) {
3249 var src = this._getIconUrl(name);
3252 if (name === 'icon') {
3253 throw new Error('iconUrl not set in Icon options (see the docs).');
3259 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3260 img = this._createImg(src);
3262 img = this._createImg(src, oldIcon);
3264 this._setIconStyles(img, name);
3269 _setIconStyles: function (img, name) {
3270 var options = this.options,
3271 size = L.point(options[name + 'Size']),
3274 if (name === 'shadow') {
3275 anchor = L.point(options.shadowAnchor || options.iconAnchor);
3277 anchor = L.point(options.iconAnchor);
3280 if (!anchor && size) {
3281 anchor = size.divideBy(2, true);
3284 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3287 img.style.marginLeft = (-anchor.x) + 'px';
3288 img.style.marginTop = (-anchor.y) + 'px';
3292 img.style.width = size.x + 'px';
3293 img.style.height = size.y + 'px';
3297 _createImg: function (src, el) {
3299 if (!L.Browser.ie6) {
3301 el = document.createElement('img');
3306 el = document.createElement('div');
3309 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
3314 _getIconUrl: function (name) {
3315 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3316 return this.options[name + 'RetinaUrl'];
3318 return this.options[name + 'Url'];
3322 L.icon = function (options) {
3323 return new L.Icon(options);
3328 * L.Icon.Default is the blue marker icon used by default in Leaflet.
3331 L.Icon.Default = L.Icon.extend({
3335 iconAnchor: [12, 41],
3336 popupAnchor: [1, -34],
3338 shadowSize: [41, 41]
3341 _getIconUrl: function (name) {
3342 var key = name + 'Url';
3344 if (this.options[key]) {
3345 return this.options[key];
3348 if (L.Browser.retina && name === 'icon') {
3352 var path = L.Icon.Default.imagePath;
3355 throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3358 return path + '/marker-' + name + '.png';
3362 L.Icon.Default.imagePath = (function () {
3363 var scripts = document.getElementsByTagName('script'),
3364 leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3366 var i, len, src, matches, path;
3368 for (i = 0, len = scripts.length; i < len; i++) {
3369 src = scripts[i].src;
3370 matches = src.match(leafletRe);
3373 path = src.split(leafletRe)[0];
3374 return (path ? path + '/' : '') + 'images';
3381 * L.Marker is used to display clickable/draggable icons on the map.
3384 L.Marker = L.Class.extend({
3386 includes: L.Mixin.Events,
3389 icon: new L.Icon.Default(),
3400 initialize: function (latlng, options) {
3401 L.setOptions(this, options);
3402 this._latlng = L.latLng(latlng);
3405 onAdd: function (map) {
3408 map.on('viewreset', this.update, this);
3413 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3414 map.on('zoomanim', this._animateZoom, this);
3418 addTo: function (map) {
3423 onRemove: function (map) {
3424 if (this.dragging) {
3425 this.dragging.disable();
3429 this._removeShadow();
3431 this.fire('remove');
3434 'viewreset': this.update,
3435 'zoomanim': this._animateZoom
3441 getLatLng: function () {
3442 return this._latlng;
3445 setLatLng: function (latlng) {
3446 this._latlng = L.latLng(latlng);
3450 return this.fire('move', { latlng: this._latlng });
3453 setZIndexOffset: function (offset) {
3454 this.options.zIndexOffset = offset;
3460 setIcon: function (icon) {
3462 this.options.icon = icon;
3472 update: function () {
3474 var pos = this._map.latLngToLayerPoint(this._latlng).round();
3481 _initIcon: function () {
3482 var options = this.options,
3484 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3485 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3487 var icon = options.icon.createIcon(this._icon),
3490 // if we're not reusing the icon, remove the old one and init new one
3491 if (icon !== this._icon) {
3497 if (options.title) {
3498 icon.title = options.title;
3502 L.DomUtil.addClass(icon, classToAdd);
3504 if (options.keyboard) {
3505 icon.tabIndex = '0';
3510 this._initInteraction();
3512 if (options.riseOnHover) {
3514 .on(icon, 'mouseover', this._bringToFront, this)
3515 .on(icon, 'mouseout', this._resetZIndex, this);
3518 var newShadow = options.icon.createShadow(this._shadow),
3521 if (newShadow !== this._shadow) {
3522 this._removeShadow();
3527 L.DomUtil.addClass(newShadow, classToAdd);
3529 this._shadow = newShadow;
3532 if (options.opacity < 1) {
3533 this._updateOpacity();
3537 var panes = this._map._panes;
3540 panes.markerPane.appendChild(this._icon);
3543 if (newShadow && addShadow) {
3544 panes.shadowPane.appendChild(this._shadow);
3548 _removeIcon: function () {
3549 if (this.options.riseOnHover) {
3551 .off(this._icon, 'mouseover', this._bringToFront)
3552 .off(this._icon, 'mouseout', this._resetZIndex);
3555 this._map._panes.markerPane.removeChild(this._icon);
3560 _removeShadow: function () {
3562 this._map._panes.shadowPane.removeChild(this._shadow);
3564 this._shadow = null;
3567 _setPos: function (pos) {
3568 L.DomUtil.setPosition(this._icon, pos);
3571 L.DomUtil.setPosition(this._shadow, pos);
3574 this._zIndex = pos.y + this.options.zIndexOffset;
3576 this._resetZIndex();
3579 _updateZIndex: function (offset) {
3580 this._icon.style.zIndex = this._zIndex + offset;
3583 _animateZoom: function (opt) {
3584 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3589 _initInteraction: function () {
3591 if (!this.options.clickable) { return; }
3593 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3595 var icon = this._icon,
3596 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3598 L.DomUtil.addClass(icon, 'leaflet-clickable');
3599 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3600 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3602 for (var i = 0; i < events.length; i++) {
3603 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3606 if (L.Handler.MarkerDrag) {
3607 this.dragging = new L.Handler.MarkerDrag(this);
3609 if (this.options.draggable) {
3610 this.dragging.enable();
3615 _onMouseClick: function (e) {
3616 var wasDragged = this.dragging && this.dragging.moved();
3618 if (this.hasEventListeners(e.type) || wasDragged) {
3619 L.DomEvent.stopPropagation(e);
3622 if (wasDragged) { return; }
3624 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3628 latlng: this._latlng
3632 _onKeyPress: function (e) {
3633 if (e.keyCode === 13) {
3634 this.fire('click', {
3636 latlng: this._latlng
3641 _fireMouseEvent: function (e) {
3645 latlng: this._latlng
3648 // TODO proper custom event propagation
3649 // this line will always be called if marker is in a FeatureGroup
3650 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3651 L.DomEvent.preventDefault(e);
3653 if (e.type !== 'mousedown') {
3654 L.DomEvent.stopPropagation(e);
3656 L.DomEvent.preventDefault(e);
3660 setOpacity: function (opacity) {
3661 this.options.opacity = opacity;
3663 this._updateOpacity();
3669 _updateOpacity: function () {
3670 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3672 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3676 _bringToFront: function () {
3677 this._updateZIndex(this.options.riseOffset);
3680 _resetZIndex: function () {
3681 this._updateZIndex(0);
3685 L.marker = function (latlng, options) {
3686 return new L.Marker(latlng, options);
3691 * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3692 * to use with L.Marker.
3695 L.DivIcon = L.Icon.extend({
3697 iconSize: [12, 12], // also can be set through CSS
3700 popupAnchor: (Point)
3704 className: 'leaflet-div-icon',
3708 createIcon: function (oldIcon) {
3709 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3710 options = this.options;
3712 if (options.html !== false) {
3713 div.innerHTML = options.html;
3718 if (options.bgPos) {
3719 div.style.backgroundPosition =
3720 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3723 this._setIconStyles(div, 'icon');
3727 createShadow: function () {
3732 L.divIcon = function (options) {
3733 return new L.DivIcon(options);
3738 * L.Popup is used for displaying popups on the map.
3741 L.Map.mergeOptions({
3742 closePopupOnClick: true
3745 L.Popup = L.Class.extend({
3746 includes: L.Mixin.Events,
3755 autoPanPadding: [5, 5],
3761 initialize: function (options, source) {
3762 L.setOptions(this, options);
3764 this._source = source;
3765 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3766 this._isOpen = false;
3769 onAdd: function (map) {
3772 if (!this._container) {
3775 this._updateContent();
3777 var animFade = map.options.fadeAnimation;
3780 L.DomUtil.setOpacity(this._container, 0);
3782 map._panes.popupPane.appendChild(this._container);
3784 map.on(this._getEvents(), this);
3789 L.DomUtil.setOpacity(this._container, 1);
3794 map.fire('popupopen', {popup: this});
3797 this._source.fire('popupopen', {popup: this});
3801 addTo: function (map) {
3806 openOn: function (map) {
3807 map.openPopup(this);
3811 onRemove: function (map) {
3812 map._panes.popupPane.removeChild(this._container);
3814 L.Util.falseFn(this._container.offsetWidth); // force reflow
3816 map.off(this._getEvents(), this);
3818 if (map.options.fadeAnimation) {
3819 L.DomUtil.setOpacity(this._container, 0);
3826 map.fire('popupclose', {popup: this});
3829 this._source.fire('popupclose', {popup: this});
3833 setLatLng: function (latlng) {
3834 this._latlng = L.latLng(latlng);
3839 setContent: function (content) {
3840 this._content = content;
3845 _getEvents: function () {
3847 viewreset: this._updatePosition
3850 if (this._animated) {
3851 events.zoomanim = this._zoomAnimation;
3853 if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
3854 events.preclick = this._close;
3856 if (this.options.keepInView) {
3857 events.moveend = this._adjustPan;
3863 _close: function () {
3865 this._map.closePopup(this);
3869 _initLayout: function () {
3870 var prefix = 'leaflet-popup',
3871 containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
3872 (this._animated ? 'animated' : 'hide'),
3873 container = this._container = L.DomUtil.create('div', containerClass),
3876 if (this.options.closeButton) {
3877 closeButton = this._closeButton =
3878 L.DomUtil.create('a', prefix + '-close-button', container);
3879 closeButton.href = '#close';
3880 closeButton.innerHTML = '×';
3881 L.DomEvent.disableClickPropagation(closeButton);
3883 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3886 var wrapper = this._wrapper =
3887 L.DomUtil.create('div', prefix + '-content-wrapper', container);
3888 L.DomEvent.disableClickPropagation(wrapper);
3890 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3891 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
3892 L.DomEvent.on(this._contentNode, 'MozMousePixelScroll', L.DomEvent.stopPropagation);
3893 L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
3894 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3895 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3898 _update: function () {
3899 if (!this._map) { return; }
3901 this._container.style.visibility = 'hidden';
3903 this._updateContent();
3904 this._updateLayout();
3905 this._updatePosition();
3907 this._container.style.visibility = '';
3912 _updateContent: function () {
3913 if (!this._content) { return; }
3915 if (typeof this._content === 'string') {
3916 this._contentNode.innerHTML = this._content;
3918 while (this._contentNode.hasChildNodes()) {
3919 this._contentNode.removeChild(this._contentNode.firstChild);
3921 this._contentNode.appendChild(this._content);
3923 this.fire('contentupdate');
3926 _updateLayout: function () {
3927 var container = this._contentNode,
3928 style = container.style;
3931 style.whiteSpace = 'nowrap';
3933 var width = container.offsetWidth;
3934 width = Math.min(width, this.options.maxWidth);
3935 width = Math.max(width, this.options.minWidth);
3937 style.width = (width + 1) + 'px';
3938 style.whiteSpace = '';
3942 var height = container.offsetHeight,
3943 maxHeight = this.options.maxHeight,
3944 scrolledClass = 'leaflet-popup-scrolled';
3946 if (maxHeight && height > maxHeight) {
3947 style.height = maxHeight + 'px';
3948 L.DomUtil.addClass(container, scrolledClass);
3950 L.DomUtil.removeClass(container, scrolledClass);
3953 this._containerWidth = this._container.offsetWidth;
3956 _updatePosition: function () {
3957 if (!this._map) { return; }
3959 var pos = this._map.latLngToLayerPoint(this._latlng),
3960 animated = this._animated,
3961 offset = L.point(this.options.offset);
3964 L.DomUtil.setPosition(this._container, pos);
3967 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
3968 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
3970 // bottom position the popup in case the height of the popup changes (images loading etc)
3971 this._container.style.bottom = this._containerBottom + 'px';
3972 this._container.style.left = this._containerLeft + 'px';
3975 _zoomAnimation: function (opt) {
3976 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3978 L.DomUtil.setPosition(this._container, pos);
3981 _adjustPan: function () {
3982 if (!this.options.autoPan) { return; }
3984 var map = this._map,
3985 containerHeight = this._container.offsetHeight,
3986 containerWidth = this._containerWidth,
3988 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
3990 if (this._animated) {
3991 layerPos._add(L.DomUtil.getPosition(this._container));
3994 var containerPos = map.layerPointToContainerPoint(layerPos),
3995 padding = L.point(this.options.autoPanPadding),
3996 size = map.getSize(),
4000 if (containerPos.x + containerWidth > size.x) { // right
4001 dx = containerPos.x + containerWidth - size.x + padding.x;
4003 if (containerPos.x - dx < 0) { // left
4004 dx = containerPos.x - padding.x;
4006 if (containerPos.y + containerHeight > size.y) { // bottom
4007 dy = containerPos.y + containerHeight - size.y + padding.y;
4009 if (containerPos.y - dy < 0) { // top
4010 dy = containerPos.y - padding.y;
4015 .fire('autopanstart')
4020 _onCloseButtonClick: function (e) {
4026 L.popup = function (options, source) {
4027 return new L.Popup(options, source);
4032 openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
4035 if (!(popup instanceof L.Popup)) {
4036 var content = popup;
4038 popup = new L.Popup(options)
4040 .setContent(content);
4042 popup._isOpen = true;
4044 this._popup = popup;
4045 return this.addLayer(popup);
4048 closePopup: function (popup) {
4049 if (!popup || popup === this._popup) {
4050 popup = this._popup;
4054 this.removeLayer(popup);
4055 popup._isOpen = false;
4063 * Popup extension to L.Marker, adding popup-related methods.
4067 openPopup: function () {
4068 if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
4069 this._popup.setLatLng(this._latlng);
4070 this._map.openPopup(this._popup);
4076 closePopup: function () {
4078 this._popup._close();
4083 togglePopup: function () {
4085 if (this._popup._isOpen) {
4094 bindPopup: function (content, options) {
4095 var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
4097 anchor = anchor.add(L.Popup.prototype.options.offset);
4099 if (options && options.offset) {
4100 anchor = anchor.add(options.offset);
4103 options = L.extend({offset: anchor}, options);
4107 .on('click', this.togglePopup, this)
4108 .on('remove', this.closePopup, this)
4109 .on('move', this._movePopup, this);
4112 if (content instanceof L.Popup) {
4113 L.setOptions(content, options);
4114 this._popup = content;
4116 this._popup = new L.Popup(options, this)
4117 .setContent(content);
4123 setPopupContent: function (content) {
4125 this._popup.setContent(content);
4130 unbindPopup: function () {
4134 .off('click', this.togglePopup)
4135 .off('remove', this.closePopup)
4136 .off('move', this._movePopup);
4141 _movePopup: function (e) {
4142 this._popup.setLatLng(e.latlng);
4148 * L.LayerGroup is a class to combine several layers into one so that
4149 * you can manipulate the group (e.g. add/remove it) as one layer.
4152 L.LayerGroup = L.Class.extend({
4153 initialize: function (layers) {
4159 for (i = 0, len = layers.length; i < len; i++) {
4160 this.addLayer(layers[i]);
4165 addLayer: function (layer) {
4166 var id = this.getLayerId(layer);
4168 this._layers[id] = layer;
4171 this._map.addLayer(layer);
4177 removeLayer: function (layer) {
4178 var id = layer in this._layers ? layer : this.getLayerId(layer);
4180 if (this._map && this._layers[id]) {
4181 this._map.removeLayer(this._layers[id]);
4184 delete this._layers[id];
4189 hasLayer: function (layer) {
4190 if (!layer) { return false; }
4192 return (layer in this._layers || this.getLayerId(layer) in this._layers);
4195 clearLayers: function () {
4196 this.eachLayer(this.removeLayer, this);
4200 invoke: function (methodName) {
4201 var args = Array.prototype.slice.call(arguments, 1),
4204 for (i in this._layers) {
4205 layer = this._layers[i];
4207 if (layer[methodName]) {
4208 layer[methodName].apply(layer, args);
4215 onAdd: function (map) {
4217 this.eachLayer(map.addLayer, map);
4220 onRemove: function (map) {
4221 this.eachLayer(map.removeLayer, map);
4225 addTo: function (map) {
4230 eachLayer: function (method, context) {
4231 for (var i in this._layers) {
4232 method.call(context, this._layers[i]);
4237 getLayer: function (id) {
4238 return this._layers[id];
4241 getLayers: function () {
4244 for (var i in this._layers) {
4245 layers.push(this._layers[i]);
4250 setZIndex: function (zIndex) {
4251 return this.invoke('setZIndex', zIndex);
4254 getLayerId: function (layer) {
4255 return L.stamp(layer);
4259 L.layerGroup = function (layers) {
4260 return new L.LayerGroup(layers);
4265 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
4266 * shared between a group of interactive layers (like vectors or markers).
4269 L.FeatureGroup = L.LayerGroup.extend({
4270 includes: L.Mixin.Events,
4273 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
4276 addLayer: function (layer) {
4277 if (this.hasLayer(layer)) {
4281 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4283 L.LayerGroup.prototype.addLayer.call(this, layer);
4285 if (this._popupContent && layer.bindPopup) {
4286 layer.bindPopup(this._popupContent, this._popupOptions);
4289 return this.fire('layeradd', {layer: layer});
4292 removeLayer: function (layer) {
4293 if (!this.hasLayer(layer)) {
4296 if (layer in this._layers) {
4297 layer = this._layers[layer];
4300 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4302 L.LayerGroup.prototype.removeLayer.call(this, layer);
4304 if (this._popupContent) {
4305 this.invoke('unbindPopup');
4308 return this.fire('layerremove', {layer: layer});
4311 bindPopup: function (content, options) {
4312 this._popupContent = content;
4313 this._popupOptions = options;
4314 return this.invoke('bindPopup', content, options);
4317 setStyle: function (style) {
4318 return this.invoke('setStyle', style);
4321 bringToFront: function () {
4322 return this.invoke('bringToFront');
4325 bringToBack: function () {
4326 return this.invoke('bringToBack');
4329 getBounds: function () {
4330 var bounds = new L.LatLngBounds();
4332 this.eachLayer(function (layer) {
4333 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
4339 _propagateEvent: function (e) {
4345 this.fire(e.type, e);
4349 L.featureGroup = function (layers) {
4350 return new L.FeatureGroup(layers);
4355 * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
4358 L.Path = L.Class.extend({
4359 includes: [L.Mixin.Events],
4362 // how much to extend the clip area around the map view
4363 // (relative to its size, e.g. 0.5 is half the screen in each direction)
4364 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
4365 CLIP_PADDING: (function () {
4366 var max = L.Browser.mobile ? 1280 : 2000,
4367 target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
4368 return Math.max(0, Math.min(0.5, target));
4380 fillColor: null, //same as color by default
4386 initialize: function (options) {
4387 L.setOptions(this, options);
4390 onAdd: function (map) {
4393 if (!this._container) {
4394 this._initElements();
4398 this.projectLatlngs();
4401 if (this._container) {
4402 this._map._pathRoot.appendChild(this._container);
4408 'viewreset': this.projectLatlngs,
4409 'moveend': this._updatePath
4413 addTo: function (map) {
4418 onRemove: function (map) {
4419 map._pathRoot.removeChild(this._container);
4421 // Need to fire remove event before we set _map to null as the event hooks might need the object
4422 this.fire('remove');
4425 if (L.Browser.vml) {
4426 this._container = null;
4427 this._stroke = null;
4432 'viewreset': this.projectLatlngs,
4433 'moveend': this._updatePath
4437 projectLatlngs: function () {
4438 // do all projection stuff here
4441 setStyle: function (style) {
4442 L.setOptions(this, style);
4444 if (this._container) {
4445 this._updateStyle();
4451 redraw: function () {
4453 this.projectLatlngs();
4461 _updatePathViewport: function () {
4462 var p = L.Path.CLIP_PADDING,
4463 size = this.getSize(),
4464 panePos = L.DomUtil.getPosition(this._mapPane),
4465 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4466 max = min.add(size.multiplyBy(1 + p * 2)._round());
4468 this._pathViewport = new L.Bounds(min, max);
4474 * Extends L.Path with SVG-specific rendering code.
4477 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4479 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4481 L.Path = L.Path.extend({
4486 bringToFront: function () {
4487 var root = this._map._pathRoot,
4488 path = this._container;
4490 if (path && root.lastChild !== path) {
4491 root.appendChild(path);
4496 bringToBack: function () {
4497 var root = this._map._pathRoot,
4498 path = this._container,
4499 first = root.firstChild;
4501 if (path && first !== path) {
4502 root.insertBefore(path, first);
4507 getPathString: function () {
4508 // form path string here
4511 _createElement: function (name) {
4512 return document.createElementNS(L.Path.SVG_NS, name);
4515 _initElements: function () {
4516 this._map._initPathRoot();
4521 _initPath: function () {
4522 this._container = this._createElement('g');
4524 this._path = this._createElement('path');
4525 this._container.appendChild(this._path);
4528 _initStyle: function () {
4529 if (this.options.stroke) {
4530 this._path.setAttribute('stroke-linejoin', 'round');
4531 this._path.setAttribute('stroke-linecap', 'round');
4533 if (this.options.fill) {
4534 this._path.setAttribute('fill-rule', 'evenodd');
4536 if (this.options.pointerEvents) {
4537 this._path.setAttribute('pointer-events', this.options.pointerEvents);
4539 if (!this.options.clickable && !this.options.pointerEvents) {
4540 this._path.setAttribute('pointer-events', 'none');
4542 this._updateStyle();
4545 _updateStyle: function () {
4546 if (this.options.stroke) {
4547 this._path.setAttribute('stroke', this.options.color);
4548 this._path.setAttribute('stroke-opacity', this.options.opacity);
4549 this._path.setAttribute('stroke-width', this.options.weight);
4550 if (this.options.dashArray) {
4551 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4553 this._path.removeAttribute('stroke-dasharray');
4556 this._path.setAttribute('stroke', 'none');
4558 if (this.options.fill) {
4559 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4560 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4562 this._path.setAttribute('fill', 'none');
4566 _updatePath: function () {
4567 var str = this.getPathString();
4569 // fix webkit empty string parsing bug
4572 this._path.setAttribute('d', str);
4575 // TODO remove duplication with L.Map
4576 _initEvents: function () {
4577 if (this.options.clickable) {
4578 if (L.Browser.svg || !L.Browser.vml) {
4579 this._path.setAttribute('class', 'leaflet-clickable');
4582 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4584 var events = ['dblclick', 'mousedown', 'mouseover',
4585 'mouseout', 'mousemove', 'contextmenu'];
4586 for (var i = 0; i < events.length; i++) {
4587 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4592 _onMouseClick: function (e) {
4593 if (this._map.dragging && this._map.dragging.moved()) { return; }
4595 this._fireMouseEvent(e);
4598 _fireMouseEvent: function (e) {
4599 if (!this.hasEventListeners(e.type)) { return; }
4601 var map = this._map,
4602 containerPoint = map.mouseEventToContainerPoint(e),
4603 layerPoint = map.containerPointToLayerPoint(containerPoint),
4604 latlng = map.layerPointToLatLng(layerPoint);
4608 layerPoint: layerPoint,
4609 containerPoint: containerPoint,
4613 if (e.type === 'contextmenu') {
4614 L.DomEvent.preventDefault(e);
4616 if (e.type !== 'mousemove') {
4617 L.DomEvent.stopPropagation(e);
4623 _initPathRoot: function () {
4624 if (!this._pathRoot) {
4625 this._pathRoot = L.Path.prototype._createElement('svg');
4626 this._panes.overlayPane.appendChild(this._pathRoot);
4628 if (this.options.zoomAnimation && L.Browser.any3d) {
4629 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
4632 'zoomanim': this._animatePathZoom,
4633 'zoomend': this._endPathZoom
4636 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
4639 this.on('moveend', this._updateSvgViewport);
4640 this._updateSvgViewport();
4644 _animatePathZoom: function (e) {
4645 var scale = this.getZoomScale(e.zoom),
4646 offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4648 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4649 L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4651 this._pathZooming = true;
4654 _endPathZoom: function () {
4655 this._pathZooming = false;
4658 _updateSvgViewport: function () {
4660 if (this._pathZooming) {
4661 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4662 // When the zoom animation ends we will be updated again anyway
4663 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4667 this._updatePathViewport();
4669 var vp = this._pathViewport,
4672 width = max.x - min.x,
4673 height = max.y - min.y,
4674 root = this._pathRoot,
4675 pane = this._panes.overlayPane;
4677 // Hack to make flicker on drag end on mobile webkit less irritating
4678 if (L.Browser.mobileWebkit) {
4679 pane.removeChild(root);
4682 L.DomUtil.setPosition(root, min);
4683 root.setAttribute('width', width);
4684 root.setAttribute('height', height);
4685 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4687 if (L.Browser.mobileWebkit) {
4688 pane.appendChild(root);
4695 * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4700 bindPopup: function (content, options) {
4702 if (content instanceof L.Popup) {
4703 this._popup = content;
4705 if (!this._popup || options) {
4706 this._popup = new L.Popup(options, this);
4708 this._popup.setContent(content);
4711 if (!this._popupHandlersAdded) {
4713 .on('click', this._openPopup, this)
4714 .on('remove', this.closePopup, this);
4716 this._popupHandlersAdded = true;
4722 unbindPopup: function () {
4726 .off('click', this._openPopup)
4727 .off('remove', this.closePopup);
4729 this._popupHandlersAdded = false;
4734 openPopup: function (latlng) {
4737 // open the popup from one of the path's points if not specified
4738 latlng = latlng || this._latlng ||
4739 this._latlngs[Math.floor(this._latlngs.length / 2)];
4741 this._openPopup({latlng: latlng});
4747 closePopup: function () {
4749 this._popup._close();
4754 _openPopup: function (e) {
4755 this._popup.setLatLng(e.latlng);
4756 this._map.openPopup(this._popup);
4762 * Vector rendering for IE6-8 through VML.
4763 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4766 L.Browser.vml = !L.Browser.svg && (function () {
4768 var div = document.createElement('div');
4769 div.innerHTML = '<v:shape adj="1"/>';
4771 var shape = div.firstChild;
4772 shape.style.behavior = 'url(#default#VML)';
4774 return shape && (typeof shape.adj === 'object');
4781 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4787 _createElement: (function () {
4789 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4790 return function (name) {
4791 return document.createElement('<lvml:' + name + ' class="lvml">');
4794 return function (name) {
4795 return document.createElement(
4796 '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4801 _initPath: function () {
4802 var container = this._container = this._createElement('shape');
4803 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4804 if (this.options.clickable) {
4805 L.DomUtil.addClass(container, 'leaflet-clickable');
4807 container.coordsize = '1 1';
4809 this._path = this._createElement('path');
4810 container.appendChild(this._path);
4812 this._map._pathRoot.appendChild(container);
4815 _initStyle: function () {
4816 this._updateStyle();
4819 _updateStyle: function () {
4820 var stroke = this._stroke,
4822 options = this.options,
4823 container = this._container;
4825 container.stroked = options.stroke;
4826 container.filled = options.fill;
4828 if (options.stroke) {
4830 stroke = this._stroke = this._createElement('stroke');
4831 stroke.endcap = 'round';
4832 container.appendChild(stroke);
4834 stroke.weight = options.weight + 'px';
4835 stroke.color = options.color;
4836 stroke.opacity = options.opacity;
4838 if (options.dashArray) {
4839 stroke.dashStyle = options.dashArray instanceof Array ?
4840 options.dashArray.join(' ') :
4841 options.dashArray.replace(/( *, *)/g, ' ');
4843 stroke.dashStyle = '';
4846 } else if (stroke) {
4847 container.removeChild(stroke);
4848 this._stroke = null;
4853 fill = this._fill = this._createElement('fill');
4854 container.appendChild(fill);
4856 fill.color = options.fillColor || options.color;
4857 fill.opacity = options.fillOpacity;
4860 container.removeChild(fill);
4865 _updatePath: function () {
4866 var style = this._container.style;
4868 style.display = 'none';
4869 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4874 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4875 _initPathRoot: function () {
4876 if (this._pathRoot) { return; }
4878 var root = this._pathRoot = document.createElement('div');
4879 root.className = 'leaflet-vml-container';
4880 this._panes.overlayPane.appendChild(root);
4882 this.on('moveend', this._updatePathViewport);
4883 this._updatePathViewport();
4889 * Vector rendering for all browsers that support canvas.
4892 L.Browser.canvas = (function () {
4893 return !!document.createElement('canvas').getContext;
4896 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4898 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4903 redraw: function () {
4905 this.projectLatlngs();
4906 this._requestUpdate();
4911 setStyle: function (style) {
4912 L.setOptions(this, style);
4915 this._updateStyle();
4916 this._requestUpdate();
4921 onRemove: function (map) {
4923 .off('viewreset', this.projectLatlngs, this)
4924 .off('moveend', this._updatePath, this);
4926 if (this.options.clickable) {
4927 this._map.off('click', this._onClick, this);
4928 this._map.off('mousemove', this._onMouseMove, this);
4931 this._requestUpdate();
4936 _requestUpdate: function () {
4937 if (this._map && !L.Path._updateRequest) {
4938 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4942 _fireMapMoveEnd: function () {
4943 L.Path._updateRequest = null;
4944 this.fire('moveend');
4947 _initElements: function () {
4948 this._map._initPathRoot();
4949 this._ctx = this._map._canvasCtx;
4952 _updateStyle: function () {
4953 var options = this.options;
4955 if (options.stroke) {
4956 this._ctx.lineWidth = options.weight;
4957 this._ctx.strokeStyle = options.color;
4960 this._ctx.fillStyle = options.fillColor || options.color;
4964 _drawPath: function () {
4965 var i, j, len, len2, point, drawMethod;
4967 this._ctx.beginPath();
4969 for (i = 0, len = this._parts.length; i < len; i++) {
4970 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4971 point = this._parts[i][j];
4972 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4974 this._ctx[drawMethod](point.x, point.y);
4976 // TODO refactor ugly hack
4977 if (this instanceof L.Polygon) {
4978 this._ctx.closePath();
4983 _checkIfEmpty: function () {
4984 return !this._parts.length;
4987 _updatePath: function () {
4988 if (this._checkIfEmpty()) { return; }
4990 var ctx = this._ctx,
4991 options = this.options;
4995 this._updateStyle();
4998 ctx.globalAlpha = options.fillOpacity;
5002 if (options.stroke) {
5003 ctx.globalAlpha = options.opacity;
5009 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
5012 _initEvents: function () {
5013 if (this.options.clickable) {
5015 this._map.on('mousemove', this._onMouseMove, this);
5016 this._map.on('click', this._onClick, this);
5020 _onClick: function (e) {
5021 if (this._containsPoint(e.layerPoint)) {
5022 this.fire('click', e);
5026 _onMouseMove: function (e) {
5027 if (!this._map || this._map._animatingZoom) { return; }
5029 // TODO don't do on each move
5030 if (this._containsPoint(e.layerPoint)) {
5031 this._ctx.canvas.style.cursor = 'pointer';
5032 this._mouseInside = true;
5033 this.fire('mouseover', e);
5035 } else if (this._mouseInside) {
5036 this._ctx.canvas.style.cursor = '';
5037 this._mouseInside = false;
5038 this.fire('mouseout', e);
5043 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
5044 _initPathRoot: function () {
5045 var root = this._pathRoot,
5049 root = this._pathRoot = document.createElement('canvas');
5050 root.style.position = 'absolute';
5051 ctx = this._canvasCtx = root.getContext('2d');
5053 ctx.lineCap = 'round';
5054 ctx.lineJoin = 'round';
5056 this._panes.overlayPane.appendChild(root);
5058 if (this.options.zoomAnimation) {
5059 this._pathRoot.className = 'leaflet-zoom-animated';
5060 this.on('zoomanim', this._animatePathZoom);
5061 this.on('zoomend', this._endPathZoom);
5063 this.on('moveend', this._updateCanvasViewport);
5064 this._updateCanvasViewport();
5068 _updateCanvasViewport: function () {
5069 // don't redraw while zooming. See _updateSvgViewport for more details
5070 if (this._pathZooming) { return; }
5071 this._updatePathViewport();
5073 var vp = this._pathViewport,
5075 size = vp.max.subtract(min),
5076 root = this._pathRoot;
5078 //TODO check if this works properly on mobile webkit
5079 L.DomUtil.setPosition(root, min);
5080 root.width = size.x;
5081 root.height = size.y;
5082 root.getContext('2d').translate(-min.x, -min.y);
5088 * L.LineUtil contains different utility functions for line segments
5089 * and polylines (clipping, simplification, distances, etc.)
5092 /*jshint bitwise:false */ // allow bitwise oprations for this file
5096 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
5097 // Improves rendering performance dramatically by lessening the number of points to draw.
5099 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
5100 if (!tolerance || !points.length) {
5101 return points.slice();
5104 var sqTolerance = tolerance * tolerance;
5106 // stage 1: vertex reduction
5107 points = this._reducePoints(points, sqTolerance);
5109 // stage 2: Douglas-Peucker simplification
5110 points = this._simplifyDP(points, sqTolerance);
5115 // distance from a point to a segment between two points
5116 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5117 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
5120 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5121 return this._sqClosestPointOnSegment(p, p1, p2);
5124 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
5125 _simplifyDP: function (points, sqTolerance) {
5127 var len = points.length,
5128 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
5129 markers = new ArrayConstructor(len);
5131 markers[0] = markers[len - 1] = 1;
5133 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
5138 for (i = 0; i < len; i++) {
5140 newPoints.push(points[i]);
5147 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
5152 for (i = first + 1; i <= last - 1; i++) {
5153 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
5155 if (sqDist > maxSqDist) {
5161 if (maxSqDist > sqTolerance) {
5164 this._simplifyDPStep(points, markers, sqTolerance, first, index);
5165 this._simplifyDPStep(points, markers, sqTolerance, index, last);
5169 // reduce points that are too close to each other to a single point
5170 _reducePoints: function (points, sqTolerance) {
5171 var reducedPoints = [points[0]];
5173 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
5174 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
5175 reducedPoints.push(points[i]);
5179 if (prev < len - 1) {
5180 reducedPoints.push(points[len - 1]);
5182 return reducedPoints;
5185 // Cohen-Sutherland line clipping algorithm.
5186 // Used to avoid rendering parts of a polyline that are not currently visible.
5188 clipSegment: function (a, b, bounds, useLastCode) {
5189 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
5190 codeB = this._getBitCode(b, bounds),
5192 codeOut, p, newCode;
5194 // save 2nd code to avoid calculating it on the next segment
5195 this._lastCode = codeB;
5198 // if a,b is inside the clip window (trivial accept)
5199 if (!(codeA | codeB)) {
5201 // if a,b is outside the clip window (trivial reject)
5202 } else if (codeA & codeB) {
5206 codeOut = codeA || codeB;
5207 p = this._getEdgeIntersection(a, b, codeOut, bounds);
5208 newCode = this._getBitCode(p, bounds);
5210 if (codeOut === codeA) {
5221 _getEdgeIntersection: function (a, b, code, bounds) {
5227 if (code & 8) { // top
5228 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
5229 } else if (code & 4) { // bottom
5230 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
5231 } else if (code & 2) { // right
5232 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
5233 } else if (code & 1) { // left
5234 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
5238 _getBitCode: function (/*Point*/ p, bounds) {
5241 if (p.x < bounds.min.x) { // left
5243 } else if (p.x > bounds.max.x) { // right
5246 if (p.y < bounds.min.y) { // bottom
5248 } else if (p.y > bounds.max.y) { // top
5255 // square distance (to avoid unnecessary Math.sqrt calls)
5256 _sqDist: function (p1, p2) {
5257 var dx = p2.x - p1.x,
5259 return dx * dx + dy * dy;
5262 // return closest point on segment or distance to that point
5263 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
5268 dot = dx * dx + dy * dy,
5272 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
5286 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
5292 * L.Polyline is used to display polylines on a map.
5295 L.Polyline = L.Path.extend({
5296 initialize: function (latlngs, options) {
5297 L.Path.prototype.initialize.call(this, options);
5299 this._latlngs = this._convertLatLngs(latlngs);
5303 // how much to simplify the polyline on each zoom level
5304 // more = better performance and smoother look, less = more accurate
5309 projectLatlngs: function () {
5310 this._originalPoints = [];
5312 for (var i = 0, len = this._latlngs.length; i < len; i++) {
5313 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
5317 getPathString: function () {
5318 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
5319 str += this._getPathPartStr(this._parts[i]);
5324 getLatLngs: function () {
5325 return this._latlngs;
5328 setLatLngs: function (latlngs) {
5329 this._latlngs = this._convertLatLngs(latlngs);
5330 return this.redraw();
5333 addLatLng: function (latlng) {
5334 this._latlngs.push(L.latLng(latlng));
5335 return this.redraw();
5338 spliceLatLngs: function () { // (Number index, Number howMany)
5339 var removed = [].splice.apply(this._latlngs, arguments);
5340 this._convertLatLngs(this._latlngs, true);
5345 closestLayerPoint: function (p) {
5346 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
5348 for (var j = 0, jLen = parts.length; j < jLen; j++) {
5349 var points = parts[j];
5350 for (var i = 1, len = points.length; i < len; i++) {
5353 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
5354 if (sqDist < minDistance) {
5355 minDistance = sqDist;
5356 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
5361 minPoint.distance = Math.sqrt(minDistance);
5366 getBounds: function () {
5367 return new L.LatLngBounds(this.getLatLngs());
5370 _convertLatLngs: function (latlngs, overwrite) {
5371 var i, len, target = overwrite ? latlngs : [];
5373 for (i = 0, len = latlngs.length; i < len; i++) {
5374 if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
5377 target[i] = L.latLng(latlngs[i]);
5382 _initEvents: function () {
5383 L.Path.prototype._initEvents.call(this);
5386 _getPathPartStr: function (points) {
5387 var round = L.Path.VML;
5389 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
5394 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
5399 _clipPoints: function () {
5400 var points = this._originalPoints,
5401 len = points.length,
5404 if (this.options.noClip) {
5405 this._parts = [points];
5411 var parts = this._parts,
5412 vp = this._map._pathViewport,
5415 for (i = 0, k = 0; i < len - 1; i++) {
5416 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
5421 parts[k] = parts[k] || [];
5422 parts[k].push(segment[0]);
5424 // if segment goes out of screen, or it's the last one, it's the end of the line part
5425 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
5426 parts[k].push(segment[1]);
5432 // simplify each clipped part of the polyline
5433 _simplifyPoints: function () {
5434 var parts = this._parts,
5437 for (var i = 0, len = parts.length; i < len; i++) {
5438 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
5442 _updatePath: function () {
5443 if (!this._map) { return; }
5446 this._simplifyPoints();
5448 L.Path.prototype._updatePath.call(this);
5452 L.polyline = function (latlngs, options) {
5453 return new L.Polyline(latlngs, options);
5458 * L.PolyUtil contains utility functions for polygons (clipping, etc.).
5461 /*jshint bitwise:false */ // allow bitwise operations here
5466 * Sutherland-Hodgeman polygon clipping algorithm.
5467 * Used to avoid rendering parts of a polygon that are not currently visible.
5469 L.PolyUtil.clipPolygon = function (points, bounds) {
5471 edges = [1, 4, 2, 8],
5477 for (i = 0, len = points.length; i < len; i++) {
5478 points[i]._code = lu._getBitCode(points[i], bounds);
5481 // for each edge (left, bottom, right, top)
5482 for (k = 0; k < 4; k++) {
5486 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5490 // if a is inside the clip window
5491 if (!(a._code & edge)) {
5492 // if b is outside the clip window (a->b goes out of screen)
5493 if (b._code & edge) {
5494 p = lu._getEdgeIntersection(b, a, edge, bounds);
5495 p._code = lu._getBitCode(p, bounds);
5496 clippedPoints.push(p);
5498 clippedPoints.push(a);
5500 // else if b is inside the clip window (a->b enters the screen)
5501 } else if (!(b._code & edge)) {
5502 p = lu._getEdgeIntersection(b, a, edge, bounds);
5503 p._code = lu._getBitCode(p, bounds);
5504 clippedPoints.push(p);
5507 points = clippedPoints;
5515 * L.Polygon is used to display polygons on a map.
5518 L.Polygon = L.Polyline.extend({
5523 initialize: function (latlngs, options) {
5526 L.Polyline.prototype.initialize.call(this, latlngs, options);
5528 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5529 this._latlngs = this._convertLatLngs(latlngs[0]);
5530 this._holes = latlngs.slice(1);
5532 for (i = 0, len = this._holes.length; i < len; i++) {
5533 hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
5534 if (hole[0].equals(hole[hole.length - 1])) {
5540 // filter out last point if its equal to the first one
5541 latlngs = this._latlngs;
5543 if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
5548 projectLatlngs: function () {
5549 L.Polyline.prototype.projectLatlngs.call(this);
5551 // project polygon holes points
5552 // TODO move this logic to Polyline to get rid of duplication
5553 this._holePoints = [];
5555 if (!this._holes) { return; }
5557 var i, j, len, len2;
5559 for (i = 0, len = this._holes.length; i < len; i++) {
5560 this._holePoints[i] = [];
5562 for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5563 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5568 _clipPoints: function () {
5569 var points = this._originalPoints,
5572 this._parts = [points].concat(this._holePoints);
5574 if (this.options.noClip) { return; }
5576 for (var i = 0, len = this._parts.length; i < len; i++) {
5577 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5578 if (clipped.length) {
5579 newParts.push(clipped);
5583 this._parts = newParts;
5586 _getPathPartStr: function (points) {
5587 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5588 return str + (L.Browser.svg ? 'z' : 'x');
5592 L.polygon = function (latlngs, options) {
5593 return new L.Polygon(latlngs, options);
5598 * Contains L.MultiPolyline and L.MultiPolygon layers.
5602 function createMulti(Klass) {
5604 return L.FeatureGroup.extend({
5606 initialize: function (latlngs, options) {
5608 this._options = options;
5609 this.setLatLngs(latlngs);
5612 setLatLngs: function (latlngs) {
5614 len = latlngs.length;
5616 this.eachLayer(function (layer) {
5618 layer.setLatLngs(latlngs[i++]);
5620 this.removeLayer(layer);
5625 this.addLayer(new Klass(latlngs[i++], this._options));
5631 getLatLngs: function () {
5634 this.eachLayer(function (layer) {
5635 latlngs.push(layer.getLatLngs());
5643 L.MultiPolyline = createMulti(L.Polyline);
5644 L.MultiPolygon = createMulti(L.Polygon);
5646 L.multiPolyline = function (latlngs, options) {
5647 return new L.MultiPolyline(latlngs, options);
5650 L.multiPolygon = function (latlngs, options) {
5651 return new L.MultiPolygon(latlngs, options);
5657 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5660 L.Rectangle = L.Polygon.extend({
5661 initialize: function (latLngBounds, options) {
5662 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5665 setBounds: function (latLngBounds) {
5666 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5669 _boundsToLatLngs: function (latLngBounds) {
5670 latLngBounds = L.latLngBounds(latLngBounds);
5672 latLngBounds.getSouthWest(),
5673 latLngBounds.getNorthWest(),
5674 latLngBounds.getNorthEast(),
5675 latLngBounds.getSouthEast()
5680 L.rectangle = function (latLngBounds, options) {
5681 return new L.Rectangle(latLngBounds, options);
5686 * L.Circle is a circle overlay (with a certain radius in meters).
5689 L.Circle = L.Path.extend({
5690 initialize: function (latlng, radius, options) {
5691 L.Path.prototype.initialize.call(this, options);
5693 this._latlng = L.latLng(latlng);
5694 this._mRadius = radius;
5701 setLatLng: function (latlng) {
5702 this._latlng = L.latLng(latlng);
5703 return this.redraw();
5706 setRadius: function (radius) {
5707 this._mRadius = radius;
5708 return this.redraw();
5711 projectLatlngs: function () {
5712 var lngRadius = this._getLngRadius(),
5713 latlng = this._latlng,
5714 pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
5716 this._point = this._map.latLngToLayerPoint(latlng);
5717 this._radius = Math.max(this._point.x - pointLeft.x, 1);
5720 getBounds: function () {
5721 var lngRadius = this._getLngRadius(),
5722 latRadius = (this._mRadius / 40075017) * 360,
5723 latlng = this._latlng;
5725 return new L.LatLngBounds(
5726 [latlng.lat - latRadius, latlng.lng - lngRadius],
5727 [latlng.lat + latRadius, latlng.lng + lngRadius]);
5730 getLatLng: function () {
5731 return this._latlng;
5734 getPathString: function () {
5735 var p = this._point,
5738 if (this._checkIfEmpty()) {
5742 if (L.Browser.svg) {
5743 return 'M' + p.x + ',' + (p.y - r) +
5744 'A' + r + ',' + r + ',0,1,1,' +
5745 (p.x - 0.1) + ',' + (p.y - r) + ' z';
5749 return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
5753 getRadius: function () {
5754 return this._mRadius;
5757 // TODO Earth hardcoded, move into projection code!
5759 _getLatRadius: function () {
5760 return (this._mRadius / 40075017) * 360;
5763 _getLngRadius: function () {
5764 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5767 _checkIfEmpty: function () {
5771 var vp = this._map._pathViewport,
5775 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5776 p.x + r < vp.min.x || p.y + r < vp.min.y;
5780 L.circle = function (latlng, radius, options) {
5781 return new L.Circle(latlng, radius, options);
5786 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5789 L.CircleMarker = L.Circle.extend({
5795 initialize: function (latlng, options) {
5796 L.Circle.prototype.initialize.call(this, latlng, null, options);
5797 this._radius = this.options.radius;
5800 projectLatlngs: function () {
5801 this._point = this._map.latLngToLayerPoint(this._latlng);
5804 _updateStyle : function () {
5805 L.Circle.prototype._updateStyle.call(this);
5806 this.setRadius(this.options.radius);
5809 setRadius: function (radius) {
5810 this.options.radius = this._radius = radius;
5811 return this.redraw();
5815 L.circleMarker = function (latlng, options) {
5816 return new L.CircleMarker(latlng, options);
5821 * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
5824 L.Polyline.include(!L.Path.CANVAS ? {} : {
5825 _containsPoint: function (p, closed) {
5826 var i, j, k, len, len2, dist, part,
5827 w = this.options.weight / 2;
5829 if (L.Browser.touch) {
5830 w += 10; // polyline click tolerance on touch devices
5833 for (i = 0, len = this._parts.length; i < len; i++) {
5834 part = this._parts[i];
5835 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5836 if (!closed && (j === 0)) {
5840 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5853 * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
5856 L.Polygon.include(!L.Path.CANVAS ? {} : {
5857 _containsPoint: function (p) {
5863 // TODO optimization: check if within bounds first
5865 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5866 // click on polygon border
5870 // ray casting algorithm for detecting if point is in polygon
5872 for (i = 0, len = this._parts.length; i < len; i++) {
5873 part = this._parts[i];
5875 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5879 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5880 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5892 * Extends L.Circle with Canvas-specific code.
5895 L.Circle.include(!L.Path.CANVAS ? {} : {
5896 _drawPath: function () {
5897 var p = this._point;
5898 this._ctx.beginPath();
5899 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5902 _containsPoint: function (p) {
5903 var center = this._point,
5904 w2 = this.options.stroke ? this.options.weight / 2 : 0;
5906 return (p.distanceTo(center) <= this._radius + w2);
5912 * CircleMarker canvas specific drawing parts.
5915 L.CircleMarker.include(!L.Path.CANVAS ? {} : {
5916 _updateStyle: function () {
5917 L.Path.prototype._updateStyle.call(this);
5923 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
5926 L.GeoJSON = L.FeatureGroup.extend({
5928 initialize: function (geojson, options) {
5929 L.setOptions(this, options);
5934 this.addData(geojson);
5938 addData: function (geojson) {
5939 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
5943 for (i = 0, len = features.length; i < len; i++) {
5944 // Only add this if geometry or geometries are set and not null
5945 feature = features[i];
5946 if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
5947 this.addData(features[i]);
5953 var options = this.options;
5955 if (options.filter && !options.filter(geojson)) { return; }
5957 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng);
5958 layer.feature = L.GeoJSON.asFeature(geojson);
5960 layer.defaultOptions = layer.options;
5961 this.resetStyle(layer);
5963 if (options.onEachFeature) {
5964 options.onEachFeature(geojson, layer);
5967 return this.addLayer(layer);
5970 resetStyle: function (layer) {
5971 var style = this.options.style;
5973 // reset any custom styles
5974 L.Util.extend(layer.options, layer.defaultOptions);
5976 this._setLayerStyle(layer, style);
5980 setStyle: function (style) {
5981 this.eachLayer(function (layer) {
5982 this._setLayerStyle(layer, style);
5986 _setLayerStyle: function (layer, style) {
5987 if (typeof style === 'function') {
5988 style = style(layer.feature);
5990 if (layer.setStyle) {
5991 layer.setStyle(style);
5996 L.extend(L.GeoJSON, {
5997 geometryToLayer: function (geojson, pointToLayer, coordsToLatLng) {
5998 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
5999 coords = geometry.coordinates,
6001 latlng, latlngs, i, len, layer;
6003 coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
6005 switch (geometry.type) {
6007 latlng = coordsToLatLng(coords);
6008 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6011 for (i = 0, len = coords.length; i < len; i++) {
6012 latlng = coordsToLatLng(coords[i]);
6013 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6016 return new L.FeatureGroup(layers);
6019 latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
6020 return new L.Polyline(latlngs);
6023 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6024 return new L.Polygon(latlngs);
6026 case 'MultiLineString':
6027 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6028 return new L.MultiPolyline(latlngs);
6030 case 'MultiPolygon':
6031 latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
6032 return new L.MultiPolygon(latlngs);
6034 case 'GeometryCollection':
6035 for (i = 0, len = geometry.geometries.length; i < len; i++) {
6037 layer = this.geometryToLayer({
6038 geometry: geometry.geometries[i],
6040 properties: geojson.properties
6041 }, pointToLayer, coordsToLatLng);
6045 return new L.FeatureGroup(layers);
6048 throw new Error('Invalid GeoJSON object.');
6052 coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
6053 return new L.LatLng(coords[1], coords[0]);
6056 coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
6060 for (i = 0, len = coords.length; i < len; i++) {
6061 latlng = levelsDeep ?
6062 this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
6063 (coordsToLatLng || this.coordsToLatLng)(coords[i]);
6065 latlngs.push(latlng);
6071 latLngToCoords: function (latLng) {
6072 return [latLng.lng, latLng.lat];
6075 latLngsToCoords: function (latLngs) {
6078 for (var i = 0, len = latLngs.length; i < len; i++) {
6079 coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
6085 getFeature: function (layer, newGeometry) {
6086 return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
6089 asFeature: function (geoJSON) {
6090 if (geoJSON.type === 'Feature') {
6102 var PointToGeoJSON = {
6103 toGeoJSON: function () {
6104 return L.GeoJSON.getFeature(this, {
6106 coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
6111 L.Marker.include(PointToGeoJSON);
6112 L.Circle.include(PointToGeoJSON);
6113 L.CircleMarker.include(PointToGeoJSON);
6115 L.Polyline.include({
6116 toGeoJSON: function () {
6117 return L.GeoJSON.getFeature(this, {
6119 coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
6125 toGeoJSON: function () {
6126 var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
6129 coords[0].push(coords[0][0]);
6132 for (i = 0, len = this._holes.length; i < len; i++) {
6133 hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
6139 return L.GeoJSON.getFeature(this, {
6147 function includeMulti(Klass, type) {
6149 toGeoJSON: function () {
6152 this.eachLayer(function (layer) {
6153 coords.push(layer.toGeoJSON().geometry.coordinates);
6156 return L.GeoJSON.getFeature(this, {
6164 includeMulti(L.MultiPolyline, 'MultiLineString');
6165 includeMulti(L.MultiPolygon, 'MultiPolygon');
6168 L.LayerGroup.include({
6169 toGeoJSON: function () {
6172 this.eachLayer(function (layer) {
6173 if (layer.toGeoJSON) {
6174 features.push(L.GeoJSON.asFeature(layer.toGeoJSON()));
6179 type: 'FeatureCollection',
6185 L.geoJson = function (geojson, options) {
6186 return new L.GeoJSON(geojson, options);
6191 * L.DomEvent contains functions for working with DOM events.
6195 /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
6196 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
6198 var id = L.stamp(fn),
6199 key = '_leaflet_' + type + id,
6200 handler, originalHandler, newType;
6202 if (obj[key]) { return this; }
6204 handler = function (e) {
6205 return fn.call(context || obj, e || L.DomEvent._getEvent());
6208 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6209 return this.addMsTouchListener(obj, type, handler, id);
6211 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
6212 this.addDoubleTapListener(obj, handler, id);
6215 if ('addEventListener' in obj) {
6217 if (type === 'mousewheel') {
6218 obj.addEventListener('DOMMouseScroll', handler, false);
6219 obj.addEventListener(type, handler, false);
6221 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6223 originalHandler = handler;
6224 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
6226 handler = function (e) {
6227 if (!L.DomEvent._checkMouse(obj, e)) { return; }
6228 return originalHandler(e);
6231 obj.addEventListener(newType, handler, false);
6233 } else if (type === 'click' && L.Browser.android) {
6234 originalHandler = handler;
6235 handler = function (e) {
6236 return L.DomEvent._filterClick(e, originalHandler);
6239 obj.addEventListener(type, handler, false);
6241 obj.addEventListener(type, handler, false);
6244 } else if ('attachEvent' in obj) {
6245 obj.attachEvent('on' + type, handler);
6253 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
6255 var id = L.stamp(fn),
6256 key = '_leaflet_' + type + id,
6259 if (!handler) { return this; }
6261 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6262 this.removeMsTouchListener(obj, type, id);
6263 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
6264 this.removeDoubleTapListener(obj, id);
6266 } else if ('removeEventListener' in obj) {
6268 if (type === 'mousewheel') {
6269 obj.removeEventListener('DOMMouseScroll', handler, false);
6270 obj.removeEventListener(type, handler, false);
6272 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6273 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
6275 obj.removeEventListener(type, handler, false);
6277 } else if ('detachEvent' in obj) {
6278 obj.detachEvent('on' + type, handler);
6286 stopPropagation: function (e) {
6288 if (e.stopPropagation) {
6289 e.stopPropagation();
6291 e.cancelBubble = true;
6296 disableClickPropagation: function (el) {
6297 var stop = L.DomEvent.stopPropagation;
6299 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6300 L.DomEvent.addListener(el, L.Draggable.START[i], stop);
6304 .addListener(el, 'click', L.DomEvent._fakeStop)
6305 .addListener(el, 'dblclick', stop);
6308 preventDefault: function (e) {
6310 if (e.preventDefault) {
6313 e.returnValue = false;
6318 stop: function (e) {
6319 return L.DomEvent.preventDefault(e).stopPropagation(e);
6322 getMousePosition: function (e, container) {
6324 var ie7 = L.Browser.ie7,
6325 body = document.body,
6326 docEl = document.documentElement,
6327 x = e.pageX ? e.pageX - body.scrollLeft - docEl.scrollLeft: e.clientX,
6328 y = e.pageY ? e.pageY - body.scrollTop - docEl.scrollTop: e.clientY,
6329 pos = new L.Point(x, y),
6330 rect = container.getBoundingClientRect(),
6331 left = rect.left - container.clientLeft,
6332 top = rect.top - container.clientTop;
6334 // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
6335 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
6336 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
6337 left += container.scrollWidth - container.clientWidth;
6339 // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
6340 // need to add it back in if it is visible; scrollbar is on the left as we are RTL
6341 if (ie7 && L.DomUtil.getStyle(container, 'overflow-y') !== 'hidden' &&
6342 L.DomUtil.getStyle(container, 'overflow') !== 'hidden') {
6347 return pos._subtract(new L.Point(left, top));
6350 getWheelDelta: function (e) {
6355 delta = e.wheelDelta / 120;
6358 delta = -e.detail / 3;
6365 _fakeStop: function (e) {
6366 // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
6367 L.DomEvent._skipEvents[e.type] = true;
6370 _skipped: function (e) {
6371 var skipped = this._skipEvents[e.type];
6372 // reset when checking, as it's only used in map container and propagates outside of the map
6373 this._skipEvents[e.type] = false;
6377 // check if element really left/entered the event target (for mouseenter/mouseleave)
6378 _checkMouse: function (el, e) {
6380 var related = e.relatedTarget;
6382 if (!related) { return true; }
6385 while (related && (related !== el)) {
6386 related = related.parentNode;
6391 return (related !== el);
6394 _getEvent: function () { // evil magic for IE
6395 /*jshint noarg:false */
6396 var e = window.event;
6398 var caller = arguments.callee.caller;
6400 e = caller['arguments'][0];
6401 if (e && window.Event === e.constructor) {
6404 caller = caller.caller;
6410 // this is a horrible workaround for a bug in Android where a single touch triggers two click events
6411 _filterClick: function (e, handler) {
6412 var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
6413 elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
6415 // are they closer together than 1000ms yet more than 100ms?
6416 // Android typically triggers them ~300ms apart while multiple listeners
6417 // on the same event should be triggered far faster;
6418 // or check if click is simulated on the element, and if it is, reject any non-simulated events
6420 if ((elapsed && elapsed > 100 && elapsed < 1000) || (e.target._simulatedClick && !e._simulated)) {
6424 L.DomEvent._lastClick = timeStamp;
6430 L.DomEvent.on = L.DomEvent.addListener;
6431 L.DomEvent.off = L.DomEvent.removeListener;
6435 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
6438 L.Draggable = L.Class.extend({
6439 includes: L.Mixin.Events,
6442 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
6444 mousedown: 'mouseup',
6445 touchstart: 'touchend',
6446 MSPointerDown: 'touchend'
6449 mousedown: 'mousemove',
6450 touchstart: 'touchmove',
6451 MSPointerDown: 'touchmove'
6455 initialize: function (element, dragStartTarget) {
6456 this._element = element;
6457 this._dragStartTarget = dragStartTarget || element;
6460 enable: function () {
6461 if (this._enabled) { return; }
6463 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6464 L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6467 this._enabled = true;
6470 disable: function () {
6471 if (!this._enabled) { return; }
6473 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6474 L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6477 this._enabled = false;
6478 this._moved = false;
6481 _onDown: function (e) {
6482 if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
6485 .stopPropagation(e);
6487 if (L.Draggable._disabled) { return; }
6489 L.DomUtil.disableImageDrag();
6490 L.DomUtil.disableTextSelection();
6492 var first = e.touches ? e.touches[0] : e,
6495 // if touching a link, highlight it
6496 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
6497 L.DomUtil.addClass(el, 'leaflet-active');
6500 this._moved = false;
6502 if (this._moving) { return; }
6504 this._startPoint = new L.Point(first.clientX, first.clientY);
6505 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
6508 .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
6509 .on(document, L.Draggable.END[e.type], this._onUp, this);
6512 _onMove: function (e) {
6513 if (e.touches && e.touches.length > 1) { return; }
6515 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
6516 newPoint = new L.Point(first.clientX, first.clientY),
6517 offset = newPoint.subtract(this._startPoint);
6519 if (!offset.x && !offset.y) { return; }
6521 L.DomEvent.preventDefault(e);
6524 this.fire('dragstart');
6527 this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
6529 if (!L.Browser.touch) {
6530 L.DomUtil.addClass(document.body, 'leaflet-dragging');
6534 this._newPos = this._startPos.add(offset);
6535 this._moving = true;
6537 L.Util.cancelAnimFrame(this._animRequest);
6538 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
6541 _updatePosition: function () {
6542 this.fire('predrag');
6543 L.DomUtil.setPosition(this._element, this._newPos);
6547 _onUp: function () {
6548 if (!L.Browser.touch) {
6549 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
6552 for (var i in L.Draggable.MOVE) {
6554 .off(document, L.Draggable.MOVE[i], this._onMove)
6555 .off(document, L.Draggable.END[i], this._onUp);
6558 L.DomUtil.enableImageDrag();
6559 L.DomUtil.enableTextSelection();
6562 // ensure drag is not fired after dragend
6563 L.Util.cancelAnimFrame(this._animRequest);
6565 this.fire('dragend');
6568 this._moving = false;
6574 L.Handler is a base class for handler classes that are used internally to inject
6575 interaction features like dragging to classes like Map and Marker.
6578 L.Handler = L.Class.extend({
6579 initialize: function (map) {
6583 enable: function () {
6584 if (this._enabled) { return; }
6586 this._enabled = true;
6590 disable: function () {
6591 if (!this._enabled) { return; }
6593 this._enabled = false;
6597 enabled: function () {
6598 return !!this._enabled;
6604 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
6607 L.Map.mergeOptions({
6610 inertia: !L.Browser.android23,
6611 inertiaDeceleration: 3400, // px/s^2
6612 inertiaMaxSpeed: Infinity, // px/s
6613 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
6614 easeLinearity: 0.25,
6616 // TODO refactor, move to CRS
6617 worldCopyJump: false
6620 L.Map.Drag = L.Handler.extend({
6621 addHooks: function () {
6622 if (!this._draggable) {
6623 var map = this._map;
6625 this._draggable = new L.Draggable(map._mapPane, map._container);
6627 this._draggable.on({
6628 'dragstart': this._onDragStart,
6629 'drag': this._onDrag,
6630 'dragend': this._onDragEnd
6633 if (map.options.worldCopyJump) {
6634 this._draggable.on('predrag', this._onPreDrag, this);
6635 map.on('viewreset', this._onViewReset, this);
6637 this._onViewReset();
6640 this._draggable.enable();
6643 removeHooks: function () {
6644 this._draggable.disable();
6647 moved: function () {
6648 return this._draggable && this._draggable._moved;
6651 _onDragStart: function () {
6652 var map = this._map;
6655 map._panAnim.stop();
6662 if (map.options.inertia) {
6663 this._positions = [];
6668 _onDrag: function () {
6669 if (this._map.options.inertia) {
6670 var time = this._lastTime = +new Date(),
6671 pos = this._lastPos = this._draggable._newPos;
6673 this._positions.push(pos);
6674 this._times.push(time);
6676 if (time - this._times[0] > 200) {
6677 this._positions.shift();
6678 this._times.shift();
6687 _onViewReset: function () {
6688 // TODO fix hardcoded Earth values
6689 var pxCenter = this._map.getSize()._divideBy(2),
6690 pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
6692 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6693 this._worldWidth = this._map.project([0, 180]).x;
6696 _onPreDrag: function () {
6697 // TODO refactor to be able to adjust map pane position after zoom
6698 var worldWidth = this._worldWidth,
6699 halfWidth = Math.round(worldWidth / 2),
6700 dx = this._initialWorldOffset,
6701 x = this._draggable._newPos.x,
6702 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6703 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6704 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6706 this._draggable._newPos.x = newX;
6709 _onDragEnd: function () {
6710 var map = this._map,
6711 options = map.options,
6712 delay = +new Date() - this._lastTime,
6714 noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6716 map.fire('dragend');
6719 map.fire('moveend');
6723 var direction = this._lastPos.subtract(this._positions[0]),
6724 duration = (this._lastTime + delay - this._times[0]) / 1000,
6725 ease = options.easeLinearity,
6727 speedVector = direction.multiplyBy(ease / duration),
6728 speed = speedVector.distanceTo([0, 0]),
6730 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6731 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6733 decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6734 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6736 if (!offset.x || !offset.y) {
6737 map.fire('moveend');
6740 L.Util.requestAnimFrame(function () {
6742 duration: decelerationDuration,
6743 easeLinearity: ease,
6752 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6756 * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6759 L.Map.mergeOptions({
6760 doubleClickZoom: true
6763 L.Map.DoubleClickZoom = L.Handler.extend({
6764 addHooks: function () {
6765 this._map.on('dblclick', this._onDoubleClick, this);
6768 removeHooks: function () {
6769 this._map.off('dblclick', this._onDoubleClick, this);
6772 _onDoubleClick: function (e) {
6773 var map = this._map,
6774 zoom = map.getZoom() + 1;
6776 if (map.options.doubleClickZoom === 'center') {
6779 map.setZoomAround(e.containerPoint, zoom);
6784 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
6788 * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
6791 L.Map.mergeOptions({
6792 scrollWheelZoom: true
6795 L.Map.ScrollWheelZoom = L.Handler.extend({
6796 addHooks: function () {
6797 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
6798 L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6802 removeHooks: function () {
6803 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
6804 L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6807 _onWheelScroll: function (e) {
6808 var delta = L.DomEvent.getWheelDelta(e);
6810 this._delta += delta;
6811 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
6813 if (!this._startTime) {
6814 this._startTime = +new Date();
6817 var left = Math.max(40 - (+new Date() - this._startTime), 0);
6819 clearTimeout(this._timer);
6820 this._timer = setTimeout(L.bind(this._performZoom, this), left);
6822 L.DomEvent.preventDefault(e);
6823 L.DomEvent.stopPropagation(e);
6826 _performZoom: function () {
6827 var map = this._map,
6828 delta = this._delta,
6829 zoom = map.getZoom();
6831 delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
6832 delta = Math.max(Math.min(delta, 4), -4);
6833 delta = map._limitZoom(zoom + delta) - zoom;
6836 this._startTime = null;
6838 if (!delta) { return; }
6840 if (map.options.scrollWheelZoom === 'center') {
6841 map.setZoom(zoom + delta);
6843 map.setZoomAround(this._lastMousePos, zoom + delta);
6848 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
6852 * Extends the event handling code with double tap support for mobile browsers.
6855 L.extend(L.DomEvent, {
6857 _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
6858 _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
6860 // inspired by Zepto touch code by Thomas Fuchs
6861 addDoubleTapListener: function (obj, handler, id) {
6867 touchstart = this._touchstart,
6868 touchend = this._touchend,
6869 trackedTouches = [];
6871 function onTouchStart(e) {
6874 if (L.Browser.msTouch) {
6875 trackedTouches.push(e.pointerId);
6876 count = trackedTouches.length;
6878 count = e.touches.length;
6884 var now = Date.now(),
6885 delta = now - (last || now);
6887 touch = e.touches ? e.touches[0] : e;
6888 doubleTap = (delta > 0 && delta <= delay);
6892 function onTouchEnd(e) {
6893 if (L.Browser.msTouch) {
6894 var idx = trackedTouches.indexOf(e.pointerId);
6898 trackedTouches.splice(idx, 1);
6902 if (L.Browser.msTouch) {
6903 // work around .type being readonly with MSPointer* events
6907 // jshint forin:false
6908 for (var i in touch) {
6910 if (typeof prop === 'function') {
6911 newTouch[i] = prop.bind(touch);
6918 touch.type = 'dblclick';
6923 obj[pre + touchstart + id] = onTouchStart;
6924 obj[pre + touchend + id] = onTouchEnd;
6926 // on msTouch we need to listen on the document, otherwise a drag starting on the map and moving off screen
6927 // will not come through to us, so we will lose track of how many touches are ongoing
6928 var endElement = L.Browser.msTouch ? document.documentElement : obj;
6930 obj.addEventListener(touchstart, onTouchStart, false);
6931 endElement.addEventListener(touchend, onTouchEnd, false);
6933 if (L.Browser.msTouch) {
6934 endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
6940 removeDoubleTapListener: function (obj, id) {
6941 var pre = '_leaflet_';
6943 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
6944 (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(
6945 this._touchend, obj[pre + this._touchend + id], false);
6947 if (L.Browser.msTouch) {
6948 document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
6957 * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
6960 L.extend(L.DomEvent, {
6963 _msDocumentListener: false,
6965 // Provides a touch events wrapper for msPointer events.
6966 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
6968 addMsTouchListener: function (obj, type, handler, id) {
6972 return this.addMsTouchListenerStart(obj, type, handler, id);
6974 return this.addMsTouchListenerEnd(obj, type, handler, id);
6976 return this.addMsTouchListenerMove(obj, type, handler, id);
6978 throw 'Unknown touch event type';
6982 addMsTouchListenerStart: function (obj, type, handler, id) {
6983 var pre = '_leaflet_',
6984 touches = this._msTouches;
6986 var cb = function (e) {
6988 var alreadyInArray = false;
6989 for (var i = 0; i < touches.length; i++) {
6990 if (touches[i].pointerId === e.pointerId) {
6991 alreadyInArray = true;
6995 if (!alreadyInArray) {
6999 e.touches = touches.slice();
7000 e.changedTouches = [e];
7005 obj[pre + 'touchstart' + id] = cb;
7006 obj.addEventListener('MSPointerDown', cb, false);
7008 // need to also listen for end events to keep the _msTouches list accurate
7009 // this needs to be on the body and never go away
7010 if (!this._msDocumentListener) {
7011 var internalCb = function (e) {
7012 for (var i = 0; i < touches.length; i++) {
7013 if (touches[i].pointerId === e.pointerId) {
7014 touches.splice(i, 1);
7019 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
7020 document.documentElement.addEventListener('MSPointerUp', internalCb, false);
7021 document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
7023 this._msDocumentListener = true;
7029 addMsTouchListenerMove: function (obj, type, handler, id) {
7030 var pre = '_leaflet_',
7031 touches = this._msTouches;
7035 // don't fire touch moves when mouse isn't down
7036 if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) { return; }
7038 for (var i = 0; i < touches.length; i++) {
7039 if (touches[i].pointerId === e.pointerId) {
7045 e.touches = touches.slice();
7046 e.changedTouches = [e];
7051 obj[pre + 'touchmove' + id] = cb;
7052 obj.addEventListener('MSPointerMove', cb, false);
7057 addMsTouchListenerEnd: function (obj, type, handler, id) {
7058 var pre = '_leaflet_',
7059 touches = this._msTouches;
7061 var cb = function (e) {
7062 for (var i = 0; i < touches.length; i++) {
7063 if (touches[i].pointerId === e.pointerId) {
7064 touches.splice(i, 1);
7069 e.touches = touches.slice();
7070 e.changedTouches = [e];
7075 obj[pre + 'touchend' + id] = cb;
7076 obj.addEventListener('MSPointerUp', cb, false);
7077 obj.addEventListener('MSPointerCancel', cb, false);
7082 removeMsTouchListener: function (obj, type, id) {
7083 var pre = '_leaflet_',
7084 cb = obj[pre + type + id];
7088 obj.removeEventListener('MSPointerDown', cb, false);
7091 obj.removeEventListener('MSPointerMove', cb, false);
7094 obj.removeEventListener('MSPointerUp', cb, false);
7095 obj.removeEventListener('MSPointerCancel', cb, false);
7105 * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
7108 L.Map.mergeOptions({
7109 touchZoom: L.Browser.touch && !L.Browser.android23
7112 L.Map.TouchZoom = L.Handler.extend({
7113 addHooks: function () {
7114 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
7117 removeHooks: function () {
7118 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
7121 _onTouchStart: function (e) {
7122 var map = this._map;
7124 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
7126 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7127 p2 = map.mouseEventToLayerPoint(e.touches[1]),
7128 viewCenter = map._getCenterLayerPoint();
7130 this._startCenter = p1.add(p2)._divideBy(2);
7131 this._startDist = p1.distanceTo(p2);
7133 this._moved = false;
7134 this._zooming = true;
7136 this._centerOffset = viewCenter.subtract(this._startCenter);
7139 map._panAnim.stop();
7143 .on(document, 'touchmove', this._onTouchMove, this)
7144 .on(document, 'touchend', this._onTouchEnd, this);
7146 L.DomEvent.preventDefault(e);
7149 _onTouchMove: function (e) {
7150 var map = this._map;
7152 if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
7154 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7155 p2 = map.mouseEventToLayerPoint(e.touches[1]);
7157 this._scale = p1.distanceTo(p2) / this._startDist;
7158 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
7160 if (this._scale === 1) { return; }
7163 L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
7172 L.Util.cancelAnimFrame(this._animRequest);
7173 this._animRequest = L.Util.requestAnimFrame(
7174 this._updateOnMove, this, true, this._map._container);
7176 L.DomEvent.preventDefault(e);
7179 _updateOnMove: function () {
7180 var map = this._map,
7181 origin = this._getScaleOrigin(),
7182 center = map.layerPointToLatLng(origin),
7183 zoom = map.getScaleZoom(this._scale);
7185 map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta);
7188 _onTouchEnd: function () {
7189 if (!this._moved || !this._zooming) {
7190 this._zooming = false;
7194 var map = this._map;
7196 this._zooming = false;
7197 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
7198 L.Util.cancelAnimFrame(this._animRequest);
7201 .off(document, 'touchmove', this._onTouchMove)
7202 .off(document, 'touchend', this._onTouchEnd);
7204 var origin = this._getScaleOrigin(),
7205 center = map.layerPointToLatLng(origin),
7207 oldZoom = map.getZoom(),
7208 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
7209 roundZoomDelta = (floatZoomDelta > 0 ?
7210 Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
7212 zoom = map._limitZoom(oldZoom + roundZoomDelta),
7213 scale = map.getZoomScale(zoom) / this._scale;
7215 map._animateZoom(center, zoom, origin, scale);
7218 _getScaleOrigin: function () {
7219 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
7220 return this._startCenter.add(centerOffset);
7224 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
7228 * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
7231 L.Map.mergeOptions({
7236 L.Map.Tap = L.Handler.extend({
7237 addHooks: function () {
7238 L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
7241 removeHooks: function () {
7242 L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
7245 _onDown: function (e) {
7246 if (!e.touches) { return; }
7248 L.DomEvent.preventDefault(e);
7250 this._fireClick = true;
7252 // don't simulate click or track longpress if more than 1 touch
7253 if (e.touches.length > 1) {
7254 this._fireClick = false;
7255 clearTimeout(this._holdTimeout);
7259 var first = e.touches[0],
7262 this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
7264 // if touching a link, highlight it
7265 if (el.tagName.toLowerCase() === 'a') {
7266 L.DomUtil.addClass(el, 'leaflet-active');
7269 // simulate long hold but setting a timeout
7270 this._holdTimeout = setTimeout(L.bind(function () {
7271 if (this._isTapValid()) {
7272 this._fireClick = false;
7274 this._simulateEvent('contextmenu', first);
7279 .on(document, 'touchmove', this._onMove, this)
7280 .on(document, 'touchend', this._onUp, this);
7283 _onUp: function (e) {
7284 clearTimeout(this._holdTimeout);
7287 .off(document, 'touchmove', this._onMove, this)
7288 .off(document, 'touchend', this._onUp, this);
7290 if (this._fireClick && e && e.changedTouches) {
7292 var first = e.changedTouches[0],
7295 if (el.tagName.toLowerCase() === 'a') {
7296 L.DomUtil.removeClass(el, 'leaflet-active');
7299 // simulate click if the touch didn't move too much
7300 if (this._isTapValid()) {
7301 this._simulateEvent('click', first);
7306 _isTapValid: function () {
7307 return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
7310 _onMove: function (e) {
7311 var first = e.touches[0];
7312 this._newPos = new L.Point(first.clientX, first.clientY);
7315 _simulateEvent: function (type, e) {
7316 var simulatedEvent = document.createEvent('MouseEvents');
7318 simulatedEvent._simulated = true;
7319 e.target._simulatedClick = true;
7321 simulatedEvent.initMouseEvent(
7322 type, true, true, window, 1,
7323 e.screenX, e.screenY,
7324 e.clientX, e.clientY,
7325 false, false, false, false, 0, null);
7327 e.target.dispatchEvent(simulatedEvent);
7331 if (L.Browser.touch && !L.Browser.msTouch) {
7332 L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
7337 * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
7338 * (zoom to a selected bounding box), enabled by default.
7341 L.Map.mergeOptions({
7345 L.Map.BoxZoom = L.Handler.extend({
7346 initialize: function (map) {
7348 this._container = map._container;
7349 this._pane = map._panes.overlayPane;
7352 addHooks: function () {
7353 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
7356 removeHooks: function () {
7357 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
7360 _onMouseDown: function (e) {
7361 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
7363 L.DomUtil.disableTextSelection();
7364 L.DomUtil.disableImageDrag();
7366 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
7368 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
7369 L.DomUtil.setPosition(this._box, this._startLayerPoint);
7371 //TODO refactor: move cursor to styles
7372 this._container.style.cursor = 'crosshair';
7375 .on(document, 'mousemove', this._onMouseMove, this)
7376 .on(document, 'mouseup', this._onMouseUp, this)
7377 .on(document, 'keydown', this._onKeyDown, this);
7379 this._map.fire('boxzoomstart');
7382 _onMouseMove: function (e) {
7383 var startPoint = this._startLayerPoint,
7386 layerPoint = this._map.mouseEventToLayerPoint(e),
7387 offset = layerPoint.subtract(startPoint),
7389 newPos = new L.Point(
7390 Math.min(layerPoint.x, startPoint.x),
7391 Math.min(layerPoint.y, startPoint.y));
7393 L.DomUtil.setPosition(box, newPos);
7395 // TODO refactor: remove hardcoded 4 pixels
7396 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
7397 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
7400 _finish: function () {
7401 this._pane.removeChild(this._box);
7402 this._container.style.cursor = '';
7404 L.DomUtil.enableTextSelection();
7405 L.DomUtil.enableImageDrag();
7408 .off(document, 'mousemove', this._onMouseMove)
7409 .off(document, 'mouseup', this._onMouseUp)
7410 .off(document, 'keydown', this._onKeyDown);
7413 _onMouseUp: function (e) {
7417 var map = this._map,
7418 layerPoint = map.mouseEventToLayerPoint(e);
7420 if (this._startLayerPoint.equals(layerPoint)) { return; }
7422 var bounds = new L.LatLngBounds(
7423 map.layerPointToLatLng(this._startLayerPoint),
7424 map.layerPointToLatLng(layerPoint));
7426 map.fitBounds(bounds);
7428 map.fire('boxzoomend', {
7429 boxZoomBounds: bounds
7433 _onKeyDown: function (e) {
7434 if (e.keyCode === 27) {
7440 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
7444 * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
7447 L.Map.mergeOptions({
7449 keyboardPanOffset: 80,
7450 keyboardZoomOffset: 1
7453 L.Map.Keyboard = L.Handler.extend({
7460 zoomIn: [187, 107, 61],
7461 zoomOut: [189, 109, 173]
7464 initialize: function (map) {
7467 this._setPanOffset(map.options.keyboardPanOffset);
7468 this._setZoomOffset(map.options.keyboardZoomOffset);
7471 addHooks: function () {
7472 var container = this._map._container;
7474 // make the container focusable by tabbing
7475 if (container.tabIndex === -1) {
7476 container.tabIndex = '0';
7480 .on(container, 'focus', this._onFocus, this)
7481 .on(container, 'blur', this._onBlur, this)
7482 .on(container, 'mousedown', this._onMouseDown, this);
7485 .on('focus', this._addHooks, this)
7486 .on('blur', this._removeHooks, this);
7489 removeHooks: function () {
7490 this._removeHooks();
7492 var container = this._map._container;
7495 .off(container, 'focus', this._onFocus, this)
7496 .off(container, 'blur', this._onBlur, this)
7497 .off(container, 'mousedown', this._onMouseDown, this);
7500 .off('focus', this._addHooks, this)
7501 .off('blur', this._removeHooks, this);
7504 _onMouseDown: function () {
7505 if (this._focused) { return; }
7507 var body = document.body,
7508 docEl = document.documentElement,
7509 top = body.scrollTop || docEl.scrollTop,
7510 left = body.scrollTop || docEl.scrollLeft;
7512 this._map._container.focus();
7514 window.scrollTo(left, top);
7517 _onFocus: function () {
7518 this._focused = true;
7519 this._map.fire('focus');
7522 _onBlur: function () {
7523 this._focused = false;
7524 this._map.fire('blur');
7527 _setPanOffset: function (pan) {
7528 var keys = this._panKeys = {},
7529 codes = this.keyCodes,
7532 for (i = 0, len = codes.left.length; i < len; i++) {
7533 keys[codes.left[i]] = [-1 * pan, 0];
7535 for (i = 0, len = codes.right.length; i < len; i++) {
7536 keys[codes.right[i]] = [pan, 0];
7538 for (i = 0, len = codes.down.length; i < len; i++) {
7539 keys[codes.down[i]] = [0, pan];
7541 for (i = 0, len = codes.up.length; i < len; i++) {
7542 keys[codes.up[i]] = [0, -1 * pan];
7546 _setZoomOffset: function (zoom) {
7547 var keys = this._zoomKeys = {},
7548 codes = this.keyCodes,
7551 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
7552 keys[codes.zoomIn[i]] = zoom;
7554 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
7555 keys[codes.zoomOut[i]] = -zoom;
7559 _addHooks: function () {
7560 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
7563 _removeHooks: function () {
7564 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
7567 _onKeyDown: function (e) {
7568 var key = e.keyCode,
7571 if (key in this._panKeys) {
7573 if (map._panAnim && map._panAnim._inProgress) { return; }
7575 map.panBy(this._panKeys[key]);
7577 if (map.options.maxBounds) {
7578 map.panInsideBounds(map.options.maxBounds);
7581 } else if (key in this._zoomKeys) {
7582 map.setZoom(map.getZoom() + this._zoomKeys[key]);
7592 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
7596 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
7599 L.Handler.MarkerDrag = L.Handler.extend({
7600 initialize: function (marker) {
7601 this._marker = marker;
7604 addHooks: function () {
7605 var icon = this._marker._icon;
7606 if (!this._draggable) {
7607 this._draggable = new L.Draggable(icon, icon);
7611 .on('dragstart', this._onDragStart, this)
7612 .on('drag', this._onDrag, this)
7613 .on('dragend', this._onDragEnd, this);
7614 this._draggable.enable();
7617 removeHooks: function () {
7619 .off('dragstart', this._onDragStart, this)
7620 .off('drag', this._onDrag, this)
7621 .off('dragend', this._onDragEnd, this);
7623 this._draggable.disable();
7626 moved: function () {
7627 return this._draggable && this._draggable._moved;
7630 _onDragStart: function () {
7637 _onDrag: function () {
7638 var marker = this._marker,
7639 shadow = marker._shadow,
7640 iconPos = L.DomUtil.getPosition(marker._icon),
7641 latlng = marker._map.layerPointToLatLng(iconPos);
7643 // update shadow position
7645 L.DomUtil.setPosition(shadow, iconPos);
7648 marker._latlng = latlng;
7651 .fire('move', {latlng: latlng})
7655 _onDragEnd: function () {
7664 * L.Control is a base class for implementing map controls. Handles positioning.
7665 * All other controls extend from this class.
7668 L.Control = L.Class.extend({
7670 position: 'topright'
7673 initialize: function (options) {
7674 L.setOptions(this, options);
7677 getPosition: function () {
7678 return this.options.position;
7681 setPosition: function (position) {
7682 var map = this._map;
7685 map.removeControl(this);
7688 this.options.position = position;
7691 map.addControl(this);
7697 getContainer: function () {
7698 return this._container;
7701 addTo: function (map) {
7704 var container = this._container = this.onAdd(map),
7705 pos = this.getPosition(),
7706 corner = map._controlCorners[pos];
7708 L.DomUtil.addClass(container, 'leaflet-control');
7710 if (pos.indexOf('bottom') !== -1) {
7711 corner.insertBefore(container, corner.firstChild);
7713 corner.appendChild(container);
7719 removeFrom: function (map) {
7720 var pos = this.getPosition(),
7721 corner = map._controlCorners[pos];
7723 corner.removeChild(this._container);
7726 if (this.onRemove) {
7734 L.control = function (options) {
7735 return new L.Control(options);
7739 // adds control-related methods to L.Map
7742 addControl: function (control) {
7743 control.addTo(this);
7747 removeControl: function (control) {
7748 control.removeFrom(this);
7752 _initControlPos: function () {
7753 var corners = this._controlCorners = {},
7755 container = this._controlContainer =
7756 L.DomUtil.create('div', l + 'control-container', this._container);
7758 function createCorner(vSide, hSide) {
7759 var className = l + vSide + ' ' + l + hSide;
7761 corners[vSide + hSide] = L.DomUtil.create('div', className, container);
7764 createCorner('top', 'left');
7765 createCorner('top', 'right');
7766 createCorner('bottom', 'left');
7767 createCorner('bottom', 'right');
7770 _clearControlPos: function () {
7771 this._container.removeChild(this._controlContainer);
7777 * L.Control.Zoom is used for the default zoom buttons on the map.
7780 L.Control.Zoom = L.Control.extend({
7785 onAdd: function (map) {
7786 var zoomName = 'leaflet-control-zoom',
7787 container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
7791 this._zoomInButton = this._createButton(
7792 '+', 'Zoom in', zoomName + '-in', container, this._zoomIn, this);
7793 this._zoomOutButton = this._createButton(
7794 '-', 'Zoom out', zoomName + '-out', container, this._zoomOut, this);
7796 map.on('zoomend zoomlevelschange', this._updateDisabled, this);
7801 onRemove: function (map) {
7802 map.off('zoomend zoomlevelschange', this._updateDisabled, this);
7805 _zoomIn: function (e) {
7806 this._map.zoomIn(e.shiftKey ? 3 : 1);
7809 _zoomOut: function (e) {
7810 this._map.zoomOut(e.shiftKey ? 3 : 1);
7813 _createButton: function (html, title, className, container, fn, context) {
7814 var link = L.DomUtil.create('a', className, container);
7815 link.innerHTML = html;
7819 var stop = L.DomEvent.stopPropagation;
7822 .on(link, 'click', stop)
7823 .on(link, 'mousedown', stop)
7824 .on(link, 'dblclick', stop)
7825 .on(link, 'click', L.DomEvent.preventDefault)
7826 .on(link, 'click', fn, context);
7831 _updateDisabled: function () {
7832 var map = this._map,
7833 className = 'leaflet-disabled';
7835 L.DomUtil.removeClass(this._zoomInButton, className);
7836 L.DomUtil.removeClass(this._zoomOutButton, className);
7838 if (map._zoom === map.getMinZoom()) {
7839 L.DomUtil.addClass(this._zoomOutButton, className);
7841 if (map._zoom === map.getMaxZoom()) {
7842 L.DomUtil.addClass(this._zoomInButton, className);
7847 L.Map.mergeOptions({
7851 L.Map.addInitHook(function () {
7852 if (this.options.zoomControl) {
7853 this.zoomControl = new L.Control.Zoom();
7854 this.addControl(this.zoomControl);
7858 L.control.zoom = function (options) {
7859 return new L.Control.Zoom(options);
7865 * L.Control.Attribution is used for displaying attribution on the map (added by default).
7868 L.Control.Attribution = L.Control.extend({
7870 position: 'bottomright',
7871 prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
7874 initialize: function (options) {
7875 L.setOptions(this, options);
7877 this._attributions = {};
7880 onAdd: function (map) {
7881 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
7882 L.DomEvent.disableClickPropagation(this._container);
7885 .on('layeradd', this._onLayerAdd, this)
7886 .on('layerremove', this._onLayerRemove, this);
7890 return this._container;
7893 onRemove: function (map) {
7895 .off('layeradd', this._onLayerAdd)
7896 .off('layerremove', this._onLayerRemove);
7900 setPrefix: function (prefix) {
7901 this.options.prefix = prefix;
7906 addAttribution: function (text) {
7907 if (!text) { return; }
7909 if (!this._attributions[text]) {
7910 this._attributions[text] = 0;
7912 this._attributions[text]++;
7919 removeAttribution: function (text) {
7920 if (!text) { return; }
7922 if (this._attributions[text]) {
7923 this._attributions[text]--;
7930 _update: function () {
7931 if (!this._map) { return; }
7935 for (var i in this._attributions) {
7936 if (this._attributions[i]) {
7941 var prefixAndAttribs = [];
7943 if (this.options.prefix) {
7944 prefixAndAttribs.push(this.options.prefix);
7946 if (attribs.length) {
7947 prefixAndAttribs.push(attribs.join(', '));
7950 this._container.innerHTML = prefixAndAttribs.join(' | ');
7953 _onLayerAdd: function (e) {
7954 if (e.layer.getAttribution) {
7955 this.addAttribution(e.layer.getAttribution());
7959 _onLayerRemove: function (e) {
7960 if (e.layer.getAttribution) {
7961 this.removeAttribution(e.layer.getAttribution());
7966 L.Map.mergeOptions({
7967 attributionControl: true
7970 L.Map.addInitHook(function () {
7971 if (this.options.attributionControl) {
7972 this.attributionControl = (new L.Control.Attribution()).addTo(this);
7976 L.control.attribution = function (options) {
7977 return new L.Control.Attribution(options);
7982 * L.Control.Scale is used for displaying metric/imperial scale on the map.
7985 L.Control.Scale = L.Control.extend({
7987 position: 'bottomleft',
7991 updateWhenIdle: false
7994 onAdd: function (map) {
7997 var className = 'leaflet-control-scale',
7998 container = L.DomUtil.create('div', className),
7999 options = this.options;
8001 this._addScales(options, className, container);
8003 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8004 map.whenReady(this._update, this);
8009 onRemove: function (map) {
8010 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8013 _addScales: function (options, className, container) {
8014 if (options.metric) {
8015 this._mScale = L.DomUtil.create('div', className + '-line', container);
8017 if (options.imperial) {
8018 this._iScale = L.DomUtil.create('div', className + '-line', container);
8022 _update: function () {
8023 var bounds = this._map.getBounds(),
8024 centerLat = bounds.getCenter().lat,
8025 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
8026 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
8028 size = this._map.getSize(),
8029 options = this.options,
8033 maxMeters = dist * (options.maxWidth / size.x);
8036 this._updateScales(options, maxMeters);
8039 _updateScales: function (options, maxMeters) {
8040 if (options.metric && maxMeters) {
8041 this._updateMetric(maxMeters);
8044 if (options.imperial && maxMeters) {
8045 this._updateImperial(maxMeters);
8049 _updateMetric: function (maxMeters) {
8050 var meters = this._getRoundNum(maxMeters);
8052 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
8053 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
8056 _updateImperial: function (maxMeters) {
8057 var maxFeet = maxMeters * 3.2808399,
8058 scale = this._iScale,
8059 maxMiles, miles, feet;
8061 if (maxFeet > 5280) {
8062 maxMiles = maxFeet / 5280;
8063 miles = this._getRoundNum(maxMiles);
8065 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
8066 scale.innerHTML = miles + ' mi';
8069 feet = this._getRoundNum(maxFeet);
8071 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
8072 scale.innerHTML = feet + ' ft';
8076 _getScaleWidth: function (ratio) {
8077 return Math.round(this.options.maxWidth * ratio) - 10;
8080 _getRoundNum: function (num) {
8081 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
8084 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
8090 L.control.scale = function (options) {
8091 return new L.Control.Scale(options);
8096 * L.Control.Layers is a control to allow users to switch between different layers on the map.
8099 L.Control.Layers = L.Control.extend({
8102 position: 'topright',
8106 initialize: function (baseLayers, overlays, options) {
8107 L.setOptions(this, options);
8110 this._lastZIndex = 0;
8111 this._handlingClick = false;
8113 for (var i in baseLayers) {
8114 this._addLayer(baseLayers[i], i);
8117 for (i in overlays) {
8118 this._addLayer(overlays[i], i, true);
8122 onAdd: function (map) {
8127 .on('layeradd', this._onLayerChange, this)
8128 .on('layerremove', this._onLayerChange, this);
8130 return this._container;
8133 onRemove: function (map) {
8135 .off('layeradd', this._onLayerChange)
8136 .off('layerremove', this._onLayerChange);
8139 addBaseLayer: function (layer, name) {
8140 this._addLayer(layer, name);
8145 addOverlay: function (layer, name) {
8146 this._addLayer(layer, name, true);
8151 removeLayer: function (layer) {
8152 var id = L.stamp(layer);
8153 delete this._layers[id];
8158 _initLayout: function () {
8159 var className = 'leaflet-control-layers',
8160 container = this._container = L.DomUtil.create('div', className);
8162 //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
8163 container.setAttribute('aria-haspopup', true);
8165 if (!L.Browser.touch) {
8166 L.DomEvent.disableClickPropagation(container);
8167 L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
8169 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
8172 var form = this._form = L.DomUtil.create('form', className + '-list');
8174 if (this.options.collapsed) {
8175 if (!L.Browser.android) {
8177 .on(container, 'mouseover', this._expand, this)
8178 .on(container, 'mouseout', this._collapse, this);
8180 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
8182 link.title = 'Layers';
8184 if (L.Browser.touch) {
8186 .on(link, 'click', L.DomEvent.stop)
8187 .on(link, 'click', this._expand, this);
8190 L.DomEvent.on(link, 'focus', this._expand, this);
8193 this._map.on('click', this._collapse, this);
8194 // TODO keyboard accessibility
8199 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
8200 this._separator = L.DomUtil.create('div', className + '-separator', form);
8201 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
8203 container.appendChild(form);
8206 _addLayer: function (layer, name, overlay) {
8207 var id = L.stamp(layer);
8209 this._layers[id] = {
8215 if (this.options.autoZIndex && layer.setZIndex) {
8217 layer.setZIndex(this._lastZIndex);
8221 _update: function () {
8222 if (!this._container) {
8226 this._baseLayersList.innerHTML = '';
8227 this._overlaysList.innerHTML = '';
8229 var baseLayersPresent = false,
8230 overlaysPresent = false,
8233 for (i in this._layers) {
8234 obj = this._layers[i];
8236 overlaysPresent = overlaysPresent || obj.overlay;
8237 baseLayersPresent = baseLayersPresent || !obj.overlay;
8240 this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
8243 _onLayerChange: function (e) {
8244 var obj = this._layers[L.stamp(e.layer)];
8246 if (!obj) { return; }
8248 if (!this._handlingClick) {
8252 var type = obj.overlay ?
8253 (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
8254 (e.type === 'layeradd' ? 'baselayerchange' : null);
8257 this._map.fire(type, obj);
8261 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
8262 _createRadioElement: function (name, checked) {
8264 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
8266 radioHtml += ' checked="checked"';
8270 var radioFragment = document.createElement('div');
8271 radioFragment.innerHTML = radioHtml;
8273 return radioFragment.firstChild;
8276 _addItem: function (obj) {
8277 var label = document.createElement('label'),
8279 checked = this._map.hasLayer(obj.layer);
8282 input = document.createElement('input');
8283 input.type = 'checkbox';
8284 input.className = 'leaflet-control-layers-selector';
8285 input.defaultChecked = checked;
8287 input = this._createRadioElement('leaflet-base-layers', checked);
8290 input.layerId = L.stamp(obj.layer);
8292 L.DomEvent.on(input, 'click', this._onInputClick, this);
8294 var name = document.createElement('span');
8295 name.innerHTML = ' ' + obj.name;
8297 label.appendChild(input);
8298 label.appendChild(name);
8300 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
8301 container.appendChild(label);
8306 _onInputClick: function () {
8308 inputs = this._form.getElementsByTagName('input'),
8309 inputsLen = inputs.length;
8311 this._handlingClick = true;
8313 for (i = 0; i < inputsLen; i++) {
8315 obj = this._layers[input.layerId];
8317 if (input.checked && !this._map.hasLayer(obj.layer)) {
8318 this._map.addLayer(obj.layer);
8320 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
8321 this._map.removeLayer(obj.layer);
8325 this._handlingClick = false;
8328 _expand: function () {
8329 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
8332 _collapse: function () {
8333 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
8337 L.control.layers = function (baseLayers, overlays, options) {
8338 return new L.Control.Layers(baseLayers, overlays, options);
8343 * L.PosAnimation is used by Leaflet internally for pan animations.
8346 L.PosAnimation = L.Class.extend({
8347 includes: L.Mixin.Events,
8349 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8353 this._inProgress = true;
8354 this._newPos = newPos;
8358 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
8359 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
8361 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8362 L.DomUtil.setPosition(el, newPos);
8364 // toggle reflow, Chrome flickers for some reason if you don't do this
8365 L.Util.falseFn(el.offsetWidth);
8367 // there's no native way to track value updates of transitioned properties, so we imitate this
8368 this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
8372 if (!this._inProgress) { return; }
8374 // if we just removed the transition property, the element would jump to its final position,
8375 // so we need to make it stay at the current position
8377 L.DomUtil.setPosition(this._el, this._getPos());
8378 this._onTransitionEnd();
8379 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
8382 _onStep: function () {
8383 var stepPos = this._getPos();
8385 this._onTransitionEnd();
8388 // jshint camelcase: false
8389 // make L.DomUtil.getPosition return intermediate position value during animation
8390 this._el._leaflet_pos = stepPos;
8395 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
8396 // we need to parse computed style (in case of transform it returns matrix string)
8398 _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
8400 _getPos: function () {
8401 var left, top, matches,
8403 style = window.getComputedStyle(el);
8405 if (L.Browser.any3d) {
8406 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
8407 if (!matches) { return; }
8408 left = parseFloat(matches[1]);
8409 top = parseFloat(matches[2]);
8411 left = parseFloat(style.left);
8412 top = parseFloat(style.top);
8415 return new L.Point(left, top, true);
8418 _onTransitionEnd: function () {
8419 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8421 if (!this._inProgress) { return; }
8422 this._inProgress = false;
8424 this._el.style[L.DomUtil.TRANSITION] = '';
8426 // jshint camelcase: false
8427 // make sure L.DomUtil.getPosition returns the final position value after animation
8428 this._el._leaflet_pos = this._newPos;
8430 clearInterval(this._stepTimer);
8432 this.fire('step').fire('end');
8439 * Extends L.Map to handle panning animations.
8444 setView: function (center, zoom, options) {
8446 zoom = this._limitZoom(zoom);
8447 center = L.latLng(center);
8448 options = options || {};
8450 if (this._panAnim) {
8451 this._panAnim.stop();
8454 if (this._loaded && !options.reset && options !== true) {
8456 if (options.animate !== undefined) {
8457 options.zoom = L.extend({animate: options.animate}, options.zoom);
8458 options.pan = L.extend({animate: options.animate}, options.pan);
8461 // try animating pan or zoom
8462 var animated = (this._zoom !== zoom) ?
8463 this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
8464 this._tryAnimatedPan(center, options.pan);
8467 // prevent resize handler call, the view will refresh after animation anyway
8468 clearTimeout(this._sizeTimer);
8473 // animation didn't start, just reset the map view
8474 this._resetView(center, zoom);
8479 panBy: function (offset, options) {
8480 offset = L.point(offset).round();
8481 options = options || {};
8483 if (!offset.x && !offset.y) {
8487 if (!this._panAnim) {
8488 this._panAnim = new L.PosAnimation();
8491 'step': this._onPanTransitionStep,
8492 'end': this._onPanTransitionEnd
8496 // don't fire movestart if animating inertia
8497 if (!options.noMoveStart) {
8498 this.fire('movestart');
8501 // animate pan unless animate: false specified
8502 if (options.animate !== false) {
8503 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
8505 var newPos = this._getMapPanePos().subtract(offset);
8506 this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
8508 this._rawPanBy(offset);
8509 this.fire('move').fire('moveend');
8515 _onPanTransitionStep: function () {
8519 _onPanTransitionEnd: function () {
8520 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
8521 this.fire('moveend');
8524 _tryAnimatedPan: function (center, options) {
8525 // difference between the new and current centers in pixels
8526 var offset = this._getCenterOffset(center)._floor();
8528 // don't animate too far unless animate: true specified in options
8529 if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
8531 this.panBy(offset, options);
8539 * L.PosAnimation fallback implementation that powers Leaflet pan animations
8540 * in browsers that don't support CSS3 Transitions.
8543 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8545 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8549 this._inProgress = true;
8550 this._duration = duration || 0.25;
8551 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8553 this._startPos = L.DomUtil.getPosition(el);
8554 this._offset = newPos.subtract(this._startPos);
8555 this._startTime = +new Date();
8563 if (!this._inProgress) { return; }
8569 _animate: function () {
8571 this._animId = L.Util.requestAnimFrame(this._animate, this);
8575 _step: function () {
8576 var elapsed = (+new Date()) - this._startTime,
8577 duration = this._duration * 1000;
8579 if (elapsed < duration) {
8580 this._runFrame(this._easeOut(elapsed / duration));
8587 _runFrame: function (progress) {
8588 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8589 L.DomUtil.setPosition(this._el, pos);
8594 _complete: function () {
8595 L.Util.cancelAnimFrame(this._animId);
8597 this._inProgress = false;
8601 _easeOut: function (t) {
8602 return 1 - Math.pow(1 - t, this._easeOutPower);
8608 * Extends L.Map to handle zoom animations.
8611 L.Map.mergeOptions({
8612 zoomAnimation: true,
8613 zoomAnimationThreshold: 4
8616 if (L.DomUtil.TRANSITION) {
8618 L.Map.addInitHook(function () {
8619 // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
8620 this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
8621 L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
8623 // zoom transitions run with the same duration for all layers, so if one of transitionend events
8624 // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
8625 if (this._zoomAnimated) {
8626 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8631 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8633 _catchTransitionEnd: function () {
8634 if (this._animatingZoom) {
8635 this._onZoomTransitionEnd();
8639 _nothingToAnimate: function () {
8640 return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
8643 _tryAnimatedZoom: function (center, zoom, options) {
8645 if (this._animatingZoom) { return true; }
8647 options = options || {};
8649 // don't animate if disabled, not supported or zoom difference is too large
8650 if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
8651 Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
8653 // offset is the pixel coords of the zoom origin relative to the current center
8654 var scale = this.getZoomScale(zoom),
8655 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
8656 origin = this._getCenterLayerPoint()._add(offset);
8658 // don't animate if the zoom origin isn't within one screen from the current center, unless forced
8659 if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
8665 this._animateZoom(center, zoom, origin, scale, null, true);
8670 _animateZoom: function (center, zoom, origin, scale, delta, backwards) {
8672 this._animatingZoom = true;
8674 // put transform transition on all layers with leaflet-zoom-animated class
8675 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8677 // remember what center/zoom to set after animation
8678 this._animateToCenter = center;
8679 this._animateToZoom = zoom;
8681 // disable any dragging during animation
8683 L.Draggable._disabled = true;
8686 this.fire('zoomanim', {
8692 backwards: backwards
8696 _onZoomTransitionEnd: function () {
8698 this._animatingZoom = false;
8700 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8702 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8705 L.Draggable._disabled = false;
8712 Zoom animation logic for L.TileLayer.
8715 L.TileLayer.include({
8716 _animateZoom: function (e) {
8717 if (!this._animating) {
8718 this._animating = true;
8719 this._prepareBgBuffer();
8722 var bg = this._bgBuffer,
8723 transform = L.DomUtil.TRANSFORM,
8724 initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
8725 scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
8727 bg.style[transform] = e.backwards ?
8728 scaleStr + ' ' + initialTransform :
8729 initialTransform + ' ' + scaleStr;
8732 _endZoomAnim: function () {
8733 var front = this._tileContainer,
8734 bg = this._bgBuffer;
8736 front.style.visibility = '';
8737 front.parentNode.appendChild(front); // Bring to fore
8740 L.Util.falseFn(bg.offsetWidth);
8742 this._animating = false;
8745 _clearBgBuffer: function () {
8746 var map = this._map;
8748 if (map && !map._animatingZoom && !map.touchZoom._zooming) {
8749 this._bgBuffer.innerHTML = '';
8750 this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
8754 _prepareBgBuffer: function () {
8756 var front = this._tileContainer,
8757 bg = this._bgBuffer;
8759 // if foreground layer doesn't have many tiles but bg layer does,
8760 // keep the existing bg layer and just zoom it some more
8762 var bgLoaded = this._getLoadedTilesPercentage(bg),
8763 frontLoaded = this._getLoadedTilesPercentage(front);
8765 if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
8767 front.style.visibility = 'hidden';
8768 this._stopLoadingImages(front);
8772 // prepare the buffer to become the front tile pane
8773 bg.style.visibility = 'hidden';
8774 bg.style[L.DomUtil.TRANSFORM] = '';
8776 // switch out the current layer to be the new bg layer (and vice-versa)
8777 this._tileContainer = bg;
8778 bg = this._bgBuffer = front;
8780 this._stopLoadingImages(bg);
8782 //prevent bg buffer from clearing right after zoom
8783 clearTimeout(this._clearBgBufferTimer);
8786 _getLoadedTilesPercentage: function (container) {
8787 var tiles = container.getElementsByTagName('img'),
8790 for (i = 0, len = tiles.length; i < len; i++) {
8791 if (tiles[i].complete) {
8798 // stops loading all tiles in the background layer
8799 _stopLoadingImages: function (container) {
8800 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
8803 for (i = 0, len = tiles.length; i < len; i++) {
8806 if (!tile.complete) {
8807 tile.onload = L.Util.falseFn;
8808 tile.onerror = L.Util.falseFn;
8809 tile.src = L.Util.emptyImageUrl;
8811 tile.parentNode.removeChild(tile);
8819 * Provides L.Map with convenient shortcuts for using browser geolocation features.
8823 _defaultLocateOptions: {
8829 enableHighAccuracy: false
8832 locate: function (/*Object*/ options) {
8834 options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
8836 if (!navigator.geolocation) {
8837 this._handleGeolocationError({
8839 message: 'Geolocation not supported.'
8844 var onResponse = L.bind(this._handleGeolocationResponse, this),
8845 onError = L.bind(this._handleGeolocationError, this);
8847 if (options.watch) {
8848 this._locationWatchId =
8849 navigator.geolocation.watchPosition(onResponse, onError, options);
8851 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
8856 stopLocate: function () {
8857 if (navigator.geolocation) {
8858 navigator.geolocation.clearWatch(this._locationWatchId);
8860 if (this._locateOptions) {
8861 this._locateOptions.setView = false;
8866 _handleGeolocationError: function (error) {
8868 message = error.message ||
8869 (c === 1 ? 'permission denied' :
8870 (c === 2 ? 'position unavailable' : 'timeout'));
8872 if (this._locateOptions.setView && !this._loaded) {
8876 this.fire('locationerror', {
8878 message: 'Geolocation error: ' + message + '.'
8882 _handleGeolocationResponse: function (pos) {
8883 var lat = pos.coords.latitude,
8884 lng = pos.coords.longitude,
8885 latlng = new L.LatLng(lat, lng),
8887 latAccuracy = 180 * pos.coords.accuracy / 40075017,
8888 lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
8890 bounds = L.latLngBounds(
8891 [lat - latAccuracy, lng - lngAccuracy],
8892 [lat + latAccuracy, lng + lngAccuracy]),
8894 options = this._locateOptions;
8896 if (options.setView) {
8897 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
8898 this.setView(latlng, zoom);
8906 for (var i in pos.coords) {
8907 if (typeof pos.coords[i] === 'number') {
8908 data[i] = pos.coords[i];
8912 this.fire('locationfound', data);
8917 }(window, document));