2 Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
3 (c) 2010-2013, Vladimir Agafonkin
4 (c) 2010-2011, CloudMade
6 (function (window, document, undefined) {
12 // define Leaflet for Node module pattern loaders, including Browserify
13 if (typeof module === 'object' && typeof module.exports === 'object') {
16 // define Leaflet as an AMD module
17 } else if (typeof define === 'function' && define.amd) {
21 // define Leaflet as a global L variable, saving the original L to restore later if needed
23 L.noConflict = function () {
32 * L.Util contains various utility functions used throughout Leaflet code.
36 extend: function (dest) { // (Object[, Object, ...]) ->
37 var sources = Array.prototype.slice.call(arguments, 1),
40 for (j = 0, len = sources.length; j < len; j++) {
41 src = sources[j] || {};
43 if (src.hasOwnProperty(i)) {
51 bind: function (fn, obj) { // (Function, Object) -> Function
52 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
54 return fn.apply(obj, args || arguments);
61 return function (obj) {
62 obj[key] = obj[key] || ++lastId;
67 invokeEach: function (obj, method, context) {
70 if (typeof obj === 'object') {
71 args = Array.prototype.slice.call(arguments, 3);
74 method.apply(context, [i, obj[i]].concat(args));
82 limitExecByInterval: function (fn, time, context) {
83 var lock, execOnUnlock;
85 return function wrapperFn() {
95 setTimeout(function () {
99 wrapperFn.apply(context, args);
100 execOnUnlock = false;
104 fn.apply(context, args);
108 falseFn: function () {
112 formatNum: function (num, digits) {
113 var pow = Math.pow(10, digits || 5);
114 return Math.round(num * pow) / pow;
117 trim: function (str) {
118 return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
121 splitWords: function (str) {
122 return L.Util.trim(str).split(/\s+/);
125 setOptions: function (obj, options) {
126 obj.options = L.extend({}, obj.options, options);
130 getParamString: function (obj, existingUrl, uppercase) {
133 params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
135 return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
138 template: function (str, data) {
139 return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
140 var value = data[key];
141 if (value === undefined) {
142 throw new Error('No value provided for variable ' + str);
143 } else if (typeof value === 'function') {
150 isArray: function (obj) {
151 return (Object.prototype.toString.call(obj) === '[object Array]');
154 emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
159 // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
161 function getPrefixed(name) {
163 prefixes = ['webkit', 'moz', 'o', 'ms'];
165 for (i = 0; i < prefixes.length && !fn; i++) {
166 fn = window[prefixes[i] + name];
174 function timeoutDefer(fn) {
175 var time = +new Date(),
176 timeToCall = Math.max(0, 16 - (time - lastTime));
178 lastTime = time + timeToCall;
179 return window.setTimeout(fn, timeToCall);
182 var requestFn = window.requestAnimationFrame ||
183 getPrefixed('RequestAnimationFrame') || timeoutDefer;
185 var cancelFn = window.cancelAnimationFrame ||
186 getPrefixed('CancelAnimationFrame') ||
187 getPrefixed('CancelRequestAnimationFrame') ||
188 function (id) { window.clearTimeout(id); };
191 L.Util.requestAnimFrame = function (fn, context, immediate, element) {
192 fn = L.bind(fn, context);
194 if (immediate && requestFn === timeoutDefer) {
197 return requestFn.call(window, fn, element);
201 L.Util.cancelAnimFrame = function (id) {
203 cancelFn.call(window, id);
209 // shortcuts for most used utility functions
210 L.extend = L.Util.extend;
211 L.bind = L.Util.bind;
212 L.stamp = L.Util.stamp;
213 L.setOptions = L.Util.setOptions;
217 * L.Class powers the OOP facilities of the library.
218 * Thanks to John Resig and Dean Edwards for inspiration!
221 L.Class = function () {};
223 L.Class.extend = function (props) {
225 // extended class with the new prototype
226 var NewClass = function () {
228 // call the constructor
229 if (this.initialize) {
230 this.initialize.apply(this, arguments);
233 // call all constructor hooks
234 if (this._initHooks) {
235 this.callInitHooks();
239 // instantiate class without calling constructor
240 var F = function () {};
241 F.prototype = this.prototype;
244 proto.constructor = NewClass;
246 NewClass.prototype = proto;
248 //inherit parent's statics
249 for (var i in this) {
250 if (this.hasOwnProperty(i) && i !== 'prototype') {
251 NewClass[i] = this[i];
255 // mix static properties into the class
257 L.extend(NewClass, props.statics);
258 delete props.statics;
261 // mix includes into the prototype
262 if (props.includes) {
263 L.Util.extend.apply(null, [proto].concat(props.includes));
264 delete props.includes;
268 if (props.options && proto.options) {
269 props.options = L.extend({}, proto.options, props.options);
272 // mix given properties into the prototype
273 L.extend(proto, props);
275 proto._initHooks = [];
278 // jshint camelcase: false
279 NewClass.__super__ = parent.prototype;
281 // add method for calling all hooks
282 proto.callInitHooks = function () {
284 if (this._initHooksCalled) { return; }
286 if (parent.prototype.callInitHooks) {
287 parent.prototype.callInitHooks.call(this);
290 this._initHooksCalled = true;
292 for (var i = 0, len = proto._initHooks.length; i < len; i++) {
293 proto._initHooks[i].call(this);
301 // method for adding properties to prototype
302 L.Class.include = function (props) {
303 L.extend(this.prototype, props);
306 // merge new default options to the Class
307 L.Class.mergeOptions = function (options) {
308 L.extend(this.prototype.options, options);
311 // add a constructor hook
312 L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
313 var args = Array.prototype.slice.call(arguments, 1);
315 var init = typeof fn === 'function' ? fn : function () {
316 this[fn].apply(this, args);
319 this.prototype._initHooks = this.prototype._initHooks || [];
320 this.prototype._initHooks.push(init);
325 * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
328 var eventsKey = '_leaflet_events';
334 addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
336 // types can be a map of types/handlers
337 if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
339 var events = this[eventsKey] = this[eventsKey] || {},
340 contextId = context && L.stamp(context),
341 i, len, event, type, indexKey, indexLenKey, typeIndex;
343 // types can be a string of space-separated words
344 types = L.Util.splitWords(types);
346 for (i = 0, len = types.length; i < len; i++) {
349 context: context || this
354 // store listeners of a particular context in a separate hash (if it has an id)
355 // gives a major performance boost when removing thousands of map layers
357 indexKey = type + '_idx';
358 indexLenKey = indexKey + '_len';
360 typeIndex = events[indexKey] = events[indexKey] || {};
362 if (!typeIndex[contextId]) {
363 typeIndex[contextId] = [];
365 // keep track of the number of keys in the index to quickly check if it's empty
366 events[indexLenKey] = (events[indexLenKey] || 0) + 1;
369 typeIndex[contextId].push(event);
373 events[type] = events[type] || [];
374 events[type].push(event);
381 hasEventListeners: function (type) { // (String) -> Boolean
382 var events = this[eventsKey];
383 return !!events && ((type in events && events[type].length > 0) ||
384 (type + '_idx' in events && events[type + '_idx_len'] > 0));
387 removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
389 if (!this[eventsKey]) {
394 return this.clearAllEventListeners();
397 if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
399 var events = this[eventsKey],
400 contextId = context && L.stamp(context),
401 i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
403 types = L.Util.splitWords(types);
405 for (i = 0, len = types.length; i < len; i++) {
407 indexKey = type + '_idx';
408 indexLenKey = indexKey + '_len';
410 typeIndex = events[indexKey];
413 // clear all listeners for a type if function isn't specified
415 delete events[indexKey];
418 listeners = context && typeIndex ? typeIndex[contextId] : events[type];
421 for (j = listeners.length - 1; j >= 0; j--) {
422 if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
423 removed = listeners.splice(j, 1);
424 // set the old action to a no-op, because it is possible
425 // that the listener is being iterated over as part of a dispatch
426 removed[0].action = L.Util.falseFn;
430 if (context && typeIndex && (listeners.length === 0)) {
431 delete typeIndex[contextId];
432 events[indexLenKey]--;
441 clearAllEventListeners: function () {
442 delete this[eventsKey];
446 fireEvent: function (type, data) { // (String[, Object])
447 if (!this.hasEventListeners(type)) {
451 var event = L.Util.extend({}, data, { type: type, target: this });
453 var events = this[eventsKey],
454 listeners, i, len, typeIndex, contextId;
457 // make sure adding/removing listeners inside other listeners won't cause infinite loop
458 listeners = events[type].slice();
460 for (i = 0, len = listeners.length; i < len; i++) {
461 listeners[i].action.call(listeners[i].context || this, event);
465 // fire event for the context-indexed listeners as well
466 typeIndex = events[type + '_idx'];
468 for (contextId in typeIndex) {
469 listeners = typeIndex[contextId].slice();
472 for (i = 0, len = listeners.length; i < len; i++) {
473 listeners[i].action.call(listeners[i].context || this, event);
481 addOneTimeEventListener: function (types, fn, context) {
483 if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
485 var handler = L.bind(function () {
487 .removeEventListener(types, fn, context)
488 .removeEventListener(types, handler, context);
492 .addEventListener(types, fn, context)
493 .addEventListener(types, handler, context);
497 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
498 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
499 L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
500 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
504 * L.Browser handles different browser and feature detections for internal Leaflet use.
509 var ie = !!window.ActiveXObject,
510 ie6 = ie && !window.XMLHttpRequest,
511 ie7 = ie && !document.querySelector,
512 ielt9 = ie && !document.addEventListener,
514 // terrible browser detection to work around Safari / iOS / Android browser bugs
515 ua = navigator.userAgent.toLowerCase(),
516 webkit = ua.indexOf('webkit') !== -1,
517 chrome = ua.indexOf('chrome') !== -1,
518 phantomjs = ua.indexOf('phantom') !== -1,
519 android = ua.indexOf('android') !== -1,
520 android23 = ua.search('android [23]') !== -1,
522 mobile = typeof orientation !== undefined + '',
523 msTouch = window.navigator && window.navigator.msPointerEnabled &&
524 window.navigator.msMaxTouchPoints,
525 retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
526 ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
527 window.matchMedia('(min-resolution:144dpi)').matches),
529 doc = document.documentElement,
530 ie3d = ie && ('transition' in doc.style),
531 webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
532 gecko3d = 'MozPerspective' in doc.style,
533 opera3d = 'OTransition' in doc.style,
534 any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
537 // PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch.
538 // https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151
540 var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
542 var startName = 'ontouchstart';
544 // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.MsTouch) or WebKit, etc.
545 if (msTouch || (startName in doc)) {
550 var div = document.createElement('div'),
553 if (!div.setAttribute) {
556 div.setAttribute(startName, 'return;');
558 if (typeof div[startName] === 'function') {
562 div.removeAttribute(startName);
577 android23: android23,
588 mobileWebkit: mobile && webkit,
589 mobileWebkit3d: mobile && webkit3d,
590 mobileOpera: mobile && window.opera,
602 * L.Point represents a point with x and y coordinates.
605 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
606 this.x = (round ? Math.round(x) : x);
607 this.y = (round ? Math.round(y) : y);
610 L.Point.prototype = {
613 return new L.Point(this.x, this.y);
616 // non-destructive, returns a new point
617 add: function (point) {
618 return this.clone()._add(L.point(point));
621 // destructive, used directly for performance in situations where it's safe to modify existing point
622 _add: function (point) {
628 subtract: function (point) {
629 return this.clone()._subtract(L.point(point));
632 _subtract: function (point) {
638 divideBy: function (num) {
639 return this.clone()._divideBy(num);
642 _divideBy: function (num) {
648 multiplyBy: function (num) {
649 return this.clone()._multiplyBy(num);
652 _multiplyBy: function (num) {
659 return this.clone()._round();
662 _round: function () {
663 this.x = Math.round(this.x);
664 this.y = Math.round(this.y);
669 return this.clone()._floor();
672 _floor: function () {
673 this.x = Math.floor(this.x);
674 this.y = Math.floor(this.y);
678 distanceTo: function (point) {
679 point = L.point(point);
681 var x = point.x - this.x,
682 y = point.y - this.y;
684 return Math.sqrt(x * x + y * y);
687 equals: function (point) {
688 point = L.point(point);
690 return point.x === this.x &&
694 contains: function (point) {
695 point = L.point(point);
697 return Math.abs(point.x) <= Math.abs(this.x) &&
698 Math.abs(point.y) <= Math.abs(this.y);
701 toString: function () {
703 L.Util.formatNum(this.x) + ', ' +
704 L.Util.formatNum(this.y) + ')';
708 L.point = function (x, y, round) {
709 if (x instanceof L.Point) {
712 if (L.Util.isArray(x)) {
713 return new L.Point(x[0], x[1]);
715 if (x === undefined || x === null) {
718 return new L.Point(x, y, round);
723 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
726 L.Bounds = function (a, b) { //(Point, Point) or Point[]
729 var points = b ? [a, b] : a;
731 for (var i = 0, len = points.length; i < len; i++) {
732 this.extend(points[i]);
736 L.Bounds.prototype = {
737 // extend the bounds to contain the given point
738 extend: function (point) { // (Point)
739 point = L.point(point);
741 if (!this.min && !this.max) {
742 this.min = point.clone();
743 this.max = point.clone();
745 this.min.x = Math.min(point.x, this.min.x);
746 this.max.x = Math.max(point.x, this.max.x);
747 this.min.y = Math.min(point.y, this.min.y);
748 this.max.y = Math.max(point.y, this.max.y);
753 getCenter: function (round) { // (Boolean) -> Point
755 (this.min.x + this.max.x) / 2,
756 (this.min.y + this.max.y) / 2, round);
759 getBottomLeft: function () { // -> Point
760 return new L.Point(this.min.x, this.max.y);
763 getTopRight: function () { // -> Point
764 return new L.Point(this.max.x, this.min.y);
767 getSize: function () {
768 return this.max.subtract(this.min);
771 contains: function (obj) { // (Bounds) or (Point) -> Boolean
774 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
780 if (obj instanceof L.Bounds) {
787 return (min.x >= this.min.x) &&
788 (max.x <= this.max.x) &&
789 (min.y >= this.min.y) &&
790 (max.y <= this.max.y);
793 intersects: function (bounds) { // (Bounds) -> Boolean
794 bounds = L.bounds(bounds);
800 xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
801 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
803 return xIntersects && yIntersects;
806 isValid: function () {
807 return !!(this.min && this.max);
811 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
812 if (!a || a instanceof L.Bounds) {
815 return new L.Bounds(a, b);
820 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
823 L.Transformation = function (a, b, c, d) {
830 L.Transformation.prototype = {
831 transform: function (point, scale) { // (Point, Number) -> Point
832 return this._transform(point.clone(), scale);
835 // destructive transform (faster)
836 _transform: function (point, scale) {
838 point.x = scale * (this._a * point.x + this._b);
839 point.y = scale * (this._c * point.y + this._d);
843 untransform: function (point, scale) {
846 (point.x / scale - this._b) / this._a,
847 (point.y / scale - this._d) / this._c);
853 * L.DomUtil contains various utility functions for working with DOM.
858 return (typeof id === 'string' ? document.getElementById(id) : id);
861 getStyle: function (el, style) {
863 var value = el.style[style];
865 if (!value && el.currentStyle) {
866 value = el.currentStyle[style];
869 if ((!value || value === 'auto') && document.defaultView) {
870 var css = document.defaultView.getComputedStyle(el, null);
871 value = css ? css[style] : null;
874 return value === 'auto' ? null : value;
877 getViewportOffset: function (element) {
882 docBody = document.body,
883 docEl = document.documentElement,
888 top += el.offsetTop || 0;
889 left += el.offsetLeft || 0;
892 top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
893 left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
895 pos = L.DomUtil.getStyle(el, 'position');
897 if (el.offsetParent === docBody && pos === 'absolute') { break; }
899 if (pos === 'fixed') {
900 top += docBody.scrollTop || docEl.scrollTop || 0;
901 left += docBody.scrollLeft || docEl.scrollLeft || 0;
905 if (pos === 'relative' && !el.offsetLeft) {
906 var width = L.DomUtil.getStyle(el, 'width'),
907 maxWidth = L.DomUtil.getStyle(el, 'max-width'),
908 r = el.getBoundingClientRect();
910 if (width !== 'none' || maxWidth !== 'none') {
911 left += r.left + el.clientLeft;
914 //calculate full y offset since we're breaking out of the loop
915 top += r.top + (docBody.scrollTop || docEl.scrollTop || 0);
920 el = el.offsetParent;
927 if (el === docBody) { break; }
929 top -= el.scrollTop || 0;
930 left -= el.scrollLeft || 0;
932 // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
933 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
934 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
935 left += el.scrollWidth - el.clientWidth;
937 // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
938 // need to add it back in if it is visible; scrollbar is on the left as we are RTL
939 if (ie7 && L.DomUtil.getStyle(el, 'overflow-y') !== 'hidden' &&
940 L.DomUtil.getStyle(el, 'overflow') !== 'hidden') {
948 return new L.Point(left, top);
951 documentIsLtr: function () {
952 if (!L.DomUtil._docIsLtrCached) {
953 L.DomUtil._docIsLtrCached = true;
954 L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
956 return L.DomUtil._docIsLtr;
959 create: function (tagName, className, container) {
961 var el = document.createElement(tagName);
962 el.className = className;
965 container.appendChild(el);
971 hasClass: function (el, name) {
972 return (el.className.length > 0) &&
973 new RegExp('(^|\\s)' + name + '(\\s|$)').test(el.className);
976 addClass: function (el, name) {
977 if (!L.DomUtil.hasClass(el, name)) {
978 el.className += (el.className ? ' ' : '') + name;
982 removeClass: function (el, name) {
983 el.className = L.Util.trim((' ' + el.className + ' ').replace(' ' + name + ' ', ' '));
986 setOpacity: function (el, value) {
988 if ('opacity' in el.style) {
989 el.style.opacity = value;
991 } else if ('filter' in el.style) {
994 filterName = 'DXImageTransform.Microsoft.Alpha';
996 // filters collection throws an error if we try to retrieve a filter that doesn't exist
998 filter = el.filters.item(filterName);
1000 // don't set opacity to 1 if we haven't already set an opacity,
1001 // it isn't needed and breaks transparent pngs.
1002 if (value === 1) { return; }
1005 value = Math.round(value * 100);
1008 filter.Enabled = (value !== 100);
1009 filter.Opacity = value;
1011 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
1016 testProp: function (props) {
1018 var style = document.documentElement.style;
1020 for (var i = 0; i < props.length; i++) {
1021 if (props[i] in style) {
1028 getTranslateString: function (point) {
1029 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
1030 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
1031 // (same speed either way), Opera 12 doesn't support translate3d
1033 var is3d = L.Browser.webkit3d,
1034 open = 'translate' + (is3d ? '3d' : '') + '(',
1035 close = (is3d ? ',0' : '') + ')';
1037 return open + point.x + 'px,' + point.y + 'px' + close;
1040 getScaleString: function (scale, origin) {
1042 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
1043 scaleStr = ' scale(' + scale + ') ';
1045 return preTranslateStr + scaleStr;
1048 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
1050 // jshint camelcase: false
1051 el._leaflet_pos = point;
1053 if (!disable3D && L.Browser.any3d) {
1054 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
1056 // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
1057 if (L.Browser.mobileWebkit3d) {
1058 el.style.WebkitBackfaceVisibility = 'hidden';
1061 el.style.left = point.x + 'px';
1062 el.style.top = point.y + 'px';
1066 getPosition: function (el) {
1067 // this method is only used for elements previously positioned using setPosition,
1068 // so it's safe to cache the position for performance
1070 // jshint camelcase: false
1071 return el._leaflet_pos;
1076 // prefix style property names
1078 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
1079 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
1081 // webkitTransition comes first because some browser versions that drop vendor prefix don't do
1082 // the same for the transitionend event, in particular the Android 4.1 stock browser
1084 L.DomUtil.TRANSITION = L.DomUtil.testProp(
1085 ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
1087 L.DomUtil.TRANSITION_END =
1088 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
1089 L.DomUtil.TRANSITION + 'End' : 'transitionend';
1092 var userSelectProperty = L.DomUtil.testProp(
1093 ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
1095 L.extend(L.DomUtil, {
1096 disableTextSelection: function () {
1097 L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
1098 if (userSelectProperty) {
1099 var style = document.documentElement.style;
1100 this._userSelect = style[userSelectProperty];
1101 style[userSelectProperty] = 'none';
1105 enableTextSelection: function () {
1106 L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
1107 if (userSelectProperty) {
1108 document.documentElement.style[userSelectProperty] = this._userSelect;
1109 delete this._userSelect;
1113 disableImageDrag: function () {
1114 L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
1117 enableImageDrag: function () {
1118 L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
1125 * L.LatLng represents a geographical point with latitude and longitude coordinates.
1128 L.LatLng = function (rawLat, rawLng) { // (Number, Number)
1129 var lat = parseFloat(rawLat),
1130 lng = parseFloat(rawLng);
1132 if (isNaN(lat) || isNaN(lng)) {
1133 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
1140 L.extend(L.LatLng, {
1141 DEG_TO_RAD: Math.PI / 180,
1142 RAD_TO_DEG: 180 / Math.PI,
1143 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
1146 L.LatLng.prototype = {
1147 equals: function (obj) { // (LatLng) -> Boolean
1148 if (!obj) { return false; }
1150 obj = L.latLng(obj);
1152 var margin = Math.max(
1153 Math.abs(this.lat - obj.lat),
1154 Math.abs(this.lng - obj.lng));
1156 return margin <= L.LatLng.MAX_MARGIN;
1159 toString: function (precision) { // (Number) -> String
1161 L.Util.formatNum(this.lat, precision) + ', ' +
1162 L.Util.formatNum(this.lng, precision) + ')';
1165 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1166 // TODO move to projection code, LatLng shouldn't know about Earth
1167 distanceTo: function (other) { // (LatLng) -> Number
1168 other = L.latLng(other);
1170 var R = 6378137, // earth radius in meters
1171 d2r = L.LatLng.DEG_TO_RAD,
1172 dLat = (other.lat - this.lat) * d2r,
1173 dLon = (other.lng - this.lng) * d2r,
1174 lat1 = this.lat * d2r,
1175 lat2 = other.lat * d2r,
1176 sin1 = Math.sin(dLat / 2),
1177 sin2 = Math.sin(dLon / 2);
1179 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1181 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1184 wrap: function (a, b) { // (Number, Number) -> LatLng
1190 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1192 return new L.LatLng(this.lat, lng);
1196 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1197 if (a instanceof L.LatLng) {
1200 if (L.Util.isArray(a)) {
1201 return new L.LatLng(a[0], a[1]);
1203 if (a === undefined || a === null) {
1206 if (typeof a === 'object' && 'lat' in a) {
1207 return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
1209 return new L.LatLng(a, b);
1215 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1218 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1219 if (!southWest) { return; }
1221 var latlngs = northEast ? [southWest, northEast] : southWest;
1223 for (var i = 0, len = latlngs.length; i < len; i++) {
1224 this.extend(latlngs[i]);
1228 L.LatLngBounds.prototype = {
1229 // extend the bounds to contain the given point or bounds
1230 extend: function (obj) { // (LatLng) or (LatLngBounds)
1231 if (!obj) { return this; }
1233 if (typeof obj[0] === 'number' || typeof obj[0] === 'string' || obj instanceof L.LatLng) {
1234 obj = L.latLng(obj);
1236 obj = L.latLngBounds(obj);
1239 if (obj instanceof L.LatLng) {
1240 if (!this._southWest && !this._northEast) {
1241 this._southWest = new L.LatLng(obj.lat, obj.lng);
1242 this._northEast = new L.LatLng(obj.lat, obj.lng);
1244 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1245 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1247 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1248 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1250 } else if (obj instanceof L.LatLngBounds) {
1251 this.extend(obj._southWest);
1252 this.extend(obj._northEast);
1257 // extend the bounds by a percentage
1258 pad: function (bufferRatio) { // (Number) -> LatLngBounds
1259 var sw = this._southWest,
1260 ne = this._northEast,
1261 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1262 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1264 return new L.LatLngBounds(
1265 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1266 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1269 getCenter: function () { // -> LatLng
1270 return new L.LatLng(
1271 (this._southWest.lat + this._northEast.lat) / 2,
1272 (this._southWest.lng + this._northEast.lng) / 2);
1275 getSouthWest: function () {
1276 return this._southWest;
1279 getNorthEast: function () {
1280 return this._northEast;
1283 getNorthWest: function () {
1284 return new L.LatLng(this.getNorth(), this.getWest());
1287 getSouthEast: function () {
1288 return new L.LatLng(this.getSouth(), this.getEast());
1291 getWest: function () {
1292 return this._southWest.lng;
1295 getSouth: function () {
1296 return this._southWest.lat;
1299 getEast: function () {
1300 return this._northEast.lng;
1303 getNorth: function () {
1304 return this._northEast.lat;
1307 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1308 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1309 obj = L.latLng(obj);
1311 obj = L.latLngBounds(obj);
1314 var sw = this._southWest,
1315 ne = this._northEast,
1318 if (obj instanceof L.LatLngBounds) {
1319 sw2 = obj.getSouthWest();
1320 ne2 = obj.getNorthEast();
1325 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1326 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1329 intersects: function (bounds) { // (LatLngBounds)
1330 bounds = L.latLngBounds(bounds);
1332 var sw = this._southWest,
1333 ne = this._northEast,
1334 sw2 = bounds.getSouthWest(),
1335 ne2 = bounds.getNorthEast(),
1337 latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1338 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1340 return latIntersects && lngIntersects;
1343 toBBoxString: function () {
1344 return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
1347 equals: function (bounds) { // (LatLngBounds)
1348 if (!bounds) { return false; }
1350 bounds = L.latLngBounds(bounds);
1352 return this._southWest.equals(bounds.getSouthWest()) &&
1353 this._northEast.equals(bounds.getNorthEast());
1356 isValid: function () {
1357 return !!(this._southWest && this._northEast);
1361 //TODO International date line?
1363 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1364 if (!a || a instanceof L.LatLngBounds) {
1367 return new L.LatLngBounds(a, b);
1372 * L.Projection contains various geographical projections used by CRS classes.
1379 * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1382 L.Projection.SphericalMercator = {
1383 MAX_LATITUDE: 85.0511287798,
1385 project: function (latlng) { // (LatLng) -> Point
1386 var d = L.LatLng.DEG_TO_RAD,
1387 max = this.MAX_LATITUDE,
1388 lat = Math.max(Math.min(max, latlng.lat), -max),
1392 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1394 return new L.Point(x, y);
1397 unproject: function (point) { // (Point, Boolean) -> LatLng
1398 var d = L.LatLng.RAD_TO_DEG,
1400 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1402 return new L.LatLng(lat, lng);
1408 * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1411 L.Projection.LonLat = {
1412 project: function (latlng) {
1413 return new L.Point(latlng.lng, latlng.lat);
1416 unproject: function (point) {
1417 return new L.LatLng(point.y, point.x);
1423 * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1427 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1428 var projectedPoint = this.projection.project(latlng),
1429 scale = this.scale(zoom);
1431 return this.transformation._transform(projectedPoint, scale);
1434 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1435 var scale = this.scale(zoom),
1436 untransformedPoint = this.transformation.untransform(point, scale);
1438 return this.projection.unproject(untransformedPoint);
1441 project: function (latlng) {
1442 return this.projection.project(latlng);
1445 scale: function (zoom) {
1446 return 256 * Math.pow(2, zoom);
1452 * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1455 L.CRS.Simple = L.extend({}, L.CRS, {
1456 projection: L.Projection.LonLat,
1457 transformation: new L.Transformation(1, 0, -1, 0),
1459 scale: function (zoom) {
1460 return Math.pow(2, zoom);
1466 * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1467 * and is used by Leaflet by default.
1470 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1473 projection: L.Projection.SphericalMercator,
1474 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1476 project: function (latlng) { // (LatLng) -> Point
1477 var projectedPoint = this.projection.project(latlng),
1478 earthRadius = 6378137;
1479 return projectedPoint.multiplyBy(earthRadius);
1483 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1489 * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1492 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1495 projection: L.Projection.LonLat,
1496 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1501 * L.Map is the central class of the API - it is used to create a map.
1504 L.Map = L.Class.extend({
1506 includes: L.Mixin.Events,
1509 crs: L.CRS.EPSG3857,
1517 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1519 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1522 initialize: function (id, options) { // (HTMLElement or String, Object)
1523 options = L.setOptions(this, options);
1525 this._initContainer(id);
1529 if (options.maxBounds) {
1530 this.setMaxBounds(options.maxBounds);
1533 if (options.center && options.zoom !== undefined) {
1534 this.setView(L.latLng(options.center), options.zoom, {reset: true});
1537 this._handlers = [];
1540 this._zoomBoundLayers = {};
1541 this._tileLayersNum = 0;
1543 this.callInitHooks();
1545 this._addLayers(options.layers);
1549 // public methods that modify map state
1551 // replaced by animation-powered implementation in Map.PanAnimation.js
1552 setView: function (center, zoom) {
1553 this._resetView(L.latLng(center), this._limitZoom(zoom));
1557 setZoom: function (zoom, options) {
1558 return this.setView(this.getCenter(), zoom, {zoom: options});
1561 zoomIn: function (delta, options) {
1562 return this.setZoom(this._zoom + (delta || 1), options);
1565 zoomOut: function (delta, options) {
1566 return this.setZoom(this._zoom - (delta || 1), options);
1569 setZoomAround: function (latlng, zoom, options) {
1570 var scale = this.getZoomScale(zoom),
1571 viewHalf = this.getSize().divideBy(2),
1572 containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
1574 centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
1575 newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
1577 return this.setView(newCenter, zoom, {zoom: options});
1580 fitBounds: function (bounds, options) {
1582 options = options || {};
1583 bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
1585 var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
1586 paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
1588 zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
1589 paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
1591 swPoint = this.project(bounds.getSouthWest(), zoom),
1592 nePoint = this.project(bounds.getNorthEast(), zoom),
1593 center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
1595 return this.setView(center, zoom, options);
1598 fitWorld: function (options) {
1599 return this.fitBounds([[-90, -180], [90, 180]], options);
1602 panTo: function (center, options) { // (LatLng)
1603 return this.setView(center, this._zoom, {pan: options});
1606 panBy: function (offset) { // (Point)
1607 // replaced with animated panBy in Map.Animation.js
1608 this.fire('movestart');
1610 this._rawPanBy(L.point(offset));
1613 return this.fire('moveend');
1616 setMaxBounds: function (bounds, options) {
1617 bounds = L.latLngBounds(bounds);
1619 this.options.maxBounds = bounds;
1622 this._boundsMinZoom = null;
1623 this.off('moveend', this._panInsideMaxBounds, this);
1627 var minZoom = this.getBoundsZoom(bounds, true);
1629 this._boundsMinZoom = minZoom;
1632 if (this._zoom < minZoom) {
1633 this.setView(bounds.getCenter(), minZoom, options);
1635 this.panInsideBounds(bounds);
1639 this.on('moveend', this._panInsideMaxBounds, this);
1644 panInsideBounds: function (bounds) {
1645 bounds = L.latLngBounds(bounds);
1647 var viewBounds = this.getPixelBounds(),
1648 viewSw = viewBounds.getBottomLeft(),
1649 viewNe = viewBounds.getTopRight(),
1650 sw = this.project(bounds.getSouthWest()),
1651 ne = this.project(bounds.getNorthEast()),
1655 if (viewNe.y < ne.y) { // north
1656 dy = Math.ceil(ne.y - viewNe.y);
1658 if (viewNe.x > ne.x) { // east
1659 dx = Math.floor(ne.x - viewNe.x);
1661 if (viewSw.y > sw.y) { // south
1662 dy = Math.floor(sw.y - viewSw.y);
1664 if (viewSw.x < sw.x) { // west
1665 dx = Math.ceil(sw.x - viewSw.x);
1669 return this.panBy([dx, dy]);
1675 addLayer: function (layer) {
1676 // TODO method is too big, refactor
1678 var id = L.stamp(layer);
1680 if (this._layers[id]) { return this; }
1682 this._layers[id] = layer;
1684 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1685 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1686 this._zoomBoundLayers[id] = layer;
1687 this._updateZoomLevels();
1690 // TODO looks ugly, refactor!!!
1691 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1692 this._tileLayersNum++;
1693 this._tileLayersToLoad++;
1694 layer.on('load', this._onTileLayerLoad, this);
1698 this._layerAdd(layer);
1704 removeLayer: function (layer) {
1705 var id = L.stamp(layer);
1707 if (!this._layers[id]) { return; }
1710 layer.onRemove(this);
1713 delete this._layers[id];
1716 this.fire('layerremove', {layer: layer});
1719 if (this._zoomBoundLayers[id]) {
1720 delete this._zoomBoundLayers[id];
1721 this._updateZoomLevels();
1724 // TODO looks ugly, refactor
1725 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1726 this._tileLayersNum--;
1727 this._tileLayersToLoad--;
1728 layer.off('load', this._onTileLayerLoad, this);
1734 hasLayer: function (layer) {
1735 if (!layer) { return false; }
1737 return (L.stamp(layer) in this._layers);
1740 eachLayer: function (method, context) {
1741 for (var i in this._layers) {
1742 method.call(context, this._layers[i]);
1747 invalidateSize: function (options) {
1748 options = L.extend({
1751 }, options === true ? {animate: true} : options);
1753 var oldSize = this.getSize();
1754 this._sizeChanged = true;
1756 if (this.options.maxBounds) {
1757 this.setMaxBounds(this.options.maxBounds);
1760 if (!this._loaded) { return this; }
1762 var newSize = this.getSize(),
1763 offset = oldSize.subtract(newSize).divideBy(2).round();
1765 if (!offset.x && !offset.y) { return this; }
1767 if (options.animate && options.pan) {
1772 this._rawPanBy(offset);
1777 // make sure moveend is not fired too often on resize
1778 clearTimeout(this._sizeTimer);
1779 this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1782 return this.fire('resize', {
1788 // TODO handler.addTo
1789 addHandler: function (name, HandlerClass) {
1790 if (!HandlerClass) { return; }
1792 var handler = this[name] = new HandlerClass(this);
1794 this._handlers.push(handler);
1796 if (this.options[name]) {
1803 remove: function () {
1805 this.fire('unload');
1808 this._initEvents('off');
1810 delete this._container._leaflet;
1813 if (this._clearControlPos) {
1814 this._clearControlPos();
1817 this._clearHandlers();
1823 // public methods for getting map state
1825 getCenter: function () { // (Boolean) -> LatLng
1826 this._checkIfLoaded();
1828 if (!this._moved()) {
1829 return this._initialCenter;
1831 return this.layerPointToLatLng(this._getCenterLayerPoint());
1834 getZoom: function () {
1838 getBounds: function () {
1839 var bounds = this.getPixelBounds(),
1840 sw = this.unproject(bounds.getBottomLeft()),
1841 ne = this.unproject(bounds.getTopRight());
1843 return new L.LatLngBounds(sw, ne);
1846 getMinZoom: function () {
1847 var z1 = this._layersMinZoom === undefined ? -Infinity : this._layersMinZoom,
1848 z2 = this._boundsMinZoom === undefined ? -Infinity : this._boundsMinZoom;
1849 return this.options.minZoom === undefined ? Math.max(z1, z2) : this.options.minZoom;
1852 getMaxZoom: function () {
1853 return this.options.maxZoom === undefined ?
1854 (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
1855 this.options.maxZoom;
1858 getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1859 bounds = L.latLngBounds(bounds);
1861 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1862 maxZoom = this.getMaxZoom(),
1863 size = this.getSize(),
1865 nw = bounds.getNorthWest(),
1866 se = bounds.getSouthEast(),
1868 zoomNotFound = true,
1871 padding = L.point(padding || [0, 0]);
1875 boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1876 zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1878 } while (zoomNotFound && zoom <= maxZoom);
1880 if (zoomNotFound && inside) {
1884 return inside ? zoom : zoom - 1;
1887 getSize: function () {
1888 if (!this._size || this._sizeChanged) {
1889 this._size = new L.Point(
1890 this._container.clientWidth,
1891 this._container.clientHeight);
1893 this._sizeChanged = false;
1895 return this._size.clone();
1898 getPixelBounds: function () {
1899 var topLeftPoint = this._getTopLeftPoint();
1900 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1903 getPixelOrigin: function () {
1904 this._checkIfLoaded();
1905 return this._initialTopLeftPoint;
1908 getPanes: function () {
1912 getContainer: function () {
1913 return this._container;
1917 // TODO replace with universal implementation after refactoring projections
1919 getZoomScale: function (toZoom) {
1920 var crs = this.options.crs;
1921 return crs.scale(toZoom) / crs.scale(this._zoom);
1924 getScaleZoom: function (scale) {
1925 return this._zoom + (Math.log(scale) / Math.LN2);
1929 // conversion methods
1931 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1932 zoom = zoom === undefined ? this._zoom : zoom;
1933 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1936 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1937 zoom = zoom === undefined ? this._zoom : zoom;
1938 return this.options.crs.pointToLatLng(L.point(point), zoom);
1941 layerPointToLatLng: function (point) { // (Point)
1942 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1943 return this.unproject(projectedPoint);
1946 latLngToLayerPoint: function (latlng) { // (LatLng)
1947 var projectedPoint = this.project(L.latLng(latlng))._round();
1948 return projectedPoint._subtract(this.getPixelOrigin());
1951 containerPointToLayerPoint: function (point) { // (Point)
1952 return L.point(point).subtract(this._getMapPanePos());
1955 layerPointToContainerPoint: function (point) { // (Point)
1956 return L.point(point).add(this._getMapPanePos());
1959 containerPointToLatLng: function (point) {
1960 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1961 return this.layerPointToLatLng(layerPoint);
1964 latLngToContainerPoint: function (latlng) {
1965 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1968 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1969 return L.DomEvent.getMousePosition(e, this._container);
1972 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1973 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1976 mouseEventToLatLng: function (e) { // (MouseEvent)
1977 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1981 // map initialization methods
1983 _initContainer: function (id) {
1984 var container = this._container = L.DomUtil.get(id);
1987 throw new Error('Map container not found.');
1988 } else if (container._leaflet) {
1989 throw new Error('Map container is already initialized.');
1992 container._leaflet = true;
1995 _initLayout: function () {
1996 var container = this._container;
1998 L.DomUtil.addClass(container, 'leaflet-container' +
1999 (L.Browser.touch ? ' leaflet-touch' : '') +
2000 (L.Browser.retina ? ' leaflet-retina' : '') +
2001 (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
2003 var position = L.DomUtil.getStyle(container, 'position');
2005 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
2006 container.style.position = 'relative';
2011 if (this._initControlPos) {
2012 this._initControlPos();
2016 _initPanes: function () {
2017 var panes = this._panes = {};
2019 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2021 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2022 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2023 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2024 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2025 panes.markerPane = this._createPane('leaflet-marker-pane');
2026 panes.popupPane = this._createPane('leaflet-popup-pane');
2028 var zoomHide = ' leaflet-zoom-hide';
2030 if (!this.options.markerZoomAnimation) {
2031 L.DomUtil.addClass(panes.markerPane, zoomHide);
2032 L.DomUtil.addClass(panes.shadowPane, zoomHide);
2033 L.DomUtil.addClass(panes.popupPane, zoomHide);
2037 _createPane: function (className, container) {
2038 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2041 _clearPanes: function () {
2042 this._container.removeChild(this._mapPane);
2045 _addLayers: function (layers) {
2046 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2048 for (var i = 0, len = layers.length; i < len; i++) {
2049 this.addLayer(layers[i]);
2054 // private methods that modify map state
2056 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2058 var zoomChanged = (this._zoom !== zoom);
2060 if (!afterZoomAnim) {
2061 this.fire('movestart');
2064 this.fire('zoomstart');
2069 this._initialCenter = center;
2071 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2073 if (!preserveMapOffset) {
2074 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2076 this._initialTopLeftPoint._add(this._getMapPanePos());
2079 this._tileLayersToLoad = this._tileLayersNum;
2081 var loading = !this._loaded;
2082 this._loaded = true;
2086 this.eachLayer(this._layerAdd, this);
2089 this.fire('viewreset', {hard: !preserveMapOffset});
2093 if (zoomChanged || afterZoomAnim) {
2094 this.fire('zoomend');
2097 this.fire('moveend', {hard: !preserveMapOffset});
2100 _rawPanBy: function (offset) {
2101 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2104 _getZoomSpan: function () {
2105 return this.getMaxZoom() - this.getMinZoom();
2108 _updateZoomLevels: function () {
2111 maxZoom = -Infinity,
2112 oldZoomSpan = this._getZoomSpan();
2114 for (i in this._zoomBoundLayers) {
2115 var layer = this._zoomBoundLayers[i];
2116 if (!isNaN(layer.options.minZoom)) {
2117 minZoom = Math.min(minZoom, layer.options.minZoom);
2119 if (!isNaN(layer.options.maxZoom)) {
2120 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2124 if (i === undefined) { // we have no tilelayers
2125 this._layersMaxZoom = this._layersMinZoom = undefined;
2127 this._layersMaxZoom = maxZoom;
2128 this._layersMinZoom = minZoom;
2131 if (oldZoomSpan !== this._getZoomSpan()) {
2132 this.fire('zoomlevelschange');
2136 _panInsideMaxBounds: function () {
2137 this.panInsideBounds(this.options.maxBounds);
2140 _checkIfLoaded: function () {
2141 if (!this._loaded) {
2142 throw new Error('Set map center and zoom first.');
2148 _initEvents: function (onOff) {
2149 if (!L.DomEvent) { return; }
2151 onOff = onOff || 'on';
2153 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2155 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2156 'mouseleave', 'mousemove', 'contextmenu'],
2159 for (i = 0, len = events.length; i < len; i++) {
2160 L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2163 if (this.options.trackResize) {
2164 L.DomEvent[onOff](window, 'resize', this._onResize, this);
2168 _onResize: function () {
2169 L.Util.cancelAnimFrame(this._resizeRequest);
2170 this._resizeRequest = L.Util.requestAnimFrame(
2171 this.invalidateSize, this, false, this._container);
2174 _onMouseClick: function (e) {
2175 if (!this._loaded || (!e._simulated && this.dragging && this.dragging.moved()) ||
2176 L.DomEvent._skipped(e)) { return; }
2178 this.fire('preclick');
2179 this._fireMouseEvent(e);
2182 _fireMouseEvent: function (e) {
2183 if (!this._loaded || L.DomEvent._skipped(e)) { return; }
2187 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2189 if (!this.hasEventListeners(type)) { return; }
2191 if (type === 'contextmenu') {
2192 L.DomEvent.preventDefault(e);
2195 var containerPoint = this.mouseEventToContainerPoint(e),
2196 layerPoint = this.containerPointToLayerPoint(containerPoint),
2197 latlng = this.layerPointToLatLng(layerPoint);
2201 layerPoint: layerPoint,
2202 containerPoint: containerPoint,
2207 _onTileLayerLoad: function () {
2208 this._tileLayersToLoad--;
2209 if (this._tileLayersNum && !this._tileLayersToLoad) {
2210 this.fire('tilelayersload');
2214 _clearHandlers: function () {
2215 for (var i = 0, len = this._handlers.length; i < len; i++) {
2216 this._handlers[i].disable();
2220 whenReady: function (callback, context) {
2222 callback.call(context || this, this);
2224 this.on('load', callback, context);
2229 _layerAdd: function (layer) {
2231 this.fire('layeradd', {layer: layer});
2235 // private methods for getting map state
2237 _getMapPanePos: function () {
2238 return L.DomUtil.getPosition(this._mapPane);
2241 _moved: function () {
2242 var pos = this._getMapPanePos();
2243 return pos && !pos.equals([0, 0]);
2246 _getTopLeftPoint: function () {
2247 return this.getPixelOrigin().subtract(this._getMapPanePos());
2250 _getNewTopLeftPoint: function (center, zoom) {
2251 var viewHalf = this.getSize()._divideBy(2);
2252 // TODO round on display, not calculation to increase precision?
2253 return this.project(center, zoom)._subtract(viewHalf)._round();
2256 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2257 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2258 return this.project(latlng, newZoom)._subtract(topLeft);
2261 // layer point of the current center
2262 _getCenterLayerPoint: function () {
2263 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2266 // offset of the specified place to the current center in pixels
2267 _getCenterOffset: function (latlng) {
2268 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2271 _limitZoom: function (zoom) {
2272 var min = this.getMinZoom(),
2273 max = this.getMaxZoom();
2275 return Math.max(min, Math.min(max, zoom));
2279 L.map = function (id, options) {
2280 return new L.Map(id, options);
2285 * Mercator projection that takes into account that the Earth is not a perfect sphere.
2286 * Less popular than spherical mercator; used by projections like EPSG:3395.
2289 L.Projection.Mercator = {
2290 MAX_LATITUDE: 85.0840591556,
2292 R_MINOR: 6356752.314245179,
2295 project: function (latlng) { // (LatLng) -> Point
2296 var d = L.LatLng.DEG_TO_RAD,
2297 max = this.MAX_LATITUDE,
2298 lat = Math.max(Math.min(max, latlng.lat), -max),
2301 x = latlng.lng * d * r,
2304 eccent = Math.sqrt(1.0 - tmp * tmp),
2305 con = eccent * Math.sin(y);
2307 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2309 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2310 y = -r * Math.log(ts);
2312 return new L.Point(x, y);
2315 unproject: function (point) { // (Point, Boolean) -> LatLng
2316 var d = L.LatLng.RAD_TO_DEG,
2319 lng = point.x * d / r,
2321 eccent = Math.sqrt(1 - (tmp * tmp)),
2322 ts = Math.exp(- point.y / r),
2323 phi = (Math.PI / 2) - 2 * Math.atan(ts),
2330 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2331 con = eccent * Math.sin(phi);
2332 dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2333 Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2337 return new L.LatLng(phi * d, lng);
2343 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2346 projection: L.Projection.Mercator,
2348 transformation: (function () {
2349 var m = L.Projection.Mercator,
2353 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
2359 * L.TileLayer is used for standard xyz-numbered tile layers.
2362 L.TileLayer = L.Class.extend({
2363 includes: L.Mixin.Events,
2374 /* (undefined works too)
2377 continuousWorld: false,
2380 detectRetina: false,
2384 unloadInvisibleTiles: L.Browser.mobile,
2385 updateWhenIdle: L.Browser.mobile
2388 initialize: function (url, options) {
2389 options = L.setOptions(this, options);
2391 // detecting retina displays, adjusting tileSize and zoom levels
2392 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2394 options.tileSize = Math.floor(options.tileSize / 2);
2395 options.zoomOffset++;
2397 if (options.minZoom > 0) {
2400 this.options.maxZoom--;
2403 if (options.bounds) {
2404 options.bounds = L.latLngBounds(options.bounds);
2409 var subdomains = this.options.subdomains;
2411 if (typeof subdomains === 'string') {
2412 this.options.subdomains = subdomains.split('');
2416 onAdd: function (map) {
2418 this._animated = map._zoomAnimated;
2420 // create a container div for tiles
2421 this._initContainer();
2423 // create an image to clone for tiles
2424 this._createTileProto();
2428 'viewreset': this._reset,
2429 'moveend': this._update
2432 if (this._animated) {
2434 'zoomanim': this._animateZoom,
2435 'zoomend': this._endZoomAnim
2439 if (!this.options.updateWhenIdle) {
2440 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2441 map.on('move', this._limitedUpdate, this);
2448 addTo: function (map) {
2453 onRemove: function (map) {
2454 this._container.parentNode.removeChild(this._container);
2457 'viewreset': this._reset,
2458 'moveend': this._update
2461 if (this._animated) {
2463 'zoomanim': this._animateZoom,
2464 'zoomend': this._endZoomAnim
2468 if (!this.options.updateWhenIdle) {
2469 map.off('move', this._limitedUpdate, this);
2472 this._container = null;
2476 bringToFront: function () {
2477 var pane = this._map._panes.tilePane;
2479 if (this._container) {
2480 pane.appendChild(this._container);
2481 this._setAutoZIndex(pane, Math.max);
2487 bringToBack: function () {
2488 var pane = this._map._panes.tilePane;
2490 if (this._container) {
2491 pane.insertBefore(this._container, pane.firstChild);
2492 this._setAutoZIndex(pane, Math.min);
2498 getAttribution: function () {
2499 return this.options.attribution;
2502 getContainer: function () {
2503 return this._container;
2506 setOpacity: function (opacity) {
2507 this.options.opacity = opacity;
2510 this._updateOpacity();
2516 setZIndex: function (zIndex) {
2517 this.options.zIndex = zIndex;
2518 this._updateZIndex();
2523 setUrl: function (url, noRedraw) {
2533 redraw: function () {
2535 this._reset({hard: true});
2541 _updateZIndex: function () {
2542 if (this._container && this.options.zIndex !== undefined) {
2543 this._container.style.zIndex = this.options.zIndex;
2547 _setAutoZIndex: function (pane, compare) {
2549 var layers = pane.children,
2550 edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2553 for (i = 0, len = layers.length; i < len; i++) {
2555 if (layers[i] !== this._container) {
2556 zIndex = parseInt(layers[i].style.zIndex, 10);
2558 if (!isNaN(zIndex)) {
2559 edgeZIndex = compare(edgeZIndex, zIndex);
2564 this.options.zIndex = this._container.style.zIndex =
2565 (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2568 _updateOpacity: function () {
2570 tiles = this._tiles;
2572 if (L.Browser.ielt9) {
2574 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2577 L.DomUtil.setOpacity(this._container, this.options.opacity);
2581 _initContainer: function () {
2582 var tilePane = this._map._panes.tilePane;
2584 if (!this._container) {
2585 this._container = L.DomUtil.create('div', 'leaflet-layer');
2587 this._updateZIndex();
2589 if (this._animated) {
2590 var className = 'leaflet-tile-container leaflet-zoom-animated';
2592 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2593 this._tileContainer = L.DomUtil.create('div', className, this._container);
2596 this._tileContainer = this._container;
2599 tilePane.appendChild(this._container);
2601 if (this.options.opacity < 1) {
2602 this._updateOpacity();
2607 _reset: function (e) {
2608 for (var key in this._tiles) {
2609 this.fire('tileunload', {tile: this._tiles[key]});
2613 this._tilesToLoad = 0;
2615 if (this.options.reuseTiles) {
2616 this._unusedTiles = [];
2619 this._tileContainer.innerHTML = '';
2621 if (this._animated && e && e.hard) {
2622 this._clearBgBuffer();
2625 this._initContainer();
2628 _update: function () {
2630 if (!this._map) { return; }
2632 var bounds = this._map.getPixelBounds(),
2633 zoom = this._map.getZoom(),
2634 tileSize = this.options.tileSize;
2636 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2640 var tileBounds = L.bounds(
2641 bounds.min.divideBy(tileSize)._floor(),
2642 bounds.max.divideBy(tileSize)._floor());
2644 this._addTilesFromCenterOut(tileBounds);
2646 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2647 this._removeOtherTiles(tileBounds);
2651 _addTilesFromCenterOut: function (bounds) {
2653 center = bounds.getCenter();
2657 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2658 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2659 point = new L.Point(i, j);
2661 if (this._tileShouldBeLoaded(point)) {
2667 var tilesToLoad = queue.length;
2669 if (tilesToLoad === 0) { return; }
2671 // load tiles in order of their distance to center
2672 queue.sort(function (a, b) {
2673 return a.distanceTo(center) - b.distanceTo(center);
2676 var fragment = document.createDocumentFragment();
2678 // if its the first batch of tiles to load
2679 if (!this._tilesToLoad) {
2680 this.fire('loading');
2683 this._tilesToLoad += tilesToLoad;
2685 for (i = 0; i < tilesToLoad; i++) {
2686 this._addTile(queue[i], fragment);
2689 this._tileContainer.appendChild(fragment);
2692 _tileShouldBeLoaded: function (tilePoint) {
2693 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2694 return false; // already loaded
2697 var options = this.options;
2699 if (!options.continuousWorld) {
2700 var limit = this._getWrapTileNum();
2702 // don't load if exceeds world bounds
2703 if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit)) ||
2704 tilePoint.y < 0 || tilePoint.y >= limit) { return false; }
2707 if (options.bounds) {
2708 var tileSize = options.tileSize,
2709 nwPoint = tilePoint.multiplyBy(tileSize),
2710 sePoint = nwPoint.add([tileSize, tileSize]),
2711 nw = this._map.unproject(nwPoint),
2712 se = this._map.unproject(sePoint);
2714 // TODO temporary hack, will be removed after refactoring projections
2715 // https://github.com/Leaflet/Leaflet/issues/1618
2716 if (!options.continuousWorld && !options.noWrap) {
2721 if (!options.bounds.intersects([nw, se])) { return false; }
2727 _removeOtherTiles: function (bounds) {
2728 var kArr, x, y, key;
2730 for (key in this._tiles) {
2731 kArr = key.split(':');
2732 x = parseInt(kArr[0], 10);
2733 y = parseInt(kArr[1], 10);
2735 // remove tile if it's out of bounds
2736 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2737 this._removeTile(key);
2742 _removeTile: function (key) {
2743 var tile = this._tiles[key];
2745 this.fire('tileunload', {tile: tile, url: tile.src});
2747 if (this.options.reuseTiles) {
2748 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2749 this._unusedTiles.push(tile);
2751 } else if (tile.parentNode === this._tileContainer) {
2752 this._tileContainer.removeChild(tile);
2755 // for https://github.com/CloudMade/Leaflet/issues/137
2756 if (!L.Browser.android) {
2758 tile.src = L.Util.emptyImageUrl;
2761 delete this._tiles[key];
2764 _addTile: function (tilePoint, container) {
2765 var tilePos = this._getTilePos(tilePoint);
2767 // get unused tile - or create a new tile
2768 var tile = this._getTile();
2771 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2772 Android 4 browser has display issues with top/left and requires transform instead
2773 Android 2 browser requires top/left or tiles disappear on load or first drag
2774 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2775 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2777 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2779 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2781 this._loadTile(tile, tilePoint);
2783 if (tile.parentNode !== this._tileContainer) {
2784 container.appendChild(tile);
2788 _getZoomForUrl: function () {
2790 var options = this.options,
2791 zoom = this._map.getZoom();
2793 if (options.zoomReverse) {
2794 zoom = options.maxZoom - zoom;
2797 return zoom + options.zoomOffset;
2800 _getTilePos: function (tilePoint) {
2801 var origin = this._map.getPixelOrigin(),
2802 tileSize = this.options.tileSize;
2804 return tilePoint.multiplyBy(tileSize).subtract(origin);
2807 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2809 getTileUrl: function (tilePoint) {
2810 return L.Util.template(this._url, L.extend({
2811 s: this._getSubdomain(tilePoint),
2818 _getWrapTileNum: function () {
2819 // TODO refactor, limit is not valid for non-standard projections
2820 return Math.pow(2, this._getZoomForUrl());
2823 _adjustTilePoint: function (tilePoint) {
2825 var limit = this._getWrapTileNum();
2827 // wrap tile coordinates
2828 if (!this.options.continuousWorld && !this.options.noWrap) {
2829 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2832 if (this.options.tms) {
2833 tilePoint.y = limit - tilePoint.y - 1;
2836 tilePoint.z = this._getZoomForUrl();
2839 _getSubdomain: function (tilePoint) {
2840 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2841 return this.options.subdomains[index];
2844 _createTileProto: function () {
2845 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2846 img.style.width = img.style.height = this.options.tileSize + 'px';
2847 img.galleryimg = 'no';
2850 _getTile: function () {
2851 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2852 var tile = this._unusedTiles.pop();
2853 this._resetTile(tile);
2856 return this._createTile();
2859 // Override if data stored on a tile needs to be cleaned up before reuse
2860 _resetTile: function (/*tile*/) {},
2862 _createTile: function () {
2863 var tile = this._tileImg.cloneNode(false);
2864 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2866 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2867 L.DomUtil.setOpacity(tile, this.options.opacity);
2872 _loadTile: function (tile, tilePoint) {
2874 tile.onload = this._tileOnLoad;
2875 tile.onerror = this._tileOnError;
2877 this._adjustTilePoint(tilePoint);
2878 tile.src = this.getTileUrl(tilePoint);
2881 _tileLoaded: function () {
2882 this._tilesToLoad--;
2883 if (!this._tilesToLoad) {
2886 if (this._animated) {
2887 // clear scaled tiles after all new tiles are loaded (for performance)
2888 clearTimeout(this._clearBgBufferTimer);
2889 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2894 _tileOnLoad: function () {
2895 var layer = this._layer;
2897 //Only if we are loading an actual image
2898 if (this.src !== L.Util.emptyImageUrl) {
2899 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2901 layer.fire('tileload', {
2907 layer._tileLoaded();
2910 _tileOnError: function () {
2911 var layer = this._layer;
2913 layer.fire('tileerror', {
2918 var newUrl = layer.options.errorTileUrl;
2923 layer._tileLoaded();
2927 L.tileLayer = function (url, options) {
2928 return new L.TileLayer(url, options);
2933 * L.TileLayer.WMS is used for putting WMS tile layers on the map.
2936 L.TileLayer.WMS = L.TileLayer.extend({
2944 format: 'image/jpeg',
2948 initialize: function (url, options) { // (String, Object)
2952 var wmsParams = L.extend({}, this.defaultWmsParams),
2953 tileSize = options.tileSize || this.options.tileSize;
2955 if (options.detectRetina && L.Browser.retina) {
2956 wmsParams.width = wmsParams.height = tileSize * 2;
2958 wmsParams.width = wmsParams.height = tileSize;
2961 for (var i in options) {
2962 // all keys that are not TileLayer options go to WMS params
2963 if (!this.options.hasOwnProperty(i) && i !== 'crs') {
2964 wmsParams[i] = options[i];
2968 this.wmsParams = wmsParams;
2970 L.setOptions(this, options);
2973 onAdd: function (map) {
2975 this._crs = this.options.crs || map.options.crs;
2977 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2978 this.wmsParams[projectionKey] = this._crs.code;
2980 L.TileLayer.prototype.onAdd.call(this, map);
2983 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
2985 var map = this._map,
2986 tileSize = this.options.tileSize,
2988 nwPoint = tilePoint.multiplyBy(tileSize),
2989 sePoint = nwPoint.add([tileSize, tileSize]),
2991 nw = this._crs.project(map.unproject(nwPoint, zoom)),
2992 se = this._crs.project(map.unproject(sePoint, zoom)),
2994 bbox = [nw.x, se.y, se.x, nw.y].join(','),
2996 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
2998 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
3001 setParams: function (params, noRedraw) {
3003 L.extend(this.wmsParams, params);
3013 L.tileLayer.wms = function (url, options) {
3014 return new L.TileLayer.WMS(url, options);
3019 * L.TileLayer.Canvas is a class that you can use as a base for creating
3020 * dynamically drawn Canvas-based tile layers.
3023 L.TileLayer.Canvas = L.TileLayer.extend({
3028 initialize: function (options) {
3029 L.setOptions(this, options);
3032 redraw: function () {
3034 this._reset({hard: true});
3038 for (var i in this._tiles) {
3039 this._redrawTile(this._tiles[i]);
3044 _redrawTile: function (tile) {
3045 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3048 _createTileProto: function () {
3049 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
3050 proto.width = proto.height = this.options.tileSize;
3053 _createTile: function () {
3054 var tile = this._canvasProto.cloneNode(false);
3055 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3059 _loadTile: function (tile, tilePoint) {
3061 tile._tilePoint = tilePoint;
3063 this._redrawTile(tile);
3065 if (!this.options.async) {
3066 this.tileDrawn(tile);
3070 drawTile: function (/*tile, tilePoint*/) {
3071 // override with rendering code
3074 tileDrawn: function (tile) {
3075 this._tileOnLoad.call(tile);
3080 L.tileLayer.canvas = function (options) {
3081 return new L.TileLayer.Canvas(options);
3086 * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3089 L.ImageOverlay = L.Class.extend({
3090 includes: L.Mixin.Events,
3096 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3098 this._bounds = L.latLngBounds(bounds);
3100 L.setOptions(this, options);
3103 onAdd: function (map) {
3110 map._panes.overlayPane.appendChild(this._image);
3112 map.on('viewreset', this._reset, this);
3114 if (map.options.zoomAnimation && L.Browser.any3d) {
3115 map.on('zoomanim', this._animateZoom, this);
3121 onRemove: function (map) {
3122 map.getPanes().overlayPane.removeChild(this._image);
3124 map.off('viewreset', this._reset, this);
3126 if (map.options.zoomAnimation) {
3127 map.off('zoomanim', this._animateZoom, this);
3131 addTo: function (map) {
3136 setOpacity: function (opacity) {
3137 this.options.opacity = opacity;
3138 this._updateOpacity();
3142 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3143 bringToFront: function () {
3145 this._map._panes.overlayPane.appendChild(this._image);
3150 bringToBack: function () {
3151 var pane = this._map._panes.overlayPane;
3153 pane.insertBefore(this._image, pane.firstChild);
3158 _initImage: function () {
3159 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3161 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3162 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3164 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3167 this._updateOpacity();
3169 //TODO createImage util method to remove duplication
3170 L.extend(this._image, {
3172 onselectstart: L.Util.falseFn,
3173 onmousemove: L.Util.falseFn,
3174 onload: L.bind(this._onImageLoad, this),
3179 _animateZoom: function (e) {
3180 var map = this._map,
3181 image = this._image,
3182 scale = map.getZoomScale(e.zoom),
3183 nw = this._bounds.getNorthWest(),
3184 se = this._bounds.getSouthEast(),
3186 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3187 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3188 origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3190 image.style[L.DomUtil.TRANSFORM] =
3191 L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3194 _reset: function () {
3195 var image = this._image,
3196 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3197 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3199 L.DomUtil.setPosition(image, topLeft);
3201 image.style.width = size.x + 'px';
3202 image.style.height = size.y + 'px';
3205 _onImageLoad: function () {
3209 _updateOpacity: function () {
3210 L.DomUtil.setOpacity(this._image, this.options.opacity);
3214 L.imageOverlay = function (url, bounds, options) {
3215 return new L.ImageOverlay(url, bounds, options);
3220 * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3223 L.Icon = L.Class.extend({
3226 iconUrl: (String) (required)
3227 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3228 iconSize: (Point) (can be set through CSS)
3229 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3230 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3231 shadowUrl: (String) (no shadow by default)
3232 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3234 shadowAnchor: (Point)
3239 initialize: function (options) {
3240 L.setOptions(this, options);
3243 createIcon: function (oldIcon) {
3244 return this._createIcon('icon', oldIcon);
3247 createShadow: function (oldIcon) {
3248 return this._createIcon('shadow', oldIcon);
3251 _createIcon: function (name, oldIcon) {
3252 var src = this._getIconUrl(name);
3255 if (name === 'icon') {
3256 throw new Error('iconUrl not set in Icon options (see the docs).');
3262 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3263 img = this._createImg(src);
3265 img = this._createImg(src, oldIcon);
3267 this._setIconStyles(img, name);
3272 _setIconStyles: function (img, name) {
3273 var options = this.options,
3274 size = L.point(options[name + 'Size']),
3277 if (name === 'shadow') {
3278 anchor = L.point(options.shadowAnchor || options.iconAnchor);
3280 anchor = L.point(options.iconAnchor);
3283 if (!anchor && size) {
3284 anchor = size.divideBy(2, true);
3287 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3290 img.style.marginLeft = (-anchor.x) + 'px';
3291 img.style.marginTop = (-anchor.y) + 'px';
3295 img.style.width = size.x + 'px';
3296 img.style.height = size.y + 'px';
3300 _createImg: function (src, el) {
3302 if (!L.Browser.ie6) {
3304 el = document.createElement('img');
3309 el = document.createElement('div');
3312 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
3317 _getIconUrl: function (name) {
3318 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3319 return this.options[name + 'RetinaUrl'];
3321 return this.options[name + 'Url'];
3325 L.icon = function (options) {
3326 return new L.Icon(options);
3331 * L.Icon.Default is the blue marker icon used by default in Leaflet.
3334 L.Icon.Default = L.Icon.extend({
3338 iconAnchor: [12, 41],
3339 popupAnchor: [1, -34],
3341 shadowSize: [41, 41]
3344 _getIconUrl: function (name) {
3345 var key = name + 'Url';
3347 if (this.options[key]) {
3348 return this.options[key];
3351 if (L.Browser.retina && name === 'icon') {
3355 var path = L.Icon.Default.imagePath;
3358 throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3361 return path + '/marker-' + name + '.png';
3365 L.Icon.Default.imagePath = (function () {
3366 var scripts = document.getElementsByTagName('script'),
3367 leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3369 var i, len, src, matches, path;
3371 for (i = 0, len = scripts.length; i < len; i++) {
3372 src = scripts[i].src;
3373 matches = src.match(leafletRe);
3376 path = src.split(leafletRe)[0];
3377 return (path ? path + '/' : '') + 'images';
3384 * L.Marker is used to display clickable/draggable icons on the map.
3387 L.Marker = L.Class.extend({
3389 includes: L.Mixin.Events,
3392 icon: new L.Icon.Default(),
3403 initialize: function (latlng, options) {
3404 L.setOptions(this, options);
3405 this._latlng = L.latLng(latlng);
3408 onAdd: function (map) {
3411 map.on('viewreset', this.update, this);
3416 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3417 map.on('zoomanim', this._animateZoom, this);
3421 addTo: function (map) {
3426 onRemove: function (map) {
3427 if (this.dragging) {
3428 this.dragging.disable();
3432 this._removeShadow();
3434 this.fire('remove');
3437 'viewreset': this.update,
3438 'zoomanim': this._animateZoom
3444 getLatLng: function () {
3445 return this._latlng;
3448 setLatLng: function (latlng) {
3449 this._latlng = L.latLng(latlng);
3453 return this.fire('move', { latlng: this._latlng });
3456 setZIndexOffset: function (offset) {
3457 this.options.zIndexOffset = offset;
3463 setIcon: function (icon) {
3465 this.options.icon = icon;
3475 update: function () {
3477 var pos = this._map.latLngToLayerPoint(this._latlng).round();
3484 _initIcon: function () {
3485 var options = this.options,
3487 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3488 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3490 var icon = options.icon.createIcon(this._icon),
3493 // if we're not reusing the icon, remove the old one and init new one
3494 if (icon !== this._icon) {
3500 if (options.title) {
3501 icon.title = options.title;
3505 L.DomUtil.addClass(icon, classToAdd);
3507 if (options.keyboard) {
3508 icon.tabIndex = '0';
3513 this._initInteraction();
3515 if (options.riseOnHover) {
3517 .on(icon, 'mouseover', this._bringToFront, this)
3518 .on(icon, 'mouseout', this._resetZIndex, this);
3521 var newShadow = options.icon.createShadow(this._shadow),
3524 if (newShadow !== this._shadow) {
3525 this._removeShadow();
3530 L.DomUtil.addClass(newShadow, classToAdd);
3532 this._shadow = newShadow;
3535 if (options.opacity < 1) {
3536 this._updateOpacity();
3540 var panes = this._map._panes;
3543 panes.markerPane.appendChild(this._icon);
3546 if (newShadow && addShadow) {
3547 panes.shadowPane.appendChild(this._shadow);
3551 _removeIcon: function () {
3552 if (this.options.riseOnHover) {
3554 .off(this._icon, 'mouseover', this._bringToFront)
3555 .off(this._icon, 'mouseout', this._resetZIndex);
3558 this._map._panes.markerPane.removeChild(this._icon);
3563 _removeShadow: function () {
3565 this._map._panes.shadowPane.removeChild(this._shadow);
3567 this._shadow = null;
3570 _setPos: function (pos) {
3571 L.DomUtil.setPosition(this._icon, pos);
3574 L.DomUtil.setPosition(this._shadow, pos);
3577 this._zIndex = pos.y + this.options.zIndexOffset;
3579 this._resetZIndex();
3582 _updateZIndex: function (offset) {
3583 this._icon.style.zIndex = this._zIndex + offset;
3586 _animateZoom: function (opt) {
3587 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3592 _initInteraction: function () {
3594 if (!this.options.clickable) { return; }
3596 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3598 var icon = this._icon,
3599 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3601 L.DomUtil.addClass(icon, 'leaflet-clickable');
3602 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3603 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3605 for (var i = 0; i < events.length; i++) {
3606 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3609 if (L.Handler.MarkerDrag) {
3610 this.dragging = new L.Handler.MarkerDrag(this);
3612 if (this.options.draggable) {
3613 this.dragging.enable();
3618 _onMouseClick: function (e) {
3619 var wasDragged = this.dragging && this.dragging.moved();
3621 if (this.hasEventListeners(e.type) || wasDragged) {
3622 L.DomEvent.stopPropagation(e);
3625 if (wasDragged) { return; }
3627 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3631 latlng: this._latlng
3635 _onKeyPress: function (e) {
3636 if (e.keyCode === 13) {
3637 this.fire('click', {
3639 latlng: this._latlng
3644 _fireMouseEvent: function (e) {
3648 latlng: this._latlng
3651 // TODO proper custom event propagation
3652 // this line will always be called if marker is in a FeatureGroup
3653 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3654 L.DomEvent.preventDefault(e);
3656 if (e.type !== 'mousedown') {
3657 L.DomEvent.stopPropagation(e);
3659 L.DomEvent.preventDefault(e);
3663 setOpacity: function (opacity) {
3664 this.options.opacity = opacity;
3666 this._updateOpacity();
3672 _updateOpacity: function () {
3673 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3675 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3679 _bringToFront: function () {
3680 this._updateZIndex(this.options.riseOffset);
3683 _resetZIndex: function () {
3684 this._updateZIndex(0);
3688 L.marker = function (latlng, options) {
3689 return new L.Marker(latlng, options);
3694 * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3695 * to use with L.Marker.
3698 L.DivIcon = L.Icon.extend({
3700 iconSize: [12, 12], // also can be set through CSS
3703 popupAnchor: (Point)
3707 className: 'leaflet-div-icon',
3711 createIcon: function (oldIcon) {
3712 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3713 options = this.options;
3715 if (options.html !== false) {
3716 div.innerHTML = options.html;
3721 if (options.bgPos) {
3722 div.style.backgroundPosition =
3723 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3726 this._setIconStyles(div, 'icon');
3730 createShadow: function () {
3735 L.divIcon = function (options) {
3736 return new L.DivIcon(options);
3741 * L.Popup is used for displaying popups on the map.
3744 L.Map.mergeOptions({
3745 closePopupOnClick: true
3748 L.Popup = L.Class.extend({
3749 includes: L.Mixin.Events,
3758 autoPanPadding: [5, 5],
3764 initialize: function (options, source) {
3765 L.setOptions(this, options);
3767 this._source = source;
3768 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3769 this._isOpen = false;
3772 onAdd: function (map) {
3775 if (!this._container) {
3778 this._updateContent();
3780 var animFade = map.options.fadeAnimation;
3783 L.DomUtil.setOpacity(this._container, 0);
3785 map._panes.popupPane.appendChild(this._container);
3787 map.on(this._getEvents(), this);
3792 L.DomUtil.setOpacity(this._container, 1);
3797 map.fire('popupopen', {popup: this});
3800 this._source.fire('popupopen', {popup: this});
3804 addTo: function (map) {
3809 openOn: function (map) {
3810 map.openPopup(this);
3814 onRemove: function (map) {
3815 map._panes.popupPane.removeChild(this._container);
3817 L.Util.falseFn(this._container.offsetWidth); // force reflow
3819 map.off(this._getEvents(), this);
3821 if (map.options.fadeAnimation) {
3822 L.DomUtil.setOpacity(this._container, 0);
3829 map.fire('popupclose', {popup: this});
3832 this._source.fire('popupclose', {popup: this});
3836 setLatLng: function (latlng) {
3837 this._latlng = L.latLng(latlng);
3842 setContent: function (content) {
3843 this._content = content;
3848 _getEvents: function () {
3850 viewreset: this._updatePosition
3853 if (this._animated) {
3854 events.zoomanim = this._zoomAnimation;
3856 if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
3857 events.preclick = this._close;
3859 if (this.options.keepInView) {
3860 events.moveend = this._adjustPan;
3866 _close: function () {
3868 this._map.closePopup(this);
3872 _initLayout: function () {
3873 var prefix = 'leaflet-popup',
3874 containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
3875 (this._animated ? 'animated' : 'hide'),
3876 container = this._container = L.DomUtil.create('div', containerClass),
3879 if (this.options.closeButton) {
3880 closeButton = this._closeButton =
3881 L.DomUtil.create('a', prefix + '-close-button', container);
3882 closeButton.href = '#close';
3883 closeButton.innerHTML = '×';
3884 L.DomEvent.disableClickPropagation(closeButton);
3886 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3889 var wrapper = this._wrapper =
3890 L.DomUtil.create('div', prefix + '-content-wrapper', container);
3891 L.DomEvent.disableClickPropagation(wrapper);
3893 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3894 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
3895 L.DomEvent.on(this._contentNode, 'MozMousePixelScroll', L.DomEvent.stopPropagation);
3896 L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
3897 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3898 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3901 _update: function () {
3902 if (!this._map) { return; }
3904 this._container.style.visibility = 'hidden';
3906 this._updateContent();
3907 this._updateLayout();
3908 this._updatePosition();
3910 this._container.style.visibility = '';
3915 _updateContent: function () {
3916 if (!this._content) { return; }
3918 if (typeof this._content === 'string') {
3919 this._contentNode.innerHTML = this._content;
3921 while (this._contentNode.hasChildNodes()) {
3922 this._contentNode.removeChild(this._contentNode.firstChild);
3924 this._contentNode.appendChild(this._content);
3926 this.fire('contentupdate');
3929 _updateLayout: function () {
3930 var container = this._contentNode,
3931 style = container.style;
3934 style.whiteSpace = 'nowrap';
3936 var width = container.offsetWidth;
3937 width = Math.min(width, this.options.maxWidth);
3938 width = Math.max(width, this.options.minWidth);
3940 style.width = (width + 1) + 'px';
3941 style.whiteSpace = '';
3945 var height = container.offsetHeight,
3946 maxHeight = this.options.maxHeight,
3947 scrolledClass = 'leaflet-popup-scrolled';
3949 if (maxHeight && height > maxHeight) {
3950 style.height = maxHeight + 'px';
3951 L.DomUtil.addClass(container, scrolledClass);
3953 L.DomUtil.removeClass(container, scrolledClass);
3956 this._containerWidth = this._container.offsetWidth;
3959 _updatePosition: function () {
3960 if (!this._map) { return; }
3962 var pos = this._map.latLngToLayerPoint(this._latlng),
3963 animated = this._animated,
3964 offset = L.point(this.options.offset);
3967 L.DomUtil.setPosition(this._container, pos);
3970 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
3971 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
3973 // bottom position the popup in case the height of the popup changes (images loading etc)
3974 this._container.style.bottom = this._containerBottom + 'px';
3975 this._container.style.left = this._containerLeft + 'px';
3978 _zoomAnimation: function (opt) {
3979 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3981 L.DomUtil.setPosition(this._container, pos);
3984 _adjustPan: function () {
3985 if (!this.options.autoPan) { return; }
3987 var map = this._map,
3988 containerHeight = this._container.offsetHeight,
3989 containerWidth = this._containerWidth,
3991 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
3993 if (this._animated) {
3994 layerPos._add(L.DomUtil.getPosition(this._container));
3997 var containerPos = map.layerPointToContainerPoint(layerPos),
3998 padding = L.point(this.options.autoPanPadding),
3999 size = map.getSize(),
4003 if (containerPos.x + containerWidth > size.x) { // right
4004 dx = containerPos.x + containerWidth - size.x + padding.x;
4006 if (containerPos.x - dx < 0) { // left
4007 dx = containerPos.x - padding.x;
4009 if (containerPos.y + containerHeight > size.y) { // bottom
4010 dy = containerPos.y + containerHeight - size.y + padding.y;
4012 if (containerPos.y - dy < 0) { // top
4013 dy = containerPos.y - padding.y;
4018 .fire('autopanstart')
4023 _onCloseButtonClick: function (e) {
4029 L.popup = function (options, source) {
4030 return new L.Popup(options, source);
4035 openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
4038 if (!(popup instanceof L.Popup)) {
4039 var content = popup;
4041 popup = new L.Popup(options)
4043 .setContent(content);
4045 popup._isOpen = true;
4047 this._popup = popup;
4048 return this.addLayer(popup);
4051 closePopup: function (popup) {
4052 if (!popup || popup === this._popup) {
4053 popup = this._popup;
4057 this.removeLayer(popup);
4058 popup._isOpen = false;
4066 * Popup extension to L.Marker, adding popup-related methods.
4070 openPopup: function () {
4071 if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
4072 this._popup.setLatLng(this._latlng);
4073 this._map.openPopup(this._popup);
4079 closePopup: function () {
4081 this._popup._close();
4086 togglePopup: function () {
4088 if (this._popup._isOpen) {
4097 bindPopup: function (content, options) {
4098 var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
4100 anchor = anchor.add(L.Popup.prototype.options.offset);
4102 if (options && options.offset) {
4103 anchor = anchor.add(options.offset);
4106 options = L.extend({offset: anchor}, options);
4110 .on('click', this.togglePopup, this)
4111 .on('remove', this.closePopup, this)
4112 .on('move', this._movePopup, this);
4115 if (content instanceof L.Popup) {
4116 L.setOptions(content, options);
4117 this._popup = content;
4119 this._popup = new L.Popup(options, this)
4120 .setContent(content);
4126 setPopupContent: function (content) {
4128 this._popup.setContent(content);
4133 unbindPopup: function () {
4137 .off('click', this.togglePopup)
4138 .off('remove', this.closePopup)
4139 .off('move', this._movePopup);
4144 _movePopup: function (e) {
4145 this._popup.setLatLng(e.latlng);
4151 * L.LayerGroup is a class to combine several layers into one so that
4152 * you can manipulate the group (e.g. add/remove it) as one layer.
4155 L.LayerGroup = L.Class.extend({
4156 initialize: function (layers) {
4162 for (i = 0, len = layers.length; i < len; i++) {
4163 this.addLayer(layers[i]);
4168 addLayer: function (layer) {
4169 var id = this.getLayerId(layer);
4171 this._layers[id] = layer;
4174 this._map.addLayer(layer);
4180 removeLayer: function (layer) {
4181 var id = layer in this._layers ? layer : this.getLayerId(layer);
4183 if (this._map && this._layers[id]) {
4184 this._map.removeLayer(this._layers[id]);
4187 delete this._layers[id];
4192 hasLayer: function (layer) {
4193 if (!layer) { return false; }
4195 return (layer in this._layers || this.getLayerId(layer) in this._layers);
4198 clearLayers: function () {
4199 this.eachLayer(this.removeLayer, this);
4203 invoke: function (methodName) {
4204 var args = Array.prototype.slice.call(arguments, 1),
4207 for (i in this._layers) {
4208 layer = this._layers[i];
4210 if (layer[methodName]) {
4211 layer[methodName].apply(layer, args);
4218 onAdd: function (map) {
4220 this.eachLayer(map.addLayer, map);
4223 onRemove: function (map) {
4224 this.eachLayer(map.removeLayer, map);
4228 addTo: function (map) {
4233 eachLayer: function (method, context) {
4234 for (var i in this._layers) {
4235 method.call(context, this._layers[i]);
4240 getLayer: function (id) {
4241 return this._layers[id];
4244 getLayers: function () {
4247 for (var i in this._layers) {
4248 layers.push(this._layers[i]);
4253 setZIndex: function (zIndex) {
4254 return this.invoke('setZIndex', zIndex);
4257 getLayerId: function (layer) {
4258 return L.stamp(layer);
4262 L.layerGroup = function (layers) {
4263 return new L.LayerGroup(layers);
4268 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
4269 * shared between a group of interactive layers (like vectors or markers).
4272 L.FeatureGroup = L.LayerGroup.extend({
4273 includes: L.Mixin.Events,
4276 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
4279 addLayer: function (layer) {
4280 if (this.hasLayer(layer)) {
4284 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4286 L.LayerGroup.prototype.addLayer.call(this, layer);
4288 if (this._popupContent && layer.bindPopup) {
4289 layer.bindPopup(this._popupContent, this._popupOptions);
4292 return this.fire('layeradd', {layer: layer});
4295 removeLayer: function (layer) {
4296 if (!this.hasLayer(layer)) {
4299 if (layer in this._layers) {
4300 layer = this._layers[layer];
4303 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4305 L.LayerGroup.prototype.removeLayer.call(this, layer);
4307 if (this._popupContent) {
4308 this.invoke('unbindPopup');
4311 return this.fire('layerremove', {layer: layer});
4314 bindPopup: function (content, options) {
4315 this._popupContent = content;
4316 this._popupOptions = options;
4317 return this.invoke('bindPopup', content, options);
4320 setStyle: function (style) {
4321 return this.invoke('setStyle', style);
4324 bringToFront: function () {
4325 return this.invoke('bringToFront');
4328 bringToBack: function () {
4329 return this.invoke('bringToBack');
4332 getBounds: function () {
4333 var bounds = new L.LatLngBounds();
4335 this.eachLayer(function (layer) {
4336 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
4342 _propagateEvent: function (e) {
4348 this.fire(e.type, e);
4352 L.featureGroup = function (layers) {
4353 return new L.FeatureGroup(layers);
4358 * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
4361 L.Path = L.Class.extend({
4362 includes: [L.Mixin.Events],
4365 // how much to extend the clip area around the map view
4366 // (relative to its size, e.g. 0.5 is half the screen in each direction)
4367 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
4368 CLIP_PADDING: (function () {
4369 var max = L.Browser.mobile ? 1280 : 2000,
4370 target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
4371 return Math.max(0, Math.min(0.5, target));
4383 fillColor: null, //same as color by default
4389 initialize: function (options) {
4390 L.setOptions(this, options);
4393 onAdd: function (map) {
4396 if (!this._container) {
4397 this._initElements();
4401 this.projectLatlngs();
4404 if (this._container) {
4405 this._map._pathRoot.appendChild(this._container);
4411 'viewreset': this.projectLatlngs,
4412 'moveend': this._updatePath
4416 addTo: function (map) {
4421 onRemove: function (map) {
4422 map._pathRoot.removeChild(this._container);
4424 // Need to fire remove event before we set _map to null as the event hooks might need the object
4425 this.fire('remove');
4428 if (L.Browser.vml) {
4429 this._container = null;
4430 this._stroke = null;
4435 'viewreset': this.projectLatlngs,
4436 'moveend': this._updatePath
4440 projectLatlngs: function () {
4441 // do all projection stuff here
4444 setStyle: function (style) {
4445 L.setOptions(this, style);
4447 if (this._container) {
4448 this._updateStyle();
4454 redraw: function () {
4456 this.projectLatlngs();
4464 _updatePathViewport: function () {
4465 var p = L.Path.CLIP_PADDING,
4466 size = this.getSize(),
4467 panePos = L.DomUtil.getPosition(this._mapPane),
4468 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4469 max = min.add(size.multiplyBy(1 + p * 2)._round());
4471 this._pathViewport = new L.Bounds(min, max);
4477 * Extends L.Path with SVG-specific rendering code.
4480 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4482 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4484 L.Path = L.Path.extend({
4489 bringToFront: function () {
4490 var root = this._map._pathRoot,
4491 path = this._container;
4493 if (path && root.lastChild !== path) {
4494 root.appendChild(path);
4499 bringToBack: function () {
4500 var root = this._map._pathRoot,
4501 path = this._container,
4502 first = root.firstChild;
4504 if (path && first !== path) {
4505 root.insertBefore(path, first);
4510 getPathString: function () {
4511 // form path string here
4514 _createElement: function (name) {
4515 return document.createElementNS(L.Path.SVG_NS, name);
4518 _initElements: function () {
4519 this._map._initPathRoot();
4524 _initPath: function () {
4525 this._container = this._createElement('g');
4527 this._path = this._createElement('path');
4528 this._container.appendChild(this._path);
4531 _initStyle: function () {
4532 if (this.options.stroke) {
4533 this._path.setAttribute('stroke-linejoin', 'round');
4534 this._path.setAttribute('stroke-linecap', 'round');
4536 if (this.options.fill) {
4537 this._path.setAttribute('fill-rule', 'evenodd');
4539 if (this.options.pointerEvents) {
4540 this._path.setAttribute('pointer-events', this.options.pointerEvents);
4542 if (!this.options.clickable && !this.options.pointerEvents) {
4543 this._path.setAttribute('pointer-events', 'none');
4545 this._updateStyle();
4548 _updateStyle: function () {
4549 if (this.options.stroke) {
4550 this._path.setAttribute('stroke', this.options.color);
4551 this._path.setAttribute('stroke-opacity', this.options.opacity);
4552 this._path.setAttribute('stroke-width', this.options.weight);
4553 if (this.options.dashArray) {
4554 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4556 this._path.removeAttribute('stroke-dasharray');
4559 this._path.setAttribute('stroke', 'none');
4561 if (this.options.fill) {
4562 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4563 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4565 this._path.setAttribute('fill', 'none');
4569 _updatePath: function () {
4570 var str = this.getPathString();
4572 // fix webkit empty string parsing bug
4575 this._path.setAttribute('d', str);
4578 // TODO remove duplication with L.Map
4579 _initEvents: function () {
4580 if (this.options.clickable) {
4581 if (L.Browser.svg || !L.Browser.vml) {
4582 this._path.setAttribute('class', 'leaflet-clickable');
4585 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4587 var events = ['dblclick', 'mousedown', 'mouseover',
4588 'mouseout', 'mousemove', 'contextmenu'];
4589 for (var i = 0; i < events.length; i++) {
4590 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4595 _onMouseClick: function (e) {
4596 if (this._map.dragging && this._map.dragging.moved()) { return; }
4598 this._fireMouseEvent(e);
4601 _fireMouseEvent: function (e) {
4602 if (!this.hasEventListeners(e.type)) { return; }
4604 var map = this._map,
4605 containerPoint = map.mouseEventToContainerPoint(e),
4606 layerPoint = map.containerPointToLayerPoint(containerPoint),
4607 latlng = map.layerPointToLatLng(layerPoint);
4611 layerPoint: layerPoint,
4612 containerPoint: containerPoint,
4616 if (e.type === 'contextmenu') {
4617 L.DomEvent.preventDefault(e);
4619 if (e.type !== 'mousemove') {
4620 L.DomEvent.stopPropagation(e);
4626 _initPathRoot: function () {
4627 if (!this._pathRoot) {
4628 this._pathRoot = L.Path.prototype._createElement('svg');
4629 this._panes.overlayPane.appendChild(this._pathRoot);
4631 if (this.options.zoomAnimation && L.Browser.any3d) {
4632 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
4635 'zoomanim': this._animatePathZoom,
4636 'zoomend': this._endPathZoom
4639 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
4642 this.on('moveend', this._updateSvgViewport);
4643 this._updateSvgViewport();
4647 _animatePathZoom: function (e) {
4648 var scale = this.getZoomScale(e.zoom),
4649 offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4651 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4652 L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4654 this._pathZooming = true;
4657 _endPathZoom: function () {
4658 this._pathZooming = false;
4661 _updateSvgViewport: function () {
4663 if (this._pathZooming) {
4664 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4665 // When the zoom animation ends we will be updated again anyway
4666 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4670 this._updatePathViewport();
4672 var vp = this._pathViewport,
4675 width = max.x - min.x,
4676 height = max.y - min.y,
4677 root = this._pathRoot,
4678 pane = this._panes.overlayPane;
4680 // Hack to make flicker on drag end on mobile webkit less irritating
4681 if (L.Browser.mobileWebkit) {
4682 pane.removeChild(root);
4685 L.DomUtil.setPosition(root, min);
4686 root.setAttribute('width', width);
4687 root.setAttribute('height', height);
4688 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4690 if (L.Browser.mobileWebkit) {
4691 pane.appendChild(root);
4698 * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4703 bindPopup: function (content, options) {
4705 if (content instanceof L.Popup) {
4706 this._popup = content;
4708 if (!this._popup || options) {
4709 this._popup = new L.Popup(options, this);
4711 this._popup.setContent(content);
4714 if (!this._popupHandlersAdded) {
4716 .on('click', this._openPopup, this)
4717 .on('remove', this.closePopup, this);
4719 this._popupHandlersAdded = true;
4725 unbindPopup: function () {
4729 .off('click', this._openPopup)
4730 .off('remove', this.closePopup);
4732 this._popupHandlersAdded = false;
4737 openPopup: function (latlng) {
4740 // open the popup from one of the path's points if not specified
4741 latlng = latlng || this._latlng ||
4742 this._latlngs[Math.floor(this._latlngs.length / 2)];
4744 this._openPopup({latlng: latlng});
4750 closePopup: function () {
4752 this._popup._close();
4757 _openPopup: function (e) {
4758 this._popup.setLatLng(e.latlng);
4759 this._map.openPopup(this._popup);
4765 * Vector rendering for IE6-8 through VML.
4766 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4769 L.Browser.vml = !L.Browser.svg && (function () {
4771 var div = document.createElement('div');
4772 div.innerHTML = '<v:shape adj="1"/>';
4774 var shape = div.firstChild;
4775 shape.style.behavior = 'url(#default#VML)';
4777 return shape && (typeof shape.adj === 'object');
4784 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4790 _createElement: (function () {
4792 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4793 return function (name) {
4794 return document.createElement('<lvml:' + name + ' class="lvml">');
4797 return function (name) {
4798 return document.createElement(
4799 '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4804 _initPath: function () {
4805 var container = this._container = this._createElement('shape');
4806 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4807 if (this.options.clickable) {
4808 L.DomUtil.addClass(container, 'leaflet-clickable');
4810 container.coordsize = '1 1';
4812 this._path = this._createElement('path');
4813 container.appendChild(this._path);
4815 this._map._pathRoot.appendChild(container);
4818 _initStyle: function () {
4819 this._updateStyle();
4822 _updateStyle: function () {
4823 var stroke = this._stroke,
4825 options = this.options,
4826 container = this._container;
4828 container.stroked = options.stroke;
4829 container.filled = options.fill;
4831 if (options.stroke) {
4833 stroke = this._stroke = this._createElement('stroke');
4834 stroke.endcap = 'round';
4835 container.appendChild(stroke);
4837 stroke.weight = options.weight + 'px';
4838 stroke.color = options.color;
4839 stroke.opacity = options.opacity;
4841 if (options.dashArray) {
4842 stroke.dashStyle = options.dashArray instanceof Array ?
4843 options.dashArray.join(' ') :
4844 options.dashArray.replace(/( *, *)/g, ' ');
4846 stroke.dashStyle = '';
4849 } else if (stroke) {
4850 container.removeChild(stroke);
4851 this._stroke = null;
4856 fill = this._fill = this._createElement('fill');
4857 container.appendChild(fill);
4859 fill.color = options.fillColor || options.color;
4860 fill.opacity = options.fillOpacity;
4863 container.removeChild(fill);
4868 _updatePath: function () {
4869 var style = this._container.style;
4871 style.display = 'none';
4872 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4877 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4878 _initPathRoot: function () {
4879 if (this._pathRoot) { return; }
4881 var root = this._pathRoot = document.createElement('div');
4882 root.className = 'leaflet-vml-container';
4883 this._panes.overlayPane.appendChild(root);
4885 this.on('moveend', this._updatePathViewport);
4886 this._updatePathViewport();
4892 * Vector rendering for all browsers that support canvas.
4895 L.Browser.canvas = (function () {
4896 return !!document.createElement('canvas').getContext;
4899 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4901 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4906 redraw: function () {
4908 this.projectLatlngs();
4909 this._requestUpdate();
4914 setStyle: function (style) {
4915 L.setOptions(this, style);
4918 this._updateStyle();
4919 this._requestUpdate();
4924 onRemove: function (map) {
4926 .off('viewreset', this.projectLatlngs, this)
4927 .off('moveend', this._updatePath, this);
4929 if (this.options.clickable) {
4930 this._map.off('click', this._onClick, this);
4931 this._map.off('mousemove', this._onMouseMove, this);
4934 this._requestUpdate();
4939 _requestUpdate: function () {
4940 if (this._map && !L.Path._updateRequest) {
4941 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4945 _fireMapMoveEnd: function () {
4946 L.Path._updateRequest = null;
4947 this.fire('moveend');
4950 _initElements: function () {
4951 this._map._initPathRoot();
4952 this._ctx = this._map._canvasCtx;
4955 _updateStyle: function () {
4956 var options = this.options;
4958 if (options.stroke) {
4959 this._ctx.lineWidth = options.weight;
4960 this._ctx.strokeStyle = options.color;
4963 this._ctx.fillStyle = options.fillColor || options.color;
4967 _drawPath: function () {
4968 var i, j, len, len2, point, drawMethod;
4970 this._ctx.beginPath();
4972 for (i = 0, len = this._parts.length; i < len; i++) {
4973 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4974 point = this._parts[i][j];
4975 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4977 this._ctx[drawMethod](point.x, point.y);
4979 // TODO refactor ugly hack
4980 if (this instanceof L.Polygon) {
4981 this._ctx.closePath();
4986 _checkIfEmpty: function () {
4987 return !this._parts.length;
4990 _updatePath: function () {
4991 if (this._checkIfEmpty()) { return; }
4993 var ctx = this._ctx,
4994 options = this.options;
4998 this._updateStyle();
5001 ctx.globalAlpha = options.fillOpacity;
5005 if (options.stroke) {
5006 ctx.globalAlpha = options.opacity;
5012 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
5015 _initEvents: function () {
5016 if (this.options.clickable) {
5018 this._map.on('mousemove', this._onMouseMove, this);
5019 this._map.on('click', this._onClick, this);
5023 _onClick: function (e) {
5024 if (this._containsPoint(e.layerPoint)) {
5025 this.fire('click', e);
5029 _onMouseMove: function (e) {
5030 if (!this._map || this._map._animatingZoom) { return; }
5032 // TODO don't do on each move
5033 if (this._containsPoint(e.layerPoint)) {
5034 this._ctx.canvas.style.cursor = 'pointer';
5035 this._mouseInside = true;
5036 this.fire('mouseover', e);
5038 } else if (this._mouseInside) {
5039 this._ctx.canvas.style.cursor = '';
5040 this._mouseInside = false;
5041 this.fire('mouseout', e);
5046 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
5047 _initPathRoot: function () {
5048 var root = this._pathRoot,
5052 root = this._pathRoot = document.createElement('canvas');
5053 root.style.position = 'absolute';
5054 ctx = this._canvasCtx = root.getContext('2d');
5056 ctx.lineCap = 'round';
5057 ctx.lineJoin = 'round';
5059 this._panes.overlayPane.appendChild(root);
5061 if (this.options.zoomAnimation) {
5062 this._pathRoot.className = 'leaflet-zoom-animated';
5063 this.on('zoomanim', this._animatePathZoom);
5064 this.on('zoomend', this._endPathZoom);
5066 this.on('moveend', this._updateCanvasViewport);
5067 this._updateCanvasViewport();
5071 _updateCanvasViewport: function () {
5072 // don't redraw while zooming. See _updateSvgViewport for more details
5073 if (this._pathZooming) { return; }
5074 this._updatePathViewport();
5076 var vp = this._pathViewport,
5078 size = vp.max.subtract(min),
5079 root = this._pathRoot;
5081 //TODO check if this works properly on mobile webkit
5082 L.DomUtil.setPosition(root, min);
5083 root.width = size.x;
5084 root.height = size.y;
5085 root.getContext('2d').translate(-min.x, -min.y);
5091 * L.LineUtil contains different utility functions for line segments
5092 * and polylines (clipping, simplification, distances, etc.)
5095 /*jshint bitwise:false */ // allow bitwise oprations for this file
5099 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
5100 // Improves rendering performance dramatically by lessening the number of points to draw.
5102 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
5103 if (!tolerance || !points.length) {
5104 return points.slice();
5107 var sqTolerance = tolerance * tolerance;
5109 // stage 1: vertex reduction
5110 points = this._reducePoints(points, sqTolerance);
5112 // stage 2: Douglas-Peucker simplification
5113 points = this._simplifyDP(points, sqTolerance);
5118 // distance from a point to a segment between two points
5119 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5120 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
5123 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5124 return this._sqClosestPointOnSegment(p, p1, p2);
5127 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
5128 _simplifyDP: function (points, sqTolerance) {
5130 var len = points.length,
5131 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
5132 markers = new ArrayConstructor(len);
5134 markers[0] = markers[len - 1] = 1;
5136 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
5141 for (i = 0; i < len; i++) {
5143 newPoints.push(points[i]);
5150 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
5155 for (i = first + 1; i <= last - 1; i++) {
5156 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
5158 if (sqDist > maxSqDist) {
5164 if (maxSqDist > sqTolerance) {
5167 this._simplifyDPStep(points, markers, sqTolerance, first, index);
5168 this._simplifyDPStep(points, markers, sqTolerance, index, last);
5172 // reduce points that are too close to each other to a single point
5173 _reducePoints: function (points, sqTolerance) {
5174 var reducedPoints = [points[0]];
5176 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
5177 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
5178 reducedPoints.push(points[i]);
5182 if (prev < len - 1) {
5183 reducedPoints.push(points[len - 1]);
5185 return reducedPoints;
5188 // Cohen-Sutherland line clipping algorithm.
5189 // Used to avoid rendering parts of a polyline that are not currently visible.
5191 clipSegment: function (a, b, bounds, useLastCode) {
5192 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
5193 codeB = this._getBitCode(b, bounds),
5195 codeOut, p, newCode;
5197 // save 2nd code to avoid calculating it on the next segment
5198 this._lastCode = codeB;
5201 // if a,b is inside the clip window (trivial accept)
5202 if (!(codeA | codeB)) {
5204 // if a,b is outside the clip window (trivial reject)
5205 } else if (codeA & codeB) {
5209 codeOut = codeA || codeB;
5210 p = this._getEdgeIntersection(a, b, codeOut, bounds);
5211 newCode = this._getBitCode(p, bounds);
5213 if (codeOut === codeA) {
5224 _getEdgeIntersection: function (a, b, code, bounds) {
5230 if (code & 8) { // top
5231 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
5232 } else if (code & 4) { // bottom
5233 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
5234 } else if (code & 2) { // right
5235 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
5236 } else if (code & 1) { // left
5237 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
5241 _getBitCode: function (/*Point*/ p, bounds) {
5244 if (p.x < bounds.min.x) { // left
5246 } else if (p.x > bounds.max.x) { // right
5249 if (p.y < bounds.min.y) { // bottom
5251 } else if (p.y > bounds.max.y) { // top
5258 // square distance (to avoid unnecessary Math.sqrt calls)
5259 _sqDist: function (p1, p2) {
5260 var dx = p2.x - p1.x,
5262 return dx * dx + dy * dy;
5265 // return closest point on segment or distance to that point
5266 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
5271 dot = dx * dx + dy * dy,
5275 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
5289 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
5295 * L.Polyline is used to display polylines on a map.
5298 L.Polyline = L.Path.extend({
5299 initialize: function (latlngs, options) {
5300 L.Path.prototype.initialize.call(this, options);
5302 this._latlngs = this._convertLatLngs(latlngs);
5306 // how much to simplify the polyline on each zoom level
5307 // more = better performance and smoother look, less = more accurate
5312 projectLatlngs: function () {
5313 this._originalPoints = [];
5315 for (var i = 0, len = this._latlngs.length; i < len; i++) {
5316 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
5320 getPathString: function () {
5321 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
5322 str += this._getPathPartStr(this._parts[i]);
5327 getLatLngs: function () {
5328 return this._latlngs;
5331 setLatLngs: function (latlngs) {
5332 this._latlngs = this._convertLatLngs(latlngs);
5333 return this.redraw();
5336 addLatLng: function (latlng) {
5337 this._latlngs.push(L.latLng(latlng));
5338 return this.redraw();
5341 spliceLatLngs: function () { // (Number index, Number howMany)
5342 var removed = [].splice.apply(this._latlngs, arguments);
5343 this._convertLatLngs(this._latlngs, true);
5348 closestLayerPoint: function (p) {
5349 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
5351 for (var j = 0, jLen = parts.length; j < jLen; j++) {
5352 var points = parts[j];
5353 for (var i = 1, len = points.length; i < len; i++) {
5356 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
5357 if (sqDist < minDistance) {
5358 minDistance = sqDist;
5359 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
5364 minPoint.distance = Math.sqrt(minDistance);
5369 getBounds: function () {
5370 return new L.LatLngBounds(this.getLatLngs());
5373 _convertLatLngs: function (latlngs, overwrite) {
5374 var i, len, target = overwrite ? latlngs : [];
5376 for (i = 0, len = latlngs.length; i < len; i++) {
5377 if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
5380 target[i] = L.latLng(latlngs[i]);
5385 _initEvents: function () {
5386 L.Path.prototype._initEvents.call(this);
5389 _getPathPartStr: function (points) {
5390 var round = L.Path.VML;
5392 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
5397 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
5402 _clipPoints: function () {
5403 var points = this._originalPoints,
5404 len = points.length,
5407 if (this.options.noClip) {
5408 this._parts = [points];
5414 var parts = this._parts,
5415 vp = this._map._pathViewport,
5418 for (i = 0, k = 0; i < len - 1; i++) {
5419 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
5424 parts[k] = parts[k] || [];
5425 parts[k].push(segment[0]);
5427 // if segment goes out of screen, or it's the last one, it's the end of the line part
5428 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
5429 parts[k].push(segment[1]);
5435 // simplify each clipped part of the polyline
5436 _simplifyPoints: function () {
5437 var parts = this._parts,
5440 for (var i = 0, len = parts.length; i < len; i++) {
5441 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
5445 _updatePath: function () {
5446 if (!this._map) { return; }
5449 this._simplifyPoints();
5451 L.Path.prototype._updatePath.call(this);
5455 L.polyline = function (latlngs, options) {
5456 return new L.Polyline(latlngs, options);
5461 * L.PolyUtil contains utility functions for polygons (clipping, etc.).
5464 /*jshint bitwise:false */ // allow bitwise operations here
5469 * Sutherland-Hodgeman polygon clipping algorithm.
5470 * Used to avoid rendering parts of a polygon that are not currently visible.
5472 L.PolyUtil.clipPolygon = function (points, bounds) {
5474 edges = [1, 4, 2, 8],
5480 for (i = 0, len = points.length; i < len; i++) {
5481 points[i]._code = lu._getBitCode(points[i], bounds);
5484 // for each edge (left, bottom, right, top)
5485 for (k = 0; k < 4; k++) {
5489 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5493 // if a is inside the clip window
5494 if (!(a._code & edge)) {
5495 // if b is outside the clip window (a->b goes out of screen)
5496 if (b._code & edge) {
5497 p = lu._getEdgeIntersection(b, a, edge, bounds);
5498 p._code = lu._getBitCode(p, bounds);
5499 clippedPoints.push(p);
5501 clippedPoints.push(a);
5503 // else if b is inside the clip window (a->b enters the screen)
5504 } else if (!(b._code & edge)) {
5505 p = lu._getEdgeIntersection(b, a, edge, bounds);
5506 p._code = lu._getBitCode(p, bounds);
5507 clippedPoints.push(p);
5510 points = clippedPoints;
5518 * L.Polygon is used to display polygons on a map.
5521 L.Polygon = L.Polyline.extend({
5526 initialize: function (latlngs, options) {
5529 L.Polyline.prototype.initialize.call(this, latlngs, options);
5531 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5532 this._latlngs = this._convertLatLngs(latlngs[0]);
5533 this._holes = latlngs.slice(1);
5535 for (i = 0, len = this._holes.length; i < len; i++) {
5536 hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
5537 if (hole[0].equals(hole[hole.length - 1])) {
5543 // filter out last point if its equal to the first one
5544 latlngs = this._latlngs;
5546 if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
5551 projectLatlngs: function () {
5552 L.Polyline.prototype.projectLatlngs.call(this);
5554 // project polygon holes points
5555 // TODO move this logic to Polyline to get rid of duplication
5556 this._holePoints = [];
5558 if (!this._holes) { return; }
5560 var i, j, len, len2;
5562 for (i = 0, len = this._holes.length; i < len; i++) {
5563 this._holePoints[i] = [];
5565 for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5566 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5571 _clipPoints: function () {
5572 var points = this._originalPoints,
5575 this._parts = [points].concat(this._holePoints);
5577 if (this.options.noClip) { return; }
5579 for (var i = 0, len = this._parts.length; i < len; i++) {
5580 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5581 if (clipped.length) {
5582 newParts.push(clipped);
5586 this._parts = newParts;
5589 _getPathPartStr: function (points) {
5590 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5591 return str + (L.Browser.svg ? 'z' : 'x');
5595 L.polygon = function (latlngs, options) {
5596 return new L.Polygon(latlngs, options);
5601 * Contains L.MultiPolyline and L.MultiPolygon layers.
5605 function createMulti(Klass) {
5607 return L.FeatureGroup.extend({
5609 initialize: function (latlngs, options) {
5611 this._options = options;
5612 this.setLatLngs(latlngs);
5615 setLatLngs: function (latlngs) {
5617 len = latlngs.length;
5619 this.eachLayer(function (layer) {
5621 layer.setLatLngs(latlngs[i++]);
5623 this.removeLayer(layer);
5628 this.addLayer(new Klass(latlngs[i++], this._options));
5634 getLatLngs: function () {
5637 this.eachLayer(function (layer) {
5638 latlngs.push(layer.getLatLngs());
5646 L.MultiPolyline = createMulti(L.Polyline);
5647 L.MultiPolygon = createMulti(L.Polygon);
5649 L.multiPolyline = function (latlngs, options) {
5650 return new L.MultiPolyline(latlngs, options);
5653 L.multiPolygon = function (latlngs, options) {
5654 return new L.MultiPolygon(latlngs, options);
5660 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5663 L.Rectangle = L.Polygon.extend({
5664 initialize: function (latLngBounds, options) {
5665 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5668 setBounds: function (latLngBounds) {
5669 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5672 _boundsToLatLngs: function (latLngBounds) {
5673 latLngBounds = L.latLngBounds(latLngBounds);
5675 latLngBounds.getSouthWest(),
5676 latLngBounds.getNorthWest(),
5677 latLngBounds.getNorthEast(),
5678 latLngBounds.getSouthEast()
5683 L.rectangle = function (latLngBounds, options) {
5684 return new L.Rectangle(latLngBounds, options);
5689 * L.Circle is a circle overlay (with a certain radius in meters).
5692 L.Circle = L.Path.extend({
5693 initialize: function (latlng, radius, options) {
5694 L.Path.prototype.initialize.call(this, options);
5696 this._latlng = L.latLng(latlng);
5697 this._mRadius = radius;
5704 setLatLng: function (latlng) {
5705 this._latlng = L.latLng(latlng);
5706 return this.redraw();
5709 setRadius: function (radius) {
5710 this._mRadius = radius;
5711 return this.redraw();
5714 projectLatlngs: function () {
5715 var lngRadius = this._getLngRadius(),
5716 latlng = this._latlng,
5717 pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
5719 this._point = this._map.latLngToLayerPoint(latlng);
5720 this._radius = Math.max(this._point.x - pointLeft.x, 1);
5723 getBounds: function () {
5724 var lngRadius = this._getLngRadius(),
5725 latRadius = (this._mRadius / 40075017) * 360,
5726 latlng = this._latlng;
5728 return new L.LatLngBounds(
5729 [latlng.lat - latRadius, latlng.lng - lngRadius],
5730 [latlng.lat + latRadius, latlng.lng + lngRadius]);
5733 getLatLng: function () {
5734 return this._latlng;
5737 getPathString: function () {
5738 var p = this._point,
5741 if (this._checkIfEmpty()) {
5745 if (L.Browser.svg) {
5746 return 'M' + p.x + ',' + (p.y - r) +
5747 'A' + r + ',' + r + ',0,1,1,' +
5748 (p.x - 0.1) + ',' + (p.y - r) + ' z';
5752 return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
5756 getRadius: function () {
5757 return this._mRadius;
5760 // TODO Earth hardcoded, move into projection code!
5762 _getLatRadius: function () {
5763 return (this._mRadius / 40075017) * 360;
5766 _getLngRadius: function () {
5767 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5770 _checkIfEmpty: function () {
5774 var vp = this._map._pathViewport,
5778 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5779 p.x + r < vp.min.x || p.y + r < vp.min.y;
5783 L.circle = function (latlng, radius, options) {
5784 return new L.Circle(latlng, radius, options);
5789 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5792 L.CircleMarker = L.Circle.extend({
5798 initialize: function (latlng, options) {
5799 L.Circle.prototype.initialize.call(this, latlng, null, options);
5800 this._radius = this.options.radius;
5803 projectLatlngs: function () {
5804 this._point = this._map.latLngToLayerPoint(this._latlng);
5807 _updateStyle : function () {
5808 L.Circle.prototype._updateStyle.call(this);
5809 this.setRadius(this.options.radius);
5812 setRadius: function (radius) {
5813 this.options.radius = this._radius = radius;
5814 return this.redraw();
5818 L.circleMarker = function (latlng, options) {
5819 return new L.CircleMarker(latlng, options);
5824 * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
5827 L.Polyline.include(!L.Path.CANVAS ? {} : {
5828 _containsPoint: function (p, closed) {
5829 var i, j, k, len, len2, dist, part,
5830 w = this.options.weight / 2;
5832 if (L.Browser.touch) {
5833 w += 10; // polyline click tolerance on touch devices
5836 for (i = 0, len = this._parts.length; i < len; i++) {
5837 part = this._parts[i];
5838 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5839 if (!closed && (j === 0)) {
5843 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5856 * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
5859 L.Polygon.include(!L.Path.CANVAS ? {} : {
5860 _containsPoint: function (p) {
5866 // TODO optimization: check if within bounds first
5868 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5869 // click on polygon border
5873 // ray casting algorithm for detecting if point is in polygon
5875 for (i = 0, len = this._parts.length; i < len; i++) {
5876 part = this._parts[i];
5878 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5882 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5883 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5895 * Extends L.Circle with Canvas-specific code.
5898 L.Circle.include(!L.Path.CANVAS ? {} : {
5899 _drawPath: function () {
5900 var p = this._point;
5901 this._ctx.beginPath();
5902 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5905 _containsPoint: function (p) {
5906 var center = this._point,
5907 w2 = this.options.stroke ? this.options.weight / 2 : 0;
5909 return (p.distanceTo(center) <= this._radius + w2);
5915 * CircleMarker canvas specific drawing parts.
5918 L.CircleMarker.include(!L.Path.CANVAS ? {} : {
5919 _updateStyle: function () {
5920 L.Path.prototype._updateStyle.call(this);
5926 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
5929 L.GeoJSON = L.FeatureGroup.extend({
5931 initialize: function (geojson, options) {
5932 L.setOptions(this, options);
5937 this.addData(geojson);
5941 addData: function (geojson) {
5942 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
5946 for (i = 0, len = features.length; i < len; i++) {
5947 // Only add this if geometry or geometries are set and not null
5948 feature = features[i];
5949 if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
5950 this.addData(features[i]);
5956 var options = this.options;
5958 if (options.filter && !options.filter(geojson)) { return; }
5960 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng);
5961 layer.feature = L.GeoJSON.asFeature(geojson);
5963 layer.defaultOptions = layer.options;
5964 this.resetStyle(layer);
5966 if (options.onEachFeature) {
5967 options.onEachFeature(geojson, layer);
5970 return this.addLayer(layer);
5973 resetStyle: function (layer) {
5974 var style = this.options.style;
5976 // reset any custom styles
5977 L.Util.extend(layer.options, layer.defaultOptions);
5979 this._setLayerStyle(layer, style);
5983 setStyle: function (style) {
5984 this.eachLayer(function (layer) {
5985 this._setLayerStyle(layer, style);
5989 _setLayerStyle: function (layer, style) {
5990 if (typeof style === 'function') {
5991 style = style(layer.feature);
5993 if (layer.setStyle) {
5994 layer.setStyle(style);
5999 L.extend(L.GeoJSON, {
6000 geometryToLayer: function (geojson, pointToLayer, coordsToLatLng) {
6001 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
6002 coords = geometry.coordinates,
6004 latlng, latlngs, i, len, layer;
6006 coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
6008 switch (geometry.type) {
6010 latlng = coordsToLatLng(coords);
6011 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6014 for (i = 0, len = coords.length; i < len; i++) {
6015 latlng = coordsToLatLng(coords[i]);
6016 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6019 return new L.FeatureGroup(layers);
6022 latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
6023 return new L.Polyline(latlngs);
6026 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6027 return new L.Polygon(latlngs);
6029 case 'MultiLineString':
6030 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6031 return new L.MultiPolyline(latlngs);
6033 case 'MultiPolygon':
6034 latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
6035 return new L.MultiPolygon(latlngs);
6037 case 'GeometryCollection':
6038 for (i = 0, len = geometry.geometries.length; i < len; i++) {
6040 layer = this.geometryToLayer({
6041 geometry: geometry.geometries[i],
6043 properties: geojson.properties
6044 }, pointToLayer, coordsToLatLng);
6048 return new L.FeatureGroup(layers);
6051 throw new Error('Invalid GeoJSON object.');
6055 coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
6056 return new L.LatLng(coords[1], coords[0]);
6059 coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
6063 for (i = 0, len = coords.length; i < len; i++) {
6064 latlng = levelsDeep ?
6065 this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
6066 (coordsToLatLng || this.coordsToLatLng)(coords[i]);
6068 latlngs.push(latlng);
6074 latLngToCoords: function (latLng) {
6075 return [latLng.lng, latLng.lat];
6078 latLngsToCoords: function (latLngs) {
6081 for (var i = 0, len = latLngs.length; i < len; i++) {
6082 coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
6088 getFeature: function (layer, newGeometry) {
6089 return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
6092 asFeature: function (geoJSON) {
6093 if (geoJSON.type === 'Feature') {
6105 var PointToGeoJSON = {
6106 toGeoJSON: function () {
6107 return L.GeoJSON.getFeature(this, {
6109 coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
6114 L.Marker.include(PointToGeoJSON);
6115 L.Circle.include(PointToGeoJSON);
6116 L.CircleMarker.include(PointToGeoJSON);
6118 L.Polyline.include({
6119 toGeoJSON: function () {
6120 return L.GeoJSON.getFeature(this, {
6122 coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
6128 toGeoJSON: function () {
6129 var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
6132 coords[0].push(coords[0][0]);
6135 for (i = 0, len = this._holes.length; i < len; i++) {
6136 hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
6142 return L.GeoJSON.getFeature(this, {
6150 function includeMulti(Klass, type) {
6152 toGeoJSON: function () {
6155 this.eachLayer(function (layer) {
6156 coords.push(layer.toGeoJSON().geometry.coordinates);
6159 return L.GeoJSON.getFeature(this, {
6167 includeMulti(L.MultiPolyline, 'MultiLineString');
6168 includeMulti(L.MultiPolygon, 'MultiPolygon');
6171 L.LayerGroup.include({
6172 toGeoJSON: function () {
6175 this.eachLayer(function (layer) {
6176 if (layer.toGeoJSON) {
6177 features.push(L.GeoJSON.asFeature(layer.toGeoJSON()));
6182 type: 'FeatureCollection',
6188 L.geoJson = function (geojson, options) {
6189 return new L.GeoJSON(geojson, options);
6194 * L.DomEvent contains functions for working with DOM events.
6198 /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
6199 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
6201 var id = L.stamp(fn),
6202 key = '_leaflet_' + type + id,
6203 handler, originalHandler, newType;
6205 if (obj[key]) { return this; }
6207 handler = function (e) {
6208 return fn.call(context || obj, e || L.DomEvent._getEvent());
6211 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6212 return this.addMsTouchListener(obj, type, handler, id);
6214 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
6215 this.addDoubleTapListener(obj, handler, id);
6218 if ('addEventListener' in obj) {
6220 if (type === 'mousewheel') {
6221 obj.addEventListener('DOMMouseScroll', handler, false);
6222 obj.addEventListener(type, handler, false);
6224 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6226 originalHandler = handler;
6227 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
6229 handler = function (e) {
6230 if (!L.DomEvent._checkMouse(obj, e)) { return; }
6231 return originalHandler(e);
6234 obj.addEventListener(newType, handler, false);
6236 } else if (type === 'click' && L.Browser.android) {
6237 originalHandler = handler;
6238 handler = function (e) {
6239 return L.DomEvent._filterClick(e, originalHandler);
6242 obj.addEventListener(type, handler, false);
6244 obj.addEventListener(type, handler, false);
6247 } else if ('attachEvent' in obj) {
6248 obj.attachEvent('on' + type, handler);
6256 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
6258 var id = L.stamp(fn),
6259 key = '_leaflet_' + type + id,
6262 if (!handler) { return this; }
6264 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6265 this.removeMsTouchListener(obj, type, id);
6266 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
6267 this.removeDoubleTapListener(obj, id);
6269 } else if ('removeEventListener' in obj) {
6271 if (type === 'mousewheel') {
6272 obj.removeEventListener('DOMMouseScroll', handler, false);
6273 obj.removeEventListener(type, handler, false);
6275 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6276 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
6278 obj.removeEventListener(type, handler, false);
6280 } else if ('detachEvent' in obj) {
6281 obj.detachEvent('on' + type, handler);
6289 stopPropagation: function (e) {
6291 if (e.stopPropagation) {
6292 e.stopPropagation();
6294 e.cancelBubble = true;
6299 disableClickPropagation: function (el) {
6300 var stop = L.DomEvent.stopPropagation;
6302 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6303 L.DomEvent.addListener(el, L.Draggable.START[i], stop);
6307 .addListener(el, 'click', L.DomEvent._fakeStop)
6308 .addListener(el, 'dblclick', stop);
6311 preventDefault: function (e) {
6313 if (e.preventDefault) {
6316 e.returnValue = false;
6321 stop: function (e) {
6322 return L.DomEvent.preventDefault(e).stopPropagation(e);
6325 getMousePosition: function (e, container) {
6327 var ie7 = L.Browser.ie7,
6328 body = document.body,
6329 docEl = document.documentElement,
6330 x = e.pageX ? e.pageX - body.scrollLeft - docEl.scrollLeft: e.clientX,
6331 y = e.pageY ? e.pageY - body.scrollTop - docEl.scrollTop: e.clientY,
6332 pos = new L.Point(x, y),
6333 rect = container.getBoundingClientRect(),
6334 left = rect.left - container.clientLeft,
6335 top = rect.top - container.clientTop;
6337 // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
6338 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
6339 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
6340 left += container.scrollWidth - container.clientWidth;
6342 // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
6343 // need to add it back in if it is visible; scrollbar is on the left as we are RTL
6344 if (ie7 && L.DomUtil.getStyle(container, 'overflow-y') !== 'hidden' &&
6345 L.DomUtil.getStyle(container, 'overflow') !== 'hidden') {
6350 return pos._subtract(new L.Point(left, top));
6353 getWheelDelta: function (e) {
6358 delta = e.wheelDelta / 120;
6361 delta = -e.detail / 3;
6368 _fakeStop: function (e) {
6369 // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
6370 L.DomEvent._skipEvents[e.type] = true;
6373 _skipped: function (e) {
6374 var skipped = this._skipEvents[e.type];
6375 // reset when checking, as it's only used in map container and propagates outside of the map
6376 this._skipEvents[e.type] = false;
6380 // check if element really left/entered the event target (for mouseenter/mouseleave)
6381 _checkMouse: function (el, e) {
6383 var related = e.relatedTarget;
6385 if (!related) { return true; }
6388 while (related && (related !== el)) {
6389 related = related.parentNode;
6394 return (related !== el);
6397 _getEvent: function () { // evil magic for IE
6398 /*jshint noarg:false */
6399 var e = window.event;
6401 var caller = arguments.callee.caller;
6403 e = caller['arguments'][0];
6404 if (e && window.Event === e.constructor) {
6407 caller = caller.caller;
6413 // this is a horrible workaround for a bug in Android where a single touch triggers two click events
6414 _filterClick: function (e, handler) {
6415 var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
6416 elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
6418 // are they closer together than 1000ms yet more than 100ms?
6419 // Android typically triggers them ~300ms apart while multiple listeners
6420 // on the same event should be triggered far faster;
6421 // or check if click is simulated on the element, and if it is, reject any non-simulated events
6423 if ((elapsed && elapsed > 100 && elapsed < 1000) || (e.target._simulatedClick && !e._simulated)) {
6427 L.DomEvent._lastClick = timeStamp;
6433 L.DomEvent.on = L.DomEvent.addListener;
6434 L.DomEvent.off = L.DomEvent.removeListener;
6438 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
6441 L.Draggable = L.Class.extend({
6442 includes: L.Mixin.Events,
6445 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
6447 mousedown: 'mouseup',
6448 touchstart: 'touchend',
6449 MSPointerDown: 'touchend'
6452 mousedown: 'mousemove',
6453 touchstart: 'touchmove',
6454 MSPointerDown: 'touchmove'
6458 initialize: function (element, dragStartTarget) {
6459 this._element = element;
6460 this._dragStartTarget = dragStartTarget || element;
6463 enable: function () {
6464 if (this._enabled) { return; }
6466 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6467 L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6470 this._enabled = true;
6473 disable: function () {
6474 if (!this._enabled) { return; }
6476 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6477 L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6480 this._enabled = false;
6481 this._moved = false;
6484 _onDown: function (e) {
6485 if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
6488 .stopPropagation(e);
6490 if (L.Draggable._disabled) { return; }
6492 L.DomUtil.disableImageDrag();
6493 L.DomUtil.disableTextSelection();
6495 var first = e.touches ? e.touches[0] : e,
6498 // if touching a link, highlight it
6499 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
6500 L.DomUtil.addClass(el, 'leaflet-active');
6503 this._moved = false;
6505 if (this._moving) { return; }
6507 this._startPoint = new L.Point(first.clientX, first.clientY);
6508 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
6511 .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
6512 .on(document, L.Draggable.END[e.type], this._onUp, this);
6515 _onMove: function (e) {
6516 if (e.touches && e.touches.length > 1) { return; }
6518 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
6519 newPoint = new L.Point(first.clientX, first.clientY),
6520 offset = newPoint.subtract(this._startPoint);
6522 if (!offset.x && !offset.y) { return; }
6524 L.DomEvent.preventDefault(e);
6527 this.fire('dragstart');
6530 this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
6532 if (!L.Browser.touch) {
6533 L.DomUtil.addClass(document.body, 'leaflet-dragging');
6537 this._newPos = this._startPos.add(offset);
6538 this._moving = true;
6540 L.Util.cancelAnimFrame(this._animRequest);
6541 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
6544 _updatePosition: function () {
6545 this.fire('predrag');
6546 L.DomUtil.setPosition(this._element, this._newPos);
6550 _onUp: function () {
6551 if (!L.Browser.touch) {
6552 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
6555 for (var i in L.Draggable.MOVE) {
6557 .off(document, L.Draggable.MOVE[i], this._onMove)
6558 .off(document, L.Draggable.END[i], this._onUp);
6561 L.DomUtil.enableImageDrag();
6562 L.DomUtil.enableTextSelection();
6565 // ensure drag is not fired after dragend
6566 L.Util.cancelAnimFrame(this._animRequest);
6568 this.fire('dragend');
6571 this._moving = false;
6577 L.Handler is a base class for handler classes that are used internally to inject
6578 interaction features like dragging to classes like Map and Marker.
6581 L.Handler = L.Class.extend({
6582 initialize: function (map) {
6586 enable: function () {
6587 if (this._enabled) { return; }
6589 this._enabled = true;
6593 disable: function () {
6594 if (!this._enabled) { return; }
6596 this._enabled = false;
6600 enabled: function () {
6601 return !!this._enabled;
6607 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
6610 L.Map.mergeOptions({
6613 inertia: !L.Browser.android23,
6614 inertiaDeceleration: 3400, // px/s^2
6615 inertiaMaxSpeed: Infinity, // px/s
6616 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
6617 easeLinearity: 0.25,
6619 // TODO refactor, move to CRS
6620 worldCopyJump: false
6623 L.Map.Drag = L.Handler.extend({
6624 addHooks: function () {
6625 if (!this._draggable) {
6626 var map = this._map;
6628 this._draggable = new L.Draggable(map._mapPane, map._container);
6630 this._draggable.on({
6631 'dragstart': this._onDragStart,
6632 'drag': this._onDrag,
6633 'dragend': this._onDragEnd
6636 if (map.options.worldCopyJump) {
6637 this._draggable.on('predrag', this._onPreDrag, this);
6638 map.on('viewreset', this._onViewReset, this);
6640 this._onViewReset();
6643 this._draggable.enable();
6646 removeHooks: function () {
6647 this._draggable.disable();
6650 moved: function () {
6651 return this._draggable && this._draggable._moved;
6654 _onDragStart: function () {
6655 var map = this._map;
6658 map._panAnim.stop();
6665 if (map.options.inertia) {
6666 this._positions = [];
6671 _onDrag: function () {
6672 if (this._map.options.inertia) {
6673 var time = this._lastTime = +new Date(),
6674 pos = this._lastPos = this._draggable._newPos;
6676 this._positions.push(pos);
6677 this._times.push(time);
6679 if (time - this._times[0] > 200) {
6680 this._positions.shift();
6681 this._times.shift();
6690 _onViewReset: function () {
6691 // TODO fix hardcoded Earth values
6692 var pxCenter = this._map.getSize()._divideBy(2),
6693 pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
6695 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6696 this._worldWidth = this._map.project([0, 180]).x;
6699 _onPreDrag: function () {
6700 // TODO refactor to be able to adjust map pane position after zoom
6701 var worldWidth = this._worldWidth,
6702 halfWidth = Math.round(worldWidth / 2),
6703 dx = this._initialWorldOffset,
6704 x = this._draggable._newPos.x,
6705 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6706 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6707 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6709 this._draggable._newPos.x = newX;
6712 _onDragEnd: function () {
6713 var map = this._map,
6714 options = map.options,
6715 delay = +new Date() - this._lastTime,
6717 noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6719 map.fire('dragend');
6722 map.fire('moveend');
6726 var direction = this._lastPos.subtract(this._positions[0]),
6727 duration = (this._lastTime + delay - this._times[0]) / 1000,
6728 ease = options.easeLinearity,
6730 speedVector = direction.multiplyBy(ease / duration),
6731 speed = speedVector.distanceTo([0, 0]),
6733 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6734 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6736 decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6737 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6739 if (!offset.x || !offset.y) {
6740 map.fire('moveend');
6743 L.Util.requestAnimFrame(function () {
6745 duration: decelerationDuration,
6746 easeLinearity: ease,
6755 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6759 * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6762 L.Map.mergeOptions({
6763 doubleClickZoom: true
6766 L.Map.DoubleClickZoom = L.Handler.extend({
6767 addHooks: function () {
6768 this._map.on('dblclick', this._onDoubleClick, this);
6771 removeHooks: function () {
6772 this._map.off('dblclick', this._onDoubleClick, this);
6775 _onDoubleClick: function (e) {
6776 var map = this._map,
6777 zoom = map.getZoom() + 1;
6779 if (map.options.doubleClickZoom === 'center') {
6782 map.setZoomAround(e.containerPoint, zoom);
6787 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
6791 * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
6794 L.Map.mergeOptions({
6795 scrollWheelZoom: true
6798 L.Map.ScrollWheelZoom = L.Handler.extend({
6799 addHooks: function () {
6800 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
6801 L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6805 removeHooks: function () {
6806 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
6807 L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6810 _onWheelScroll: function (e) {
6811 var delta = L.DomEvent.getWheelDelta(e);
6813 this._delta += delta;
6814 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
6816 if (!this._startTime) {
6817 this._startTime = +new Date();
6820 var left = Math.max(40 - (+new Date() - this._startTime), 0);
6822 clearTimeout(this._timer);
6823 this._timer = setTimeout(L.bind(this._performZoom, this), left);
6825 L.DomEvent.preventDefault(e);
6826 L.DomEvent.stopPropagation(e);
6829 _performZoom: function () {
6830 var map = this._map,
6831 delta = this._delta,
6832 zoom = map.getZoom();
6834 delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
6835 delta = Math.max(Math.min(delta, 4), -4);
6836 delta = map._limitZoom(zoom + delta) - zoom;
6839 this._startTime = null;
6841 if (!delta) { return; }
6843 if (map.options.scrollWheelZoom === 'center') {
6844 map.setZoom(zoom + delta);
6846 map.setZoomAround(this._lastMousePos, zoom + delta);
6851 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
6855 * Extends the event handling code with double tap support for mobile browsers.
6858 L.extend(L.DomEvent, {
6860 _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
6861 _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
6863 // inspired by Zepto touch code by Thomas Fuchs
6864 addDoubleTapListener: function (obj, handler, id) {
6870 touchstart = this._touchstart,
6871 touchend = this._touchend,
6872 trackedTouches = [];
6874 function onTouchStart(e) {
6877 if (L.Browser.msTouch) {
6878 trackedTouches.push(e.pointerId);
6879 count = trackedTouches.length;
6881 count = e.touches.length;
6887 var now = Date.now(),
6888 delta = now - (last || now);
6890 touch = e.touches ? e.touches[0] : e;
6891 doubleTap = (delta > 0 && delta <= delay);
6895 function onTouchEnd(e) {
6896 if (L.Browser.msTouch) {
6897 var idx = trackedTouches.indexOf(e.pointerId);
6901 trackedTouches.splice(idx, 1);
6905 if (L.Browser.msTouch) {
6906 // work around .type being readonly with MSPointer* events
6910 // jshint forin:false
6911 for (var i in touch) {
6913 if (typeof prop === 'function') {
6914 newTouch[i] = prop.bind(touch);
6921 touch.type = 'dblclick';
6926 obj[pre + touchstart + id] = onTouchStart;
6927 obj[pre + touchend + id] = onTouchEnd;
6929 // on msTouch we need to listen on the document, otherwise a drag starting on the map and moving off screen
6930 // will not come through to us, so we will lose track of how many touches are ongoing
6931 var endElement = L.Browser.msTouch ? document.documentElement : obj;
6933 obj.addEventListener(touchstart, onTouchStart, false);
6934 endElement.addEventListener(touchend, onTouchEnd, false);
6936 if (L.Browser.msTouch) {
6937 endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
6943 removeDoubleTapListener: function (obj, id) {
6944 var pre = '_leaflet_';
6946 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
6947 (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(
6948 this._touchend, obj[pre + this._touchend + id], false);
6950 if (L.Browser.msTouch) {
6951 document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
6960 * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
6963 L.extend(L.DomEvent, {
6966 _msDocumentListener: false,
6968 // Provides a touch events wrapper for msPointer events.
6969 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
6971 addMsTouchListener: function (obj, type, handler, id) {
6975 return this.addMsTouchListenerStart(obj, type, handler, id);
6977 return this.addMsTouchListenerEnd(obj, type, handler, id);
6979 return this.addMsTouchListenerMove(obj, type, handler, id);
6981 throw 'Unknown touch event type';
6985 addMsTouchListenerStart: function (obj, type, handler, id) {
6986 var pre = '_leaflet_',
6987 touches = this._msTouches;
6989 var cb = function (e) {
6991 var alreadyInArray = false;
6992 for (var i = 0; i < touches.length; i++) {
6993 if (touches[i].pointerId === e.pointerId) {
6994 alreadyInArray = true;
6998 if (!alreadyInArray) {
7002 e.touches = touches.slice();
7003 e.changedTouches = [e];
7008 obj[pre + 'touchstart' + id] = cb;
7009 obj.addEventListener('MSPointerDown', cb, false);
7011 // need to also listen for end events to keep the _msTouches list accurate
7012 // this needs to be on the body and never go away
7013 if (!this._msDocumentListener) {
7014 var internalCb = function (e) {
7015 for (var i = 0; i < touches.length; i++) {
7016 if (touches[i].pointerId === e.pointerId) {
7017 touches.splice(i, 1);
7022 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
7023 document.documentElement.addEventListener('MSPointerUp', internalCb, false);
7024 document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
7026 this._msDocumentListener = true;
7032 addMsTouchListenerMove: function (obj, type, handler, id) {
7033 var pre = '_leaflet_',
7034 touches = this._msTouches;
7038 // don't fire touch moves when mouse isn't down
7039 if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) { return; }
7041 for (var i = 0; i < touches.length; i++) {
7042 if (touches[i].pointerId === e.pointerId) {
7048 e.touches = touches.slice();
7049 e.changedTouches = [e];
7054 obj[pre + 'touchmove' + id] = cb;
7055 obj.addEventListener('MSPointerMove', cb, false);
7060 addMsTouchListenerEnd: function (obj, type, handler, id) {
7061 var pre = '_leaflet_',
7062 touches = this._msTouches;
7064 var cb = function (e) {
7065 for (var i = 0; i < touches.length; i++) {
7066 if (touches[i].pointerId === e.pointerId) {
7067 touches.splice(i, 1);
7072 e.touches = touches.slice();
7073 e.changedTouches = [e];
7078 obj[pre + 'touchend' + id] = cb;
7079 obj.addEventListener('MSPointerUp', cb, false);
7080 obj.addEventListener('MSPointerCancel', cb, false);
7085 removeMsTouchListener: function (obj, type, id) {
7086 var pre = '_leaflet_',
7087 cb = obj[pre + type + id];
7091 obj.removeEventListener('MSPointerDown', cb, false);
7094 obj.removeEventListener('MSPointerMove', cb, false);
7097 obj.removeEventListener('MSPointerUp', cb, false);
7098 obj.removeEventListener('MSPointerCancel', cb, false);
7108 * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
7111 L.Map.mergeOptions({
7112 touchZoom: L.Browser.touch && !L.Browser.android23
7115 L.Map.TouchZoom = L.Handler.extend({
7116 addHooks: function () {
7117 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
7120 removeHooks: function () {
7121 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
7124 _onTouchStart: function (e) {
7125 var map = this._map;
7127 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
7129 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7130 p2 = map.mouseEventToLayerPoint(e.touches[1]),
7131 viewCenter = map._getCenterLayerPoint();
7133 this._startCenter = p1.add(p2)._divideBy(2);
7134 this._startDist = p1.distanceTo(p2);
7136 this._moved = false;
7137 this._zooming = true;
7139 this._centerOffset = viewCenter.subtract(this._startCenter);
7142 map._panAnim.stop();
7146 .on(document, 'touchmove', this._onTouchMove, this)
7147 .on(document, 'touchend', this._onTouchEnd, this);
7149 L.DomEvent.preventDefault(e);
7152 _onTouchMove: function (e) {
7153 var map = this._map;
7155 if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
7157 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7158 p2 = map.mouseEventToLayerPoint(e.touches[1]);
7160 this._scale = p1.distanceTo(p2) / this._startDist;
7161 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
7163 if (this._scale === 1) { return; }
7166 L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
7175 L.Util.cancelAnimFrame(this._animRequest);
7176 this._animRequest = L.Util.requestAnimFrame(
7177 this._updateOnMove, this, true, this._map._container);
7179 L.DomEvent.preventDefault(e);
7182 _updateOnMove: function () {
7183 var map = this._map,
7184 origin = this._getScaleOrigin(),
7185 center = map.layerPointToLatLng(origin),
7186 zoom = map.getScaleZoom(this._scale);
7188 map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta);
7191 _onTouchEnd: function () {
7192 if (!this._moved || !this._zooming) {
7193 this._zooming = false;
7197 var map = this._map;
7199 this._zooming = false;
7200 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
7201 L.Util.cancelAnimFrame(this._animRequest);
7204 .off(document, 'touchmove', this._onTouchMove)
7205 .off(document, 'touchend', this._onTouchEnd);
7207 var origin = this._getScaleOrigin(),
7208 center = map.layerPointToLatLng(origin),
7210 oldZoom = map.getZoom(),
7211 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
7212 roundZoomDelta = (floatZoomDelta > 0 ?
7213 Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
7215 zoom = map._limitZoom(oldZoom + roundZoomDelta),
7216 scale = map.getZoomScale(zoom) / this._scale;
7218 map._animateZoom(center, zoom, origin, scale);
7221 _getScaleOrigin: function () {
7222 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
7223 return this._startCenter.add(centerOffset);
7227 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
7231 * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
7234 L.Map.mergeOptions({
7239 L.Map.Tap = L.Handler.extend({
7240 addHooks: function () {
7241 L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
7244 removeHooks: function () {
7245 L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
7248 _onDown: function (e) {
7249 if (!e.touches) { return; }
7251 L.DomEvent.preventDefault(e);
7253 this._fireClick = true;
7255 // don't simulate click or track longpress if more than 1 touch
7256 if (e.touches.length > 1) {
7257 this._fireClick = false;
7258 clearTimeout(this._holdTimeout);
7262 var first = e.touches[0],
7265 this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
7267 // if touching a link, highlight it
7268 if (el.tagName.toLowerCase() === 'a') {
7269 L.DomUtil.addClass(el, 'leaflet-active');
7272 // simulate long hold but setting a timeout
7273 this._holdTimeout = setTimeout(L.bind(function () {
7274 if (this._isTapValid()) {
7275 this._fireClick = false;
7277 this._simulateEvent('contextmenu', first);
7282 .on(document, 'touchmove', this._onMove, this)
7283 .on(document, 'touchend', this._onUp, this);
7286 _onUp: function (e) {
7287 clearTimeout(this._holdTimeout);
7290 .off(document, 'touchmove', this._onMove, this)
7291 .off(document, 'touchend', this._onUp, this);
7293 if (this._fireClick && e && e.changedTouches) {
7295 var first = e.changedTouches[0],
7298 if (el.tagName.toLowerCase() === 'a') {
7299 L.DomUtil.removeClass(el, 'leaflet-active');
7302 // simulate click if the touch didn't move too much
7303 if (this._isTapValid()) {
7304 this._simulateEvent('click', first);
7309 _isTapValid: function () {
7310 return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
7313 _onMove: function (e) {
7314 var first = e.touches[0];
7315 this._newPos = new L.Point(first.clientX, first.clientY);
7318 _simulateEvent: function (type, e) {
7319 var simulatedEvent = document.createEvent('MouseEvents');
7321 simulatedEvent._simulated = true;
7322 e.target._simulatedClick = true;
7324 simulatedEvent.initMouseEvent(
7325 type, true, true, window, 1,
7326 e.screenX, e.screenY,
7327 e.clientX, e.clientY,
7328 false, false, false, false, 0, null);
7330 e.target.dispatchEvent(simulatedEvent);
7334 if (L.Browser.touch && !L.Browser.msTouch) {
7335 L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
7340 * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
7341 * (zoom to a selected bounding box), enabled by default.
7344 L.Map.mergeOptions({
7348 L.Map.BoxZoom = L.Handler.extend({
7349 initialize: function (map) {
7351 this._container = map._container;
7352 this._pane = map._panes.overlayPane;
7355 addHooks: function () {
7356 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
7359 removeHooks: function () {
7360 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
7363 _onMouseDown: function (e) {
7364 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
7366 L.DomUtil.disableTextSelection();
7367 L.DomUtil.disableImageDrag();
7369 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
7371 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
7372 L.DomUtil.setPosition(this._box, this._startLayerPoint);
7374 //TODO refactor: move cursor to styles
7375 this._container.style.cursor = 'crosshair';
7378 .on(document, 'mousemove', this._onMouseMove, this)
7379 .on(document, 'mouseup', this._onMouseUp, this)
7380 .on(document, 'keydown', this._onKeyDown, this);
7382 this._map.fire('boxzoomstart');
7385 _onMouseMove: function (e) {
7386 var startPoint = this._startLayerPoint,
7389 layerPoint = this._map.mouseEventToLayerPoint(e),
7390 offset = layerPoint.subtract(startPoint),
7392 newPos = new L.Point(
7393 Math.min(layerPoint.x, startPoint.x),
7394 Math.min(layerPoint.y, startPoint.y));
7396 L.DomUtil.setPosition(box, newPos);
7398 // TODO refactor: remove hardcoded 4 pixels
7399 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
7400 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
7403 _finish: function () {
7404 this._pane.removeChild(this._box);
7405 this._container.style.cursor = '';
7407 L.DomUtil.enableTextSelection();
7408 L.DomUtil.enableImageDrag();
7411 .off(document, 'mousemove', this._onMouseMove)
7412 .off(document, 'mouseup', this._onMouseUp)
7413 .off(document, 'keydown', this._onKeyDown);
7416 _onMouseUp: function (e) {
7420 var map = this._map,
7421 layerPoint = map.mouseEventToLayerPoint(e);
7423 if (this._startLayerPoint.equals(layerPoint)) { return; }
7425 var bounds = new L.LatLngBounds(
7426 map.layerPointToLatLng(this._startLayerPoint),
7427 map.layerPointToLatLng(layerPoint));
7429 map.fitBounds(bounds);
7431 map.fire('boxzoomend', {
7432 boxZoomBounds: bounds
7436 _onKeyDown: function (e) {
7437 if (e.keyCode === 27) {
7443 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
7447 * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
7450 L.Map.mergeOptions({
7452 keyboardPanOffset: 80,
7453 keyboardZoomOffset: 1
7456 L.Map.Keyboard = L.Handler.extend({
7463 zoomIn: [187, 107, 61],
7464 zoomOut: [189, 109, 173]
7467 initialize: function (map) {
7470 this._setPanOffset(map.options.keyboardPanOffset);
7471 this._setZoomOffset(map.options.keyboardZoomOffset);
7474 addHooks: function () {
7475 var container = this._map._container;
7477 // make the container focusable by tabbing
7478 if (container.tabIndex === -1) {
7479 container.tabIndex = '0';
7483 .on(container, 'focus', this._onFocus, this)
7484 .on(container, 'blur', this._onBlur, this)
7485 .on(container, 'mousedown', this._onMouseDown, this);
7488 .on('focus', this._addHooks, this)
7489 .on('blur', this._removeHooks, this);
7492 removeHooks: function () {
7493 this._removeHooks();
7495 var container = this._map._container;
7498 .off(container, 'focus', this._onFocus, this)
7499 .off(container, 'blur', this._onBlur, this)
7500 .off(container, 'mousedown', this._onMouseDown, this);
7503 .off('focus', this._addHooks, this)
7504 .off('blur', this._removeHooks, this);
7507 _onMouseDown: function () {
7508 if (this._focused) { return; }
7510 var body = document.body,
7511 docEl = document.documentElement,
7512 top = body.scrollTop || docEl.scrollTop,
7513 left = body.scrollTop || docEl.scrollLeft;
7515 this._map._container.focus();
7517 window.scrollTo(left, top);
7520 _onFocus: function () {
7521 this._focused = true;
7522 this._map.fire('focus');
7525 _onBlur: function () {
7526 this._focused = false;
7527 this._map.fire('blur');
7530 _setPanOffset: function (pan) {
7531 var keys = this._panKeys = {},
7532 codes = this.keyCodes,
7535 for (i = 0, len = codes.left.length; i < len; i++) {
7536 keys[codes.left[i]] = [-1 * pan, 0];
7538 for (i = 0, len = codes.right.length; i < len; i++) {
7539 keys[codes.right[i]] = [pan, 0];
7541 for (i = 0, len = codes.down.length; i < len; i++) {
7542 keys[codes.down[i]] = [0, pan];
7544 for (i = 0, len = codes.up.length; i < len; i++) {
7545 keys[codes.up[i]] = [0, -1 * pan];
7549 _setZoomOffset: function (zoom) {
7550 var keys = this._zoomKeys = {},
7551 codes = this.keyCodes,
7554 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
7555 keys[codes.zoomIn[i]] = zoom;
7557 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
7558 keys[codes.zoomOut[i]] = -zoom;
7562 _addHooks: function () {
7563 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
7566 _removeHooks: function () {
7567 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
7570 _onKeyDown: function (e) {
7571 var key = e.keyCode,
7574 if (key in this._panKeys) {
7576 if (map._panAnim && map._panAnim._inProgress) { return; }
7578 map.panBy(this._panKeys[key]);
7580 if (map.options.maxBounds) {
7581 map.panInsideBounds(map.options.maxBounds);
7584 } else if (key in this._zoomKeys) {
7585 map.setZoom(map.getZoom() + this._zoomKeys[key]);
7595 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
7599 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
7602 L.Handler.MarkerDrag = L.Handler.extend({
7603 initialize: function (marker) {
7604 this._marker = marker;
7607 addHooks: function () {
7608 var icon = this._marker._icon;
7609 if (!this._draggable) {
7610 this._draggable = new L.Draggable(icon, icon);
7614 .on('dragstart', this._onDragStart, this)
7615 .on('drag', this._onDrag, this)
7616 .on('dragend', this._onDragEnd, this);
7617 this._draggable.enable();
7620 removeHooks: function () {
7622 .off('dragstart', this._onDragStart, this)
7623 .off('drag', this._onDrag, this)
7624 .off('dragend', this._onDragEnd, this);
7626 this._draggable.disable();
7629 moved: function () {
7630 return this._draggable && this._draggable._moved;
7633 _onDragStart: function () {
7640 _onDrag: function () {
7641 var marker = this._marker,
7642 shadow = marker._shadow,
7643 iconPos = L.DomUtil.getPosition(marker._icon),
7644 latlng = marker._map.layerPointToLatLng(iconPos);
7646 // update shadow position
7648 L.DomUtil.setPosition(shadow, iconPos);
7651 marker._latlng = latlng;
7654 .fire('move', {latlng: latlng})
7658 _onDragEnd: function () {
7667 * L.Control is a base class for implementing map controls. Handles positioning.
7668 * All other controls extend from this class.
7671 L.Control = L.Class.extend({
7673 position: 'topright'
7676 initialize: function (options) {
7677 L.setOptions(this, options);
7680 getPosition: function () {
7681 return this.options.position;
7684 setPosition: function (position) {
7685 var map = this._map;
7688 map.removeControl(this);
7691 this.options.position = position;
7694 map.addControl(this);
7700 getContainer: function () {
7701 return this._container;
7704 addTo: function (map) {
7707 var container = this._container = this.onAdd(map),
7708 pos = this.getPosition(),
7709 corner = map._controlCorners[pos];
7711 L.DomUtil.addClass(container, 'leaflet-control');
7713 if (pos.indexOf('bottom') !== -1) {
7714 corner.insertBefore(container, corner.firstChild);
7716 corner.appendChild(container);
7722 removeFrom: function (map) {
7723 var pos = this.getPosition(),
7724 corner = map._controlCorners[pos];
7726 corner.removeChild(this._container);
7729 if (this.onRemove) {
7737 L.control = function (options) {
7738 return new L.Control(options);
7742 // adds control-related methods to L.Map
7745 addControl: function (control) {
7746 control.addTo(this);
7750 removeControl: function (control) {
7751 control.removeFrom(this);
7755 _initControlPos: function () {
7756 var corners = this._controlCorners = {},
7758 container = this._controlContainer =
7759 L.DomUtil.create('div', l + 'control-container', this._container);
7761 function createCorner(vSide, hSide) {
7762 var className = l + vSide + ' ' + l + hSide;
7764 corners[vSide + hSide] = L.DomUtil.create('div', className, container);
7767 createCorner('top', 'left');
7768 createCorner('top', 'right');
7769 createCorner('bottom', 'left');
7770 createCorner('bottom', 'right');
7773 _clearControlPos: function () {
7774 this._container.removeChild(this._controlContainer);
7780 * L.Control.Zoom is used for the default zoom buttons on the map.
7783 L.Control.Zoom = L.Control.extend({
7788 onAdd: function (map) {
7789 var zoomName = 'leaflet-control-zoom',
7790 container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
7794 this._zoomInButton = this._createButton(
7795 '+', 'Zoom in', zoomName + '-in', container, this._zoomIn, this);
7796 this._zoomOutButton = this._createButton(
7797 '-', 'Zoom out', zoomName + '-out', container, this._zoomOut, this);
7799 map.on('zoomend zoomlevelschange', this._updateDisabled, this);
7804 onRemove: function (map) {
7805 map.off('zoomend zoomlevelschange', this._updateDisabled, this);
7808 _zoomIn: function (e) {
7809 this._map.zoomIn(e.shiftKey ? 3 : 1);
7812 _zoomOut: function (e) {
7813 this._map.zoomOut(e.shiftKey ? 3 : 1);
7816 _createButton: function (html, title, className, container, fn, context) {
7817 var link = L.DomUtil.create('a', className, container);
7818 link.innerHTML = html;
7822 var stop = L.DomEvent.stopPropagation;
7825 .on(link, 'click', stop)
7826 .on(link, 'mousedown', stop)
7827 .on(link, 'dblclick', stop)
7828 .on(link, 'click', L.DomEvent.preventDefault)
7829 .on(link, 'click', fn, context);
7834 _updateDisabled: function () {
7835 var map = this._map,
7836 className = 'leaflet-disabled';
7838 L.DomUtil.removeClass(this._zoomInButton, className);
7839 L.DomUtil.removeClass(this._zoomOutButton, className);
7841 if (map._zoom === map.getMinZoom()) {
7842 L.DomUtil.addClass(this._zoomOutButton, className);
7844 if (map._zoom === map.getMaxZoom()) {
7845 L.DomUtil.addClass(this._zoomInButton, className);
7850 L.Map.mergeOptions({
7854 L.Map.addInitHook(function () {
7855 if (this.options.zoomControl) {
7856 this.zoomControl = new L.Control.Zoom();
7857 this.addControl(this.zoomControl);
7861 L.control.zoom = function (options) {
7862 return new L.Control.Zoom(options);
7868 * L.Control.Attribution is used for displaying attribution on the map (added by default).
7871 L.Control.Attribution = L.Control.extend({
7873 position: 'bottomright',
7874 prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
7877 initialize: function (options) {
7878 L.setOptions(this, options);
7880 this._attributions = {};
7883 onAdd: function (map) {
7884 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
7885 L.DomEvent.disableClickPropagation(this._container);
7888 .on('layeradd', this._onLayerAdd, this)
7889 .on('layerremove', this._onLayerRemove, this);
7893 return this._container;
7896 onRemove: function (map) {
7898 .off('layeradd', this._onLayerAdd)
7899 .off('layerremove', this._onLayerRemove);
7903 setPrefix: function (prefix) {
7904 this.options.prefix = prefix;
7909 addAttribution: function (text) {
7910 if (!text) { return; }
7912 if (!this._attributions[text]) {
7913 this._attributions[text] = 0;
7915 this._attributions[text]++;
7922 removeAttribution: function (text) {
7923 if (!text) { return; }
7925 if (this._attributions[text]) {
7926 this._attributions[text]--;
7933 _update: function () {
7934 if (!this._map) { return; }
7938 for (var i in this._attributions) {
7939 if (this._attributions[i]) {
7944 var prefixAndAttribs = [];
7946 if (this.options.prefix) {
7947 prefixAndAttribs.push(this.options.prefix);
7949 if (attribs.length) {
7950 prefixAndAttribs.push(attribs.join(', '));
7953 this._container.innerHTML = prefixAndAttribs.join(' | ');
7956 _onLayerAdd: function (e) {
7957 if (e.layer.getAttribution) {
7958 this.addAttribution(e.layer.getAttribution());
7962 _onLayerRemove: function (e) {
7963 if (e.layer.getAttribution) {
7964 this.removeAttribution(e.layer.getAttribution());
7969 L.Map.mergeOptions({
7970 attributionControl: true
7973 L.Map.addInitHook(function () {
7974 if (this.options.attributionControl) {
7975 this.attributionControl = (new L.Control.Attribution()).addTo(this);
7979 L.control.attribution = function (options) {
7980 return new L.Control.Attribution(options);
7985 * L.Control.Scale is used for displaying metric/imperial scale on the map.
7988 L.Control.Scale = L.Control.extend({
7990 position: 'bottomleft',
7994 updateWhenIdle: false
7997 onAdd: function (map) {
8000 var className = 'leaflet-control-scale',
8001 container = L.DomUtil.create('div', className),
8002 options = this.options;
8004 this._addScales(options, className, container);
8006 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8007 map.whenReady(this._update, this);
8012 onRemove: function (map) {
8013 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8016 _addScales: function (options, className, container) {
8017 if (options.metric) {
8018 this._mScale = L.DomUtil.create('div', className + '-line', container);
8020 if (options.imperial) {
8021 this._iScale = L.DomUtil.create('div', className + '-line', container);
8025 _update: function () {
8026 var bounds = this._map.getBounds(),
8027 centerLat = bounds.getCenter().lat,
8028 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
8029 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
8031 size = this._map.getSize(),
8032 options = this.options,
8036 maxMeters = dist * (options.maxWidth / size.x);
8039 this._updateScales(options, maxMeters);
8042 _updateScales: function (options, maxMeters) {
8043 if (options.metric && maxMeters) {
8044 this._updateMetric(maxMeters);
8047 if (options.imperial && maxMeters) {
8048 this._updateImperial(maxMeters);
8052 _updateMetric: function (maxMeters) {
8053 var meters = this._getRoundNum(maxMeters);
8055 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
8056 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
8059 _updateImperial: function (maxMeters) {
8060 var maxFeet = maxMeters * 3.2808399,
8061 scale = this._iScale,
8062 maxMiles, miles, feet;
8064 if (maxFeet > 5280) {
8065 maxMiles = maxFeet / 5280;
8066 miles = this._getRoundNum(maxMiles);
8068 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
8069 scale.innerHTML = miles + ' mi';
8072 feet = this._getRoundNum(maxFeet);
8074 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
8075 scale.innerHTML = feet + ' ft';
8079 _getScaleWidth: function (ratio) {
8080 return Math.round(this.options.maxWidth * ratio) - 10;
8083 _getRoundNum: function (num) {
8084 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
8087 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
8093 L.control.scale = function (options) {
8094 return new L.Control.Scale(options);
8099 * L.Control.Layers is a control to allow users to switch between different layers on the map.
8102 L.Control.Layers = L.Control.extend({
8105 position: 'topright',
8109 initialize: function (baseLayers, overlays, options) {
8110 L.setOptions(this, options);
8113 this._lastZIndex = 0;
8114 this._handlingClick = false;
8116 for (var i in baseLayers) {
8117 this._addLayer(baseLayers[i], i);
8120 for (i in overlays) {
8121 this._addLayer(overlays[i], i, true);
8125 onAdd: function (map) {
8130 .on('layeradd', this._onLayerChange, this)
8131 .on('layerremove', this._onLayerChange, this);
8133 return this._container;
8136 onRemove: function (map) {
8138 .off('layeradd', this._onLayerChange)
8139 .off('layerremove', this._onLayerChange);
8142 addBaseLayer: function (layer, name) {
8143 this._addLayer(layer, name);
8148 addOverlay: function (layer, name) {
8149 this._addLayer(layer, name, true);
8154 removeLayer: function (layer) {
8155 var id = L.stamp(layer);
8156 delete this._layers[id];
8161 _initLayout: function () {
8162 var className = 'leaflet-control-layers',
8163 container = this._container = L.DomUtil.create('div', className);
8165 //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
8166 container.setAttribute('aria-haspopup', true);
8168 if (!L.Browser.touch) {
8169 L.DomEvent.disableClickPropagation(container);
8170 L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
8172 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
8175 var form = this._form = L.DomUtil.create('form', className + '-list');
8177 if (this.options.collapsed) {
8178 if (!L.Browser.android) {
8180 .on(container, 'mouseover', this._expand, this)
8181 .on(container, 'mouseout', this._collapse, this);
8183 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
8185 link.title = 'Layers';
8187 if (L.Browser.touch) {
8189 .on(link, 'click', L.DomEvent.stop)
8190 .on(link, 'click', this._expand, this);
8193 L.DomEvent.on(link, 'focus', this._expand, this);
8196 this._map.on('click', this._collapse, this);
8197 // TODO keyboard accessibility
8202 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
8203 this._separator = L.DomUtil.create('div', className + '-separator', form);
8204 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
8206 container.appendChild(form);
8209 _addLayer: function (layer, name, overlay) {
8210 var id = L.stamp(layer);
8212 this._layers[id] = {
8218 if (this.options.autoZIndex && layer.setZIndex) {
8220 layer.setZIndex(this._lastZIndex);
8224 _update: function () {
8225 if (!this._container) {
8229 this._baseLayersList.innerHTML = '';
8230 this._overlaysList.innerHTML = '';
8232 var baseLayersPresent = false,
8233 overlaysPresent = false,
8236 for (i in this._layers) {
8237 obj = this._layers[i];
8239 overlaysPresent = overlaysPresent || obj.overlay;
8240 baseLayersPresent = baseLayersPresent || !obj.overlay;
8243 this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
8246 _onLayerChange: function (e) {
8247 var obj = this._layers[L.stamp(e.layer)];
8249 if (!obj) { return; }
8251 if (!this._handlingClick) {
8255 var type = obj.overlay ?
8256 (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
8257 (e.type === 'layeradd' ? 'baselayerchange' : null);
8260 this._map.fire(type, obj);
8264 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
8265 _createRadioElement: function (name, checked) {
8267 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
8269 radioHtml += ' checked="checked"';
8273 var radioFragment = document.createElement('div');
8274 radioFragment.innerHTML = radioHtml;
8276 return radioFragment.firstChild;
8279 _addItem: function (obj) {
8280 var label = document.createElement('label'),
8282 checked = this._map.hasLayer(obj.layer);
8285 input = document.createElement('input');
8286 input.type = 'checkbox';
8287 input.className = 'leaflet-control-layers-selector';
8288 input.defaultChecked = checked;
8290 input = this._createRadioElement('leaflet-base-layers', checked);
8293 input.layerId = L.stamp(obj.layer);
8295 L.DomEvent.on(input, 'click', this._onInputClick, this);
8297 var name = document.createElement('span');
8298 name.innerHTML = ' ' + obj.name;
8300 label.appendChild(input);
8301 label.appendChild(name);
8303 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
8304 container.appendChild(label);
8309 _onInputClick: function () {
8311 inputs = this._form.getElementsByTagName('input'),
8312 inputsLen = inputs.length;
8314 this._handlingClick = true;
8316 for (i = 0; i < inputsLen; i++) {
8318 obj = this._layers[input.layerId];
8320 if (input.checked && !this._map.hasLayer(obj.layer)) {
8321 this._map.addLayer(obj.layer);
8323 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
8324 this._map.removeLayer(obj.layer);
8328 this._handlingClick = false;
8331 _expand: function () {
8332 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
8335 _collapse: function () {
8336 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
8340 L.control.layers = function (baseLayers, overlays, options) {
8341 return new L.Control.Layers(baseLayers, overlays, options);
8346 * L.PosAnimation is used by Leaflet internally for pan animations.
8349 L.PosAnimation = L.Class.extend({
8350 includes: L.Mixin.Events,
8352 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8356 this._inProgress = true;
8357 this._newPos = newPos;
8361 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
8362 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
8364 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8365 L.DomUtil.setPosition(el, newPos);
8367 // toggle reflow, Chrome flickers for some reason if you don't do this
8368 L.Util.falseFn(el.offsetWidth);
8370 // there's no native way to track value updates of transitioned properties, so we imitate this
8371 this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
8375 if (!this._inProgress) { return; }
8377 // if we just removed the transition property, the element would jump to its final position,
8378 // so we need to make it stay at the current position
8380 L.DomUtil.setPosition(this._el, this._getPos());
8381 this._onTransitionEnd();
8382 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
8385 _onStep: function () {
8386 var stepPos = this._getPos();
8388 this._onTransitionEnd();
8391 // jshint camelcase: false
8392 // make L.DomUtil.getPosition return intermediate position value during animation
8393 this._el._leaflet_pos = stepPos;
8398 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
8399 // we need to parse computed style (in case of transform it returns matrix string)
8401 _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
8403 _getPos: function () {
8404 var left, top, matches,
8406 style = window.getComputedStyle(el);
8408 if (L.Browser.any3d) {
8409 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
8410 if (!matches) { return; }
8411 left = parseFloat(matches[1]);
8412 top = parseFloat(matches[2]);
8414 left = parseFloat(style.left);
8415 top = parseFloat(style.top);
8418 return new L.Point(left, top, true);
8421 _onTransitionEnd: function () {
8422 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8424 if (!this._inProgress) { return; }
8425 this._inProgress = false;
8427 this._el.style[L.DomUtil.TRANSITION] = '';
8429 // jshint camelcase: false
8430 // make sure L.DomUtil.getPosition returns the final position value after animation
8431 this._el._leaflet_pos = this._newPos;
8433 clearInterval(this._stepTimer);
8435 this.fire('step').fire('end');
8442 * Extends L.Map to handle panning animations.
8447 setView: function (center, zoom, options) {
8449 zoom = this._limitZoom(zoom);
8450 center = L.latLng(center);
8451 options = options || {};
8453 if (this._panAnim) {
8454 this._panAnim.stop();
8457 if (this._loaded && !options.reset && options !== true) {
8459 if (options.animate !== undefined) {
8460 options.zoom = L.extend({animate: options.animate}, options.zoom);
8461 options.pan = L.extend({animate: options.animate}, options.pan);
8464 // try animating pan or zoom
8465 var animated = (this._zoom !== zoom) ?
8466 this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
8467 this._tryAnimatedPan(center, options.pan);
8470 // prevent resize handler call, the view will refresh after animation anyway
8471 clearTimeout(this._sizeTimer);
8476 // animation didn't start, just reset the map view
8477 this._resetView(center, zoom);
8482 panBy: function (offset, options) {
8483 offset = L.point(offset).round();
8484 options = options || {};
8486 if (!offset.x && !offset.y) {
8490 if (!this._panAnim) {
8491 this._panAnim = new L.PosAnimation();
8494 'step': this._onPanTransitionStep,
8495 'end': this._onPanTransitionEnd
8499 // don't fire movestart if animating inertia
8500 if (!options.noMoveStart) {
8501 this.fire('movestart');
8504 // animate pan unless animate: false specified
8505 if (options.animate !== false) {
8506 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
8508 var newPos = this._getMapPanePos().subtract(offset);
8509 this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
8511 this._rawPanBy(offset);
8512 this.fire('move').fire('moveend');
8518 _onPanTransitionStep: function () {
8522 _onPanTransitionEnd: function () {
8523 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
8524 this.fire('moveend');
8527 _tryAnimatedPan: function (center, options) {
8528 // difference between the new and current centers in pixels
8529 var offset = this._getCenterOffset(center)._floor();
8531 // don't animate too far unless animate: true specified in options
8532 if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
8534 this.panBy(offset, options);
8542 * L.PosAnimation fallback implementation that powers Leaflet pan animations
8543 * in browsers that don't support CSS3 Transitions.
8546 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8548 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8552 this._inProgress = true;
8553 this._duration = duration || 0.25;
8554 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8556 this._startPos = L.DomUtil.getPosition(el);
8557 this._offset = newPos.subtract(this._startPos);
8558 this._startTime = +new Date();
8566 if (!this._inProgress) { return; }
8572 _animate: function () {
8574 this._animId = L.Util.requestAnimFrame(this._animate, this);
8578 _step: function () {
8579 var elapsed = (+new Date()) - this._startTime,
8580 duration = this._duration * 1000;
8582 if (elapsed < duration) {
8583 this._runFrame(this._easeOut(elapsed / duration));
8590 _runFrame: function (progress) {
8591 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8592 L.DomUtil.setPosition(this._el, pos);
8597 _complete: function () {
8598 L.Util.cancelAnimFrame(this._animId);
8600 this._inProgress = false;
8604 _easeOut: function (t) {
8605 return 1 - Math.pow(1 - t, this._easeOutPower);
8611 * Extends L.Map to handle zoom animations.
8614 L.Map.mergeOptions({
8615 zoomAnimation: true,
8616 zoomAnimationThreshold: 4
8619 if (L.DomUtil.TRANSITION) {
8621 L.Map.addInitHook(function () {
8622 // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
8623 this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
8624 L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
8626 // zoom transitions run with the same duration for all layers, so if one of transitionend events
8627 // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
8628 if (this._zoomAnimated) {
8629 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8634 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8636 _catchTransitionEnd: function () {
8637 if (this._animatingZoom) {
8638 this._onZoomTransitionEnd();
8642 _nothingToAnimate: function () {
8643 return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
8646 _tryAnimatedZoom: function (center, zoom, options) {
8648 if (this._animatingZoom) { return true; }
8650 options = options || {};
8652 // don't animate if disabled, not supported or zoom difference is too large
8653 if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
8654 Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
8656 // offset is the pixel coords of the zoom origin relative to the current center
8657 var scale = this.getZoomScale(zoom),
8658 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
8659 origin = this._getCenterLayerPoint()._add(offset);
8661 // don't animate if the zoom origin isn't within one screen from the current center, unless forced
8662 if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
8668 this._animateZoom(center, zoom, origin, scale, null, true);
8673 _animateZoom: function (center, zoom, origin, scale, delta, backwards) {
8675 this._animatingZoom = true;
8677 // put transform transition on all layers with leaflet-zoom-animated class
8678 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8680 // remember what center/zoom to set after animation
8681 this._animateToCenter = center;
8682 this._animateToZoom = zoom;
8684 // disable any dragging during animation
8686 L.Draggable._disabled = true;
8689 this.fire('zoomanim', {
8695 backwards: backwards
8699 _onZoomTransitionEnd: function () {
8701 this._animatingZoom = false;
8703 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8705 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8708 L.Draggable._disabled = false;
8715 Zoom animation logic for L.TileLayer.
8718 L.TileLayer.include({
8719 _animateZoom: function (e) {
8720 if (!this._animating) {
8721 this._animating = true;
8722 this._prepareBgBuffer();
8725 var bg = this._bgBuffer,
8726 transform = L.DomUtil.TRANSFORM,
8727 initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
8728 scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
8730 bg.style[transform] = e.backwards ?
8731 scaleStr + ' ' + initialTransform :
8732 initialTransform + ' ' + scaleStr;
8735 _endZoomAnim: function () {
8736 var front = this._tileContainer,
8737 bg = this._bgBuffer;
8739 front.style.visibility = '';
8740 front.parentNode.appendChild(front); // Bring to fore
8743 L.Util.falseFn(bg.offsetWidth);
8745 this._animating = false;
8748 _clearBgBuffer: function () {
8749 var map = this._map;
8751 if (map && !map._animatingZoom && !map.touchZoom._zooming) {
8752 this._bgBuffer.innerHTML = '';
8753 this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
8757 _prepareBgBuffer: function () {
8759 var front = this._tileContainer,
8760 bg = this._bgBuffer;
8762 // if foreground layer doesn't have many tiles but bg layer does,
8763 // keep the existing bg layer and just zoom it some more
8765 var bgLoaded = this._getLoadedTilesPercentage(bg),
8766 frontLoaded = this._getLoadedTilesPercentage(front);
8768 if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
8770 front.style.visibility = 'hidden';
8771 this._stopLoadingImages(front);
8775 // prepare the buffer to become the front tile pane
8776 bg.style.visibility = 'hidden';
8777 bg.style[L.DomUtil.TRANSFORM] = '';
8779 // switch out the current layer to be the new bg layer (and vice-versa)
8780 this._tileContainer = bg;
8781 bg = this._bgBuffer = front;
8783 this._stopLoadingImages(bg);
8785 //prevent bg buffer from clearing right after zoom
8786 clearTimeout(this._clearBgBufferTimer);
8789 _getLoadedTilesPercentage: function (container) {
8790 var tiles = container.getElementsByTagName('img'),
8793 for (i = 0, len = tiles.length; i < len; i++) {
8794 if (tiles[i].complete) {
8801 // stops loading all tiles in the background layer
8802 _stopLoadingImages: function (container) {
8803 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
8806 for (i = 0, len = tiles.length; i < len; i++) {
8809 if (!tile.complete) {
8810 tile.onload = L.Util.falseFn;
8811 tile.onerror = L.Util.falseFn;
8812 tile.src = L.Util.emptyImageUrl;
8814 tile.parentNode.removeChild(tile);
8822 * Provides L.Map with convenient shortcuts for using browser geolocation features.
8826 _defaultLocateOptions: {
8832 enableHighAccuracy: false
8835 locate: function (/*Object*/ options) {
8837 options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
8839 if (!navigator.geolocation) {
8840 this._handleGeolocationError({
8842 message: 'Geolocation not supported.'
8847 var onResponse = L.bind(this._handleGeolocationResponse, this),
8848 onError = L.bind(this._handleGeolocationError, this);
8850 if (options.watch) {
8851 this._locationWatchId =
8852 navigator.geolocation.watchPosition(onResponse, onError, options);
8854 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
8859 stopLocate: function () {
8860 if (navigator.geolocation) {
8861 navigator.geolocation.clearWatch(this._locationWatchId);
8863 if (this._locateOptions) {
8864 this._locateOptions.setView = false;
8869 _handleGeolocationError: function (error) {
8871 message = error.message ||
8872 (c === 1 ? 'permission denied' :
8873 (c === 2 ? 'position unavailable' : 'timeout'));
8875 if (this._locateOptions.setView && !this._loaded) {
8879 this.fire('locationerror', {
8881 message: 'Geolocation error: ' + message + '.'
8885 _handleGeolocationResponse: function (pos) {
8886 var lat = pos.coords.latitude,
8887 lng = pos.coords.longitude,
8888 latlng = new L.LatLng(lat, lng),
8890 latAccuracy = 180 * pos.coords.accuracy / 40075017,
8891 lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
8893 bounds = L.latLngBounds(
8894 [lat - latAccuracy, lng - lngAccuracy],
8895 [lat + latAccuracy, lng + lngAccuracy]),
8897 options = this._locateOptions;
8899 if (options.setView) {
8900 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
8901 this.setView(latlng, zoom);
8909 for (var i in pos.coords) {
8910 if (typeof pos.coords[i] === 'number') {
8911 data[i] = pos.coords[i];
8915 this.fire('locationfound', data);
8920 }(window, document));