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 var userDragProperty = L.DomUtil.testProp(
1096 ['userDrag', 'WebkitUserDrag', 'OUserDrag', 'MozUserDrag', 'msUserDrag']);
1098 L.extend(L.DomUtil, {
1099 disableTextSelection: function () {
1100 if (userSelectProperty) {
1101 var style = document.documentElement.style;
1102 this._userSelect = style[userSelectProperty];
1103 style[userSelectProperty] = 'none';
1105 L.DomEvent.on(window, 'selectstart', L.DomEvent.stop);
1109 enableTextSelection: function () {
1110 if (userSelectProperty) {
1111 document.documentElement.style[userSelectProperty] = this._userSelect;
1112 delete this._userSelect;
1114 L.DomEvent.off(window, 'selectstart', L.DomEvent.stop);
1118 disableImageDrag: function () {
1119 if (userDragProperty) {
1120 var style = document.documentElement.style;
1121 this._userDrag = style[userDragProperty];
1122 style[userDragProperty] = 'none';
1124 L.DomEvent.on(window, 'dragstart', L.DomEvent.stop);
1128 enableImageDrag: function () {
1129 if (userDragProperty) {
1130 document.documentElement.style[userDragProperty] = this._userDrag;
1131 delete this._userDrag;
1133 L.DomEvent.off(window, 'dragstart', L.DomEvent.stop);
1141 * L.LatLng represents a geographical point with latitude and longitude coordinates.
1144 L.LatLng = function (rawLat, rawLng) { // (Number, Number)
1145 var lat = parseFloat(rawLat),
1146 lng = parseFloat(rawLng);
1148 if (isNaN(lat) || isNaN(lng)) {
1149 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
1156 L.extend(L.LatLng, {
1157 DEG_TO_RAD: Math.PI / 180,
1158 RAD_TO_DEG: 180 / Math.PI,
1159 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
1162 L.LatLng.prototype = {
1163 equals: function (obj) { // (LatLng) -> Boolean
1164 if (!obj) { return false; }
1166 obj = L.latLng(obj);
1168 var margin = Math.max(
1169 Math.abs(this.lat - obj.lat),
1170 Math.abs(this.lng - obj.lng));
1172 return margin <= L.LatLng.MAX_MARGIN;
1175 toString: function (precision) { // (Number) -> String
1177 L.Util.formatNum(this.lat, precision) + ', ' +
1178 L.Util.formatNum(this.lng, precision) + ')';
1181 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1182 // TODO move to projection code, LatLng shouldn't know about Earth
1183 distanceTo: function (other) { // (LatLng) -> Number
1184 other = L.latLng(other);
1186 var R = 6378137, // earth radius in meters
1187 d2r = L.LatLng.DEG_TO_RAD,
1188 dLat = (other.lat - this.lat) * d2r,
1189 dLon = (other.lng - this.lng) * d2r,
1190 lat1 = this.lat * d2r,
1191 lat2 = other.lat * d2r,
1192 sin1 = Math.sin(dLat / 2),
1193 sin2 = Math.sin(dLon / 2);
1195 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1197 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1200 wrap: function (a, b) { // (Number, Number) -> LatLng
1206 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1208 return new L.LatLng(this.lat, lng);
1212 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1213 if (a instanceof L.LatLng) {
1216 if (L.Util.isArray(a)) {
1217 return new L.LatLng(a[0], a[1]);
1219 if (a === undefined || a === null) {
1222 if (typeof a === 'object' && 'lat' in a) {
1223 return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
1225 return new L.LatLng(a, b);
1231 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1234 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1235 if (!southWest) { return; }
1237 var latlngs = northEast ? [southWest, northEast] : southWest;
1239 for (var i = 0, len = latlngs.length; i < len; i++) {
1240 this.extend(latlngs[i]);
1244 L.LatLngBounds.prototype = {
1245 // extend the bounds to contain the given point or bounds
1246 extend: function (obj) { // (LatLng) or (LatLngBounds)
1247 if (!obj) { return this; }
1249 if (typeof obj[0] === 'number' || typeof obj[0] === 'string' || obj instanceof L.LatLng) {
1250 obj = L.latLng(obj);
1252 obj = L.latLngBounds(obj);
1255 if (obj instanceof L.LatLng) {
1256 if (!this._southWest && !this._northEast) {
1257 this._southWest = new L.LatLng(obj.lat, obj.lng);
1258 this._northEast = new L.LatLng(obj.lat, obj.lng);
1260 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1261 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1263 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1264 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1266 } else if (obj instanceof L.LatLngBounds) {
1267 this.extend(obj._southWest);
1268 this.extend(obj._northEast);
1273 // extend the bounds by a percentage
1274 pad: function (bufferRatio) { // (Number) -> LatLngBounds
1275 var sw = this._southWest,
1276 ne = this._northEast,
1277 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1278 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1280 return new L.LatLngBounds(
1281 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1282 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1285 getCenter: function () { // -> LatLng
1286 return new L.LatLng(
1287 (this._southWest.lat + this._northEast.lat) / 2,
1288 (this._southWest.lng + this._northEast.lng) / 2);
1291 getSouthWest: function () {
1292 return this._southWest;
1295 getNorthEast: function () {
1296 return this._northEast;
1299 getNorthWest: function () {
1300 return new L.LatLng(this.getNorth(), this.getWest());
1303 getSouthEast: function () {
1304 return new L.LatLng(this.getSouth(), this.getEast());
1307 getWest: function () {
1308 return this._southWest.lng;
1311 getSouth: function () {
1312 return this._southWest.lat;
1315 getEast: function () {
1316 return this._northEast.lng;
1319 getNorth: function () {
1320 return this._northEast.lat;
1323 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1324 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1325 obj = L.latLng(obj);
1327 obj = L.latLngBounds(obj);
1330 var sw = this._southWest,
1331 ne = this._northEast,
1334 if (obj instanceof L.LatLngBounds) {
1335 sw2 = obj.getSouthWest();
1336 ne2 = obj.getNorthEast();
1341 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1342 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1345 intersects: function (bounds) { // (LatLngBounds)
1346 bounds = L.latLngBounds(bounds);
1348 var sw = this._southWest,
1349 ne = this._northEast,
1350 sw2 = bounds.getSouthWest(),
1351 ne2 = bounds.getNorthEast(),
1353 latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1354 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1356 return latIntersects && lngIntersects;
1359 toBBoxString: function () {
1360 return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
1363 equals: function (bounds) { // (LatLngBounds)
1364 if (!bounds) { return false; }
1366 bounds = L.latLngBounds(bounds);
1368 return this._southWest.equals(bounds.getSouthWest()) &&
1369 this._northEast.equals(bounds.getNorthEast());
1372 isValid: function () {
1373 return !!(this._southWest && this._northEast);
1377 //TODO International date line?
1379 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1380 if (!a || a instanceof L.LatLngBounds) {
1383 return new L.LatLngBounds(a, b);
1388 * L.Projection contains various geographical projections used by CRS classes.
1395 * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1398 L.Projection.SphericalMercator = {
1399 MAX_LATITUDE: 85.0511287798,
1401 project: function (latlng) { // (LatLng) -> Point
1402 var d = L.LatLng.DEG_TO_RAD,
1403 max = this.MAX_LATITUDE,
1404 lat = Math.max(Math.min(max, latlng.lat), -max),
1408 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1410 return new L.Point(x, y);
1413 unproject: function (point) { // (Point, Boolean) -> LatLng
1414 var d = L.LatLng.RAD_TO_DEG,
1416 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1418 return new L.LatLng(lat, lng);
1424 * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1427 L.Projection.LonLat = {
1428 project: function (latlng) {
1429 return new L.Point(latlng.lng, latlng.lat);
1432 unproject: function (point) {
1433 return new L.LatLng(point.y, point.x);
1439 * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1443 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1444 var projectedPoint = this.projection.project(latlng),
1445 scale = this.scale(zoom);
1447 return this.transformation._transform(projectedPoint, scale);
1450 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1451 var scale = this.scale(zoom),
1452 untransformedPoint = this.transformation.untransform(point, scale);
1454 return this.projection.unproject(untransformedPoint);
1457 project: function (latlng) {
1458 return this.projection.project(latlng);
1461 scale: function (zoom) {
1462 return 256 * Math.pow(2, zoom);
1468 * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1471 L.CRS.Simple = L.extend({}, L.CRS, {
1472 projection: L.Projection.LonLat,
1473 transformation: new L.Transformation(1, 0, -1, 0),
1475 scale: function (zoom) {
1476 return Math.pow(2, zoom);
1482 * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1483 * and is used by Leaflet by default.
1486 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1489 projection: L.Projection.SphericalMercator,
1490 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1492 project: function (latlng) { // (LatLng) -> Point
1493 var projectedPoint = this.projection.project(latlng),
1494 earthRadius = 6378137;
1495 return projectedPoint.multiplyBy(earthRadius);
1499 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1505 * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1508 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1511 projection: L.Projection.LonLat,
1512 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1517 * L.Map is the central class of the API - it is used to create a map.
1520 L.Map = L.Class.extend({
1522 includes: L.Mixin.Events,
1525 crs: L.CRS.EPSG3857,
1533 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1535 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1538 initialize: function (id, options) { // (HTMLElement or String, Object)
1539 options = L.setOptions(this, options);
1541 this._initContainer(id);
1545 if (options.maxBounds) {
1546 this.setMaxBounds(options.maxBounds);
1549 if (options.center && options.zoom !== undefined) {
1550 this.setView(L.latLng(options.center), options.zoom, {reset: true});
1553 this._handlers = [];
1556 this._zoomBoundLayers = {};
1557 this._tileLayersNum = 0;
1559 this.callInitHooks();
1561 this._addLayers(options.layers);
1565 // public methods that modify map state
1567 // replaced by animation-powered implementation in Map.PanAnimation.js
1568 setView: function (center, zoom) {
1569 this._resetView(L.latLng(center), this._limitZoom(zoom));
1573 setZoom: function (zoom, options) {
1574 return this.setView(this.getCenter(), zoom, {zoom: options});
1577 zoomIn: function (delta, options) {
1578 return this.setZoom(this._zoom + (delta || 1), options);
1581 zoomOut: function (delta, options) {
1582 return this.setZoom(this._zoom - (delta || 1), options);
1585 setZoomAround: function (latlng, zoom, options) {
1586 var scale = this.getZoomScale(zoom),
1587 viewHalf = this.getSize().divideBy(2),
1588 containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
1590 centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
1591 newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
1593 return this.setView(newCenter, zoom, {zoom: options});
1596 fitBounds: function (bounds, options) {
1598 options = options || {};
1599 bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
1601 var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
1602 paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
1604 zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
1605 paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
1607 swPoint = this.project(bounds.getSouthWest(), zoom),
1608 nePoint = this.project(bounds.getNorthEast(), zoom),
1609 center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
1611 return this.setView(center, zoom, options);
1614 fitWorld: function (options) {
1615 return this.fitBounds([[-90, -180], [90, 180]], options);
1618 panTo: function (center, options) { // (LatLng)
1619 return this.setView(center, this._zoom, {pan: options});
1622 panBy: function (offset) { // (Point)
1623 // replaced with animated panBy in Map.Animation.js
1624 this.fire('movestart');
1626 this._rawPanBy(L.point(offset));
1629 return this.fire('moveend');
1632 setMaxBounds: function (bounds) {
1633 bounds = L.latLngBounds(bounds);
1635 this.options.maxBounds = bounds;
1638 this._boundsMinZoom = null;
1639 this.off('moveend', this._panInsideMaxBounds, this);
1643 var minZoom = this.getBoundsZoom(bounds, true);
1645 this._boundsMinZoom = minZoom;
1648 if (this._zoom < minZoom) {
1649 this.setView(bounds.getCenter(), minZoom);
1651 this.panInsideBounds(bounds);
1655 this.on('moveend', this._panInsideMaxBounds, this);
1660 panInsideBounds: function (bounds) {
1661 bounds = L.latLngBounds(bounds);
1663 var viewBounds = this.getPixelBounds(),
1664 viewSw = viewBounds.getBottomLeft(),
1665 viewNe = viewBounds.getTopRight(),
1666 sw = this.project(bounds.getSouthWest()),
1667 ne = this.project(bounds.getNorthEast()),
1671 if (viewNe.y < ne.y) { // north
1672 dy = Math.ceil(ne.y - viewNe.y);
1674 if (viewNe.x > ne.x) { // east
1675 dx = Math.floor(ne.x - viewNe.x);
1677 if (viewSw.y > sw.y) { // south
1678 dy = Math.floor(sw.y - viewSw.y);
1680 if (viewSw.x < sw.x) { // west
1681 dx = Math.ceil(sw.x - viewSw.x);
1685 return this.panBy([dx, dy]);
1691 addLayer: function (layer) {
1692 // TODO method is too big, refactor
1694 var id = L.stamp(layer);
1696 if (this._layers[id]) { return this; }
1698 this._layers[id] = layer;
1700 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1701 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1702 this._zoomBoundLayers[id] = layer;
1703 this._updateZoomLevels();
1706 // TODO looks ugly, refactor!!!
1707 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1708 this._tileLayersNum++;
1709 this._tileLayersToLoad++;
1710 layer.on('load', this._onTileLayerLoad, this);
1714 this._layerAdd(layer);
1720 removeLayer: function (layer) {
1721 var id = L.stamp(layer);
1723 if (!this._layers[id]) { return; }
1726 layer.onRemove(this);
1727 this.fire('layerremove', {layer: layer});
1730 delete this._layers[id];
1731 if (this._zoomBoundLayers[id]) {
1732 delete this._zoomBoundLayers[id];
1733 this._updateZoomLevels();
1736 // TODO looks ugly, refactor
1737 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1738 this._tileLayersNum--;
1739 this._tileLayersToLoad--;
1740 layer.off('load', this._onTileLayerLoad, this);
1746 hasLayer: function (layer) {
1747 if (!layer) { return false; }
1749 return (L.stamp(layer) in this._layers);
1752 eachLayer: function (method, context) {
1753 for (var i in this._layers) {
1754 method.call(context, this._layers[i]);
1759 invalidateSize: function (options) {
1760 options = L.extend({
1763 }, options === true ? {animate: true} : options);
1765 var oldSize = this.getSize();
1766 this._sizeChanged = true;
1768 if (this.options.maxBounds) {
1769 this.setMaxBounds(this.options.maxBounds);
1772 if (!this._loaded) { return this; }
1774 var newSize = this.getSize(),
1775 offset = oldSize.subtract(newSize).divideBy(2).round();
1777 if (!offset.x && !offset.y) { return this; }
1779 if (options.animate && options.pan) {
1784 this._rawPanBy(offset);
1789 // make sure moveend is not fired too often on resize
1790 clearTimeout(this._sizeTimer);
1791 this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1794 return this.fire('resize', {
1800 // TODO handler.addTo
1801 addHandler: function (name, HandlerClass) {
1802 if (!HandlerClass) { return; }
1804 var handler = this[name] = new HandlerClass(this);
1806 this._handlers.push(handler);
1808 if (this.options[name]) {
1815 remove: function () {
1817 this.fire('unload');
1820 this._initEvents('off');
1822 delete this._container._leaflet;
1825 if (this._clearControlPos) {
1826 this._clearControlPos();
1829 this._clearHandlers();
1835 // public methods for getting map state
1837 getCenter: function () { // (Boolean) -> LatLng
1838 this._checkIfLoaded();
1840 if (!this._moved()) {
1841 return this._initialCenter;
1843 return this.layerPointToLatLng(this._getCenterLayerPoint());
1846 getZoom: function () {
1850 getBounds: function () {
1851 var bounds = this.getPixelBounds(),
1852 sw = this.unproject(bounds.getBottomLeft()),
1853 ne = this.unproject(bounds.getTopRight());
1855 return new L.LatLngBounds(sw, ne);
1858 getMinZoom: function () {
1859 var z1 = this.options.minZoom || 0,
1860 z2 = this._layersMinZoom || 0,
1861 z3 = this._boundsMinZoom || 0;
1863 return Math.max(z1, z2, z3);
1866 getMaxZoom: function () {
1867 var z1 = this.options.maxZoom === undefined ? Infinity : this.options.maxZoom,
1868 z2 = this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom;
1870 return Math.min(z1, z2);
1873 getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1874 bounds = L.latLngBounds(bounds);
1876 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1877 maxZoom = this.getMaxZoom(),
1878 size = this.getSize(),
1880 nw = bounds.getNorthWest(),
1881 se = bounds.getSouthEast(),
1883 zoomNotFound = true,
1886 padding = L.point(padding || [0, 0]);
1890 boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1891 zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1893 } while (zoomNotFound && zoom <= maxZoom);
1895 if (zoomNotFound && inside) {
1899 return inside ? zoom : zoom - 1;
1902 getSize: function () {
1903 if (!this._size || this._sizeChanged) {
1904 this._size = new L.Point(
1905 this._container.clientWidth,
1906 this._container.clientHeight);
1908 this._sizeChanged = false;
1910 return this._size.clone();
1913 getPixelBounds: function () {
1914 var topLeftPoint = this._getTopLeftPoint();
1915 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1918 getPixelOrigin: function () {
1919 this._checkIfLoaded();
1920 return this._initialTopLeftPoint;
1923 getPanes: function () {
1927 getContainer: function () {
1928 return this._container;
1932 // TODO replace with universal implementation after refactoring projections
1934 getZoomScale: function (toZoom) {
1935 var crs = this.options.crs;
1936 return crs.scale(toZoom) / crs.scale(this._zoom);
1939 getScaleZoom: function (scale) {
1940 return this._zoom + (Math.log(scale) / Math.LN2);
1944 // conversion methods
1946 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1947 zoom = zoom === undefined ? this._zoom : zoom;
1948 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1951 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1952 zoom = zoom === undefined ? this._zoom : zoom;
1953 return this.options.crs.pointToLatLng(L.point(point), zoom);
1956 layerPointToLatLng: function (point) { // (Point)
1957 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1958 return this.unproject(projectedPoint);
1961 latLngToLayerPoint: function (latlng) { // (LatLng)
1962 var projectedPoint = this.project(L.latLng(latlng))._round();
1963 return projectedPoint._subtract(this.getPixelOrigin());
1966 containerPointToLayerPoint: function (point) { // (Point)
1967 return L.point(point).subtract(this._getMapPanePos());
1970 layerPointToContainerPoint: function (point) { // (Point)
1971 return L.point(point).add(this._getMapPanePos());
1974 containerPointToLatLng: function (point) {
1975 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1976 return this.layerPointToLatLng(layerPoint);
1979 latLngToContainerPoint: function (latlng) {
1980 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1983 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1984 return L.DomEvent.getMousePosition(e, this._container);
1987 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1988 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1991 mouseEventToLatLng: function (e) { // (MouseEvent)
1992 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1996 // map initialization methods
1998 _initContainer: function (id) {
1999 var container = this._container = L.DomUtil.get(id);
2002 throw new Error('Map container not found.');
2003 } else if (container._leaflet) {
2004 throw new Error('Map container is already initialized.');
2007 container._leaflet = true;
2010 _initLayout: function () {
2011 var container = this._container;
2013 L.DomUtil.addClass(container, 'leaflet-container' +
2014 (L.Browser.touch ? ' leaflet-touch' : '') +
2015 (L.Browser.retina ? ' leaflet-retina' : '') +
2016 (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
2018 var position = L.DomUtil.getStyle(container, 'position');
2020 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
2021 container.style.position = 'relative';
2026 if (this._initControlPos) {
2027 this._initControlPos();
2031 _initPanes: function () {
2032 var panes = this._panes = {};
2034 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2036 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2037 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2038 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2039 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2040 panes.markerPane = this._createPane('leaflet-marker-pane');
2041 panes.popupPane = this._createPane('leaflet-popup-pane');
2043 var zoomHide = ' leaflet-zoom-hide';
2045 if (!this.options.markerZoomAnimation) {
2046 L.DomUtil.addClass(panes.markerPane, zoomHide);
2047 L.DomUtil.addClass(panes.shadowPane, zoomHide);
2048 L.DomUtil.addClass(panes.popupPane, zoomHide);
2052 _createPane: function (className, container) {
2053 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2056 _clearPanes: function () {
2057 this._container.removeChild(this._mapPane);
2060 _addLayers: function (layers) {
2061 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2063 for (var i = 0, len = layers.length; i < len; i++) {
2064 this.addLayer(layers[i]);
2069 // private methods that modify map state
2071 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2073 var zoomChanged = (this._zoom !== zoom);
2075 if (!afterZoomAnim) {
2076 this.fire('movestart');
2079 this.fire('zoomstart');
2084 this._initialCenter = center;
2086 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2088 if (!preserveMapOffset) {
2089 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2091 this._initialTopLeftPoint._add(this._getMapPanePos());
2094 this._tileLayersToLoad = this._tileLayersNum;
2096 var loading = !this._loaded;
2097 this._loaded = true;
2101 this.eachLayer(this._layerAdd, this);
2104 this.fire('viewreset', {hard: !preserveMapOffset});
2108 if (zoomChanged || afterZoomAnim) {
2109 this.fire('zoomend');
2112 this.fire('moveend', {hard: !preserveMapOffset});
2115 _rawPanBy: function (offset) {
2116 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2119 _getZoomSpan: function () {
2120 return this.getMaxZoom() - this.getMinZoom();
2123 _updateZoomLevels: function () {
2126 maxZoom = -Infinity,
2127 oldZoomSpan = this._getZoomSpan();
2129 for (i in this._zoomBoundLayers) {
2130 var layer = this._zoomBoundLayers[i];
2131 if (!isNaN(layer.options.minZoom)) {
2132 minZoom = Math.min(minZoom, layer.options.minZoom);
2134 if (!isNaN(layer.options.maxZoom)) {
2135 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2139 if (i === undefined) { // we have no tilelayers
2140 this._layersMaxZoom = this._layersMinZoom = undefined;
2142 this._layersMaxZoom = maxZoom;
2143 this._layersMinZoom = minZoom;
2146 if (oldZoomSpan !== this._getZoomSpan()) {
2147 this.fire('zoomlevelschange');
2151 _panInsideMaxBounds: function () {
2152 this.panInsideBounds(this.options.maxBounds);
2155 _checkIfLoaded: function () {
2156 if (!this._loaded) {
2157 throw new Error('Set map center and zoom first.');
2163 _initEvents: function (onOff) {
2164 if (!L.DomEvent) { return; }
2166 onOff = onOff || 'on';
2168 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2170 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2171 'mouseleave', 'mousemove', 'contextmenu'],
2174 for (i = 0, len = events.length; i < len; i++) {
2175 L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2178 if (this.options.trackResize) {
2179 L.DomEvent[onOff](window, 'resize', this._onResize, this);
2183 _onResize: function () {
2184 L.Util.cancelAnimFrame(this._resizeRequest);
2185 this._resizeRequest = L.Util.requestAnimFrame(
2186 this.invalidateSize, this, false, this._container);
2189 _onMouseClick: function (e) {
2190 // jshint camelcase: false
2191 if (!this._loaded || (!e._simulated && this.dragging && this.dragging.moved()) || e._leaflet_stop) { return; }
2193 this.fire('preclick');
2194 this._fireMouseEvent(e);
2197 _fireMouseEvent: function (e) {
2198 // jshint camelcase: false
2199 if (!this._loaded || e._leaflet_stop) { return; }
2203 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2205 if (!this.hasEventListeners(type)) { return; }
2207 if (type === 'contextmenu') {
2208 L.DomEvent.preventDefault(e);
2211 var containerPoint = this.mouseEventToContainerPoint(e),
2212 layerPoint = this.containerPointToLayerPoint(containerPoint),
2213 latlng = this.layerPointToLatLng(layerPoint);
2217 layerPoint: layerPoint,
2218 containerPoint: containerPoint,
2223 _onTileLayerLoad: function () {
2224 this._tileLayersToLoad--;
2225 if (this._tileLayersNum && !this._tileLayersToLoad) {
2226 this.fire('tilelayersload');
2230 _clearHandlers: function () {
2231 for (var i = 0, len = this._handlers.length; i < len; i++) {
2232 this._handlers[i].disable();
2236 whenReady: function (callback, context) {
2238 callback.call(context || this, this);
2240 this.on('load', callback, context);
2245 _layerAdd: function (layer) {
2247 this.fire('layeradd', {layer: layer});
2251 // private methods for getting map state
2253 _getMapPanePos: function () {
2254 return L.DomUtil.getPosition(this._mapPane);
2257 _moved: function () {
2258 var pos = this._getMapPanePos();
2259 return pos && !pos.equals([0, 0]);
2262 _getTopLeftPoint: function () {
2263 return this.getPixelOrigin().subtract(this._getMapPanePos());
2266 _getNewTopLeftPoint: function (center, zoom) {
2267 var viewHalf = this.getSize()._divideBy(2);
2268 // TODO round on display, not calculation to increase precision?
2269 return this.project(center, zoom)._subtract(viewHalf)._round();
2272 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2273 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2274 return this.project(latlng, newZoom)._subtract(topLeft);
2277 // layer point of the current center
2278 _getCenterLayerPoint: function () {
2279 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2282 // offset of the specified place to the current center in pixels
2283 _getCenterOffset: function (latlng) {
2284 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2287 _limitZoom: function (zoom) {
2288 var min = this.getMinZoom(),
2289 max = this.getMaxZoom();
2291 return Math.max(min, Math.min(max, zoom));
2295 L.map = function (id, options) {
2296 return new L.Map(id, options);
2301 * Mercator projection that takes into account that the Earth is not a perfect sphere.
2302 * Less popular than spherical mercator; used by projections like EPSG:3395.
2305 L.Projection.Mercator = {
2306 MAX_LATITUDE: 85.0840591556,
2308 R_MINOR: 6356752.314245179,
2311 project: function (latlng) { // (LatLng) -> Point
2312 var d = L.LatLng.DEG_TO_RAD,
2313 max = this.MAX_LATITUDE,
2314 lat = Math.max(Math.min(max, latlng.lat), -max),
2317 x = latlng.lng * d * r,
2320 eccent = Math.sqrt(1.0 - tmp * tmp),
2321 con = eccent * Math.sin(y);
2323 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2325 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2326 y = -r * Math.log(ts);
2328 return new L.Point(x, y);
2331 unproject: function (point) { // (Point, Boolean) -> LatLng
2332 var d = L.LatLng.RAD_TO_DEG,
2335 lng = point.x * d / r,
2337 eccent = Math.sqrt(1 - (tmp * tmp)),
2338 ts = Math.exp(- point.y / r2),
2339 phi = (Math.PI / 2) - 2 * Math.atan(ts),
2346 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2347 con = eccent * Math.sin(phi);
2348 dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2349 Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2353 return new L.LatLng(phi * d, lng);
2359 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2362 projection: L.Projection.Mercator,
2364 transformation: (function () {
2365 var m = L.Projection.Mercator,
2369 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
2375 * L.TileLayer is used for standard xyz-numbered tile layers.
2378 L.TileLayer = L.Class.extend({
2379 includes: L.Mixin.Events,
2390 /* (undefined works too)
2393 continuousWorld: false,
2396 detectRetina: false,
2400 unloadInvisibleTiles: L.Browser.mobile,
2401 updateWhenIdle: L.Browser.mobile
2404 initialize: function (url, options) {
2405 options = L.setOptions(this, options);
2407 // detecting retina displays, adjusting tileSize and zoom levels
2408 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2410 options.tileSize = Math.floor(options.tileSize / 2);
2411 options.zoomOffset++;
2413 if (options.minZoom > 0) {
2416 this.options.maxZoom--;
2419 if (options.bounds) {
2420 options.bounds = L.latLngBounds(options.bounds);
2425 var subdomains = this.options.subdomains;
2427 if (typeof subdomains === 'string') {
2428 this.options.subdomains = subdomains.split('');
2432 onAdd: function (map) {
2434 this._animated = map._zoomAnimated;
2436 // create a container div for tiles
2437 this._initContainer();
2439 // create an image to clone for tiles
2440 this._createTileProto();
2444 'viewreset': this._reset,
2445 'moveend': this._update
2448 if (this._animated) {
2450 'zoomanim': this._animateZoom,
2451 'zoomend': this._endZoomAnim
2455 if (!this.options.updateWhenIdle) {
2456 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2457 map.on('move', this._limitedUpdate, this);
2464 addTo: function (map) {
2469 onRemove: function (map) {
2470 this._container.parentNode.removeChild(this._container);
2473 'viewreset': this._reset,
2474 'moveend': this._update
2477 if (this._animated) {
2479 'zoomanim': this._animateZoom,
2480 'zoomend': this._endZoomAnim
2484 if (!this.options.updateWhenIdle) {
2485 map.off('move', this._limitedUpdate, this);
2488 this._container = null;
2492 bringToFront: function () {
2493 var pane = this._map._panes.tilePane;
2495 if (this._container) {
2496 pane.appendChild(this._container);
2497 this._setAutoZIndex(pane, Math.max);
2503 bringToBack: function () {
2504 var pane = this._map._panes.tilePane;
2506 if (this._container) {
2507 pane.insertBefore(this._container, pane.firstChild);
2508 this._setAutoZIndex(pane, Math.min);
2514 getAttribution: function () {
2515 return this.options.attribution;
2518 getContainer: function () {
2519 return this._container;
2522 setOpacity: function (opacity) {
2523 this.options.opacity = opacity;
2526 this._updateOpacity();
2532 setZIndex: function (zIndex) {
2533 this.options.zIndex = zIndex;
2534 this._updateZIndex();
2539 setUrl: function (url, noRedraw) {
2549 redraw: function () {
2551 this._reset({hard: true});
2557 _updateZIndex: function () {
2558 if (this._container && this.options.zIndex !== undefined) {
2559 this._container.style.zIndex = this.options.zIndex;
2563 _setAutoZIndex: function (pane, compare) {
2565 var layers = pane.children,
2566 edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2569 for (i = 0, len = layers.length; i < len; i++) {
2571 if (layers[i] !== this._container) {
2572 zIndex = parseInt(layers[i].style.zIndex, 10);
2574 if (!isNaN(zIndex)) {
2575 edgeZIndex = compare(edgeZIndex, zIndex);
2580 this.options.zIndex = this._container.style.zIndex =
2581 (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2584 _updateOpacity: function () {
2586 tiles = this._tiles;
2588 if (L.Browser.ielt9) {
2590 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2593 L.DomUtil.setOpacity(this._container, this.options.opacity);
2597 _initContainer: function () {
2598 var tilePane = this._map._panes.tilePane;
2600 if (!this._container) {
2601 this._container = L.DomUtil.create('div', 'leaflet-layer');
2603 this._updateZIndex();
2605 if (this._animated) {
2606 var className = 'leaflet-tile-container leaflet-zoom-animated';
2608 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2609 this._bgBuffer.style.zIndex = 1;
2611 this._tileContainer = L.DomUtil.create('div', className, this._container);
2612 this._tileContainer.style.zIndex = 2;
2615 this._tileContainer = this._container;
2618 tilePane.appendChild(this._container);
2620 if (this.options.opacity < 1) {
2621 this._updateOpacity();
2626 _reset: function (e) {
2627 for (var key in this._tiles) {
2628 this.fire('tileunload', {tile: this._tiles[key]});
2632 this._tilesToLoad = 0;
2634 if (this.options.reuseTiles) {
2635 this._unusedTiles = [];
2638 this._tileContainer.innerHTML = '';
2640 if (this._animated && e && e.hard) {
2641 this._clearBgBuffer();
2644 this._initContainer();
2647 _update: function () {
2649 if (!this._map) { return; }
2651 var bounds = this._map.getPixelBounds(),
2652 zoom = this._map.getZoom(),
2653 tileSize = this.options.tileSize;
2655 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2659 var tileBounds = L.bounds(
2660 bounds.min.divideBy(tileSize)._floor(),
2661 bounds.max.divideBy(tileSize)._floor());
2663 this._addTilesFromCenterOut(tileBounds);
2665 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2666 this._removeOtherTiles(tileBounds);
2670 _addTilesFromCenterOut: function (bounds) {
2672 center = bounds.getCenter();
2676 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2677 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2678 point = new L.Point(i, j);
2680 if (this._tileShouldBeLoaded(point)) {
2686 var tilesToLoad = queue.length;
2688 if (tilesToLoad === 0) { return; }
2690 // load tiles in order of their distance to center
2691 queue.sort(function (a, b) {
2692 return a.distanceTo(center) - b.distanceTo(center);
2695 var fragment = document.createDocumentFragment();
2697 // if its the first batch of tiles to load
2698 if (!this._tilesToLoad) {
2699 this.fire('loading');
2702 this._tilesToLoad += tilesToLoad;
2704 for (i = 0; i < tilesToLoad; i++) {
2705 this._addTile(queue[i], fragment);
2708 this._tileContainer.appendChild(fragment);
2711 _tileShouldBeLoaded: function (tilePoint) {
2712 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2713 return false; // already loaded
2716 var options = this.options;
2718 if (!options.continuousWorld) {
2719 var limit = this._getWrapTileNum();
2721 // don't load if exceeds world bounds
2722 if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit)) ||
2723 tilePoint.y < 0 || tilePoint.y >= limit) { return false; }
2726 if (options.bounds) {
2727 var tileSize = options.tileSize,
2728 nwPoint = tilePoint.multiplyBy(tileSize),
2729 sePoint = nwPoint.add([tileSize, tileSize]),
2730 nw = this._map.unproject(nwPoint),
2731 se = this._map.unproject(sePoint);
2733 // TODO temporary hack, will be removed after refactoring projections
2734 // https://github.com/Leaflet/Leaflet/issues/1618
2735 if (!options.continuousWorld && !options.noWrap) {
2740 if (!options.bounds.intersects([nw, se])) { return false; }
2746 _removeOtherTiles: function (bounds) {
2747 var kArr, x, y, key;
2749 for (key in this._tiles) {
2750 kArr = key.split(':');
2751 x = parseInt(kArr[0], 10);
2752 y = parseInt(kArr[1], 10);
2754 // remove tile if it's out of bounds
2755 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2756 this._removeTile(key);
2761 _removeTile: function (key) {
2762 var tile = this._tiles[key];
2764 this.fire('tileunload', {tile: tile, url: tile.src});
2766 if (this.options.reuseTiles) {
2767 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2768 this._unusedTiles.push(tile);
2770 } else if (tile.parentNode === this._tileContainer) {
2771 this._tileContainer.removeChild(tile);
2774 // for https://github.com/CloudMade/Leaflet/issues/137
2775 if (!L.Browser.android) {
2777 tile.src = L.Util.emptyImageUrl;
2780 delete this._tiles[key];
2783 _addTile: function (tilePoint, container) {
2784 var tilePos = this._getTilePos(tilePoint);
2786 // get unused tile - or create a new tile
2787 var tile = this._getTile();
2790 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2791 Android 4 browser has display issues with top/left and requires transform instead
2792 Android 2 browser requires top/left or tiles disappear on load or first drag
2793 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2794 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2796 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2798 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2800 this._loadTile(tile, tilePoint);
2802 if (tile.parentNode !== this._tileContainer) {
2803 container.appendChild(tile);
2807 _getZoomForUrl: function () {
2809 var options = this.options,
2810 zoom = this._map.getZoom();
2812 if (options.zoomReverse) {
2813 zoom = options.maxZoom - zoom;
2816 return zoom + options.zoomOffset;
2819 _getTilePos: function (tilePoint) {
2820 var origin = this._map.getPixelOrigin(),
2821 tileSize = this.options.tileSize;
2823 return tilePoint.multiplyBy(tileSize).subtract(origin);
2826 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2828 getTileUrl: function (tilePoint) {
2829 return L.Util.template(this._url, L.extend({
2830 s: this._getSubdomain(tilePoint),
2837 _getWrapTileNum: function () {
2838 // TODO refactor, limit is not valid for non-standard projections
2839 return Math.pow(2, this._getZoomForUrl());
2842 _adjustTilePoint: function (tilePoint) {
2844 var limit = this._getWrapTileNum();
2846 // wrap tile coordinates
2847 if (!this.options.continuousWorld && !this.options.noWrap) {
2848 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2851 if (this.options.tms) {
2852 tilePoint.y = limit - tilePoint.y - 1;
2855 tilePoint.z = this._getZoomForUrl();
2858 _getSubdomain: function (tilePoint) {
2859 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2860 return this.options.subdomains[index];
2863 _createTileProto: function () {
2864 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2865 img.style.width = img.style.height = this.options.tileSize + 'px';
2866 img.galleryimg = 'no';
2869 _getTile: function () {
2870 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2871 var tile = this._unusedTiles.pop();
2872 this._resetTile(tile);
2875 return this._createTile();
2878 // Override if data stored on a tile needs to be cleaned up before reuse
2879 _resetTile: function (/*tile*/) {},
2881 _createTile: function () {
2882 var tile = this._tileImg.cloneNode(false);
2883 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2885 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2886 L.DomUtil.setOpacity(tile, this.options.opacity);
2891 _loadTile: function (tile, tilePoint) {
2893 tile.onload = this._tileOnLoad;
2894 tile.onerror = this._tileOnError;
2896 this._adjustTilePoint(tilePoint);
2897 tile.src = this.getTileUrl(tilePoint);
2900 _tileLoaded: function () {
2901 this._tilesToLoad--;
2902 if (!this._tilesToLoad) {
2905 if (this._animated) {
2906 // clear scaled tiles after all new tiles are loaded (for performance)
2907 clearTimeout(this._clearBgBufferTimer);
2908 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2913 _tileOnLoad: function () {
2914 var layer = this._layer;
2916 //Only if we are loading an actual image
2917 if (this.src !== L.Util.emptyImageUrl) {
2918 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2920 layer.fire('tileload', {
2926 layer._tileLoaded();
2929 _tileOnError: function () {
2930 var layer = this._layer;
2932 layer.fire('tileerror', {
2937 var newUrl = layer.options.errorTileUrl;
2942 layer._tileLoaded();
2946 L.tileLayer = function (url, options) {
2947 return new L.TileLayer(url, options);
2952 * L.TileLayer.WMS is used for putting WMS tile layers on the map.
2955 L.TileLayer.WMS = L.TileLayer.extend({
2963 format: 'image/jpeg',
2967 initialize: function (url, options) { // (String, Object)
2971 var wmsParams = L.extend({}, this.defaultWmsParams),
2972 tileSize = options.tileSize || this.options.tileSize;
2974 if (options.detectRetina && L.Browser.retina) {
2975 wmsParams.width = wmsParams.height = tileSize * 2;
2977 wmsParams.width = wmsParams.height = tileSize;
2980 for (var i in options) {
2981 // all keys that are not TileLayer options go to WMS params
2982 if (!this.options.hasOwnProperty(i) && i !== 'crs') {
2983 wmsParams[i] = options[i];
2987 this.wmsParams = wmsParams;
2989 L.setOptions(this, options);
2992 onAdd: function (map) {
2994 this._crs = this.options.crs || map.options.crs;
2996 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2997 this.wmsParams[projectionKey] = this._crs.code;
2999 L.TileLayer.prototype.onAdd.call(this, map);
3002 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
3004 var map = this._map,
3005 tileSize = this.options.tileSize,
3007 nwPoint = tilePoint.multiplyBy(tileSize),
3008 sePoint = nwPoint.add([tileSize, tileSize]),
3010 nw = this._crs.project(map.unproject(nwPoint, zoom)),
3011 se = this._crs.project(map.unproject(sePoint, zoom)),
3013 bbox = [nw.x, se.y, se.x, nw.y].join(','),
3015 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
3017 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
3020 setParams: function (params, noRedraw) {
3022 L.extend(this.wmsParams, params);
3032 L.tileLayer.wms = function (url, options) {
3033 return new L.TileLayer.WMS(url, options);
3038 * L.TileLayer.Canvas is a class that you can use as a base for creating
3039 * dynamically drawn Canvas-based tile layers.
3042 L.TileLayer.Canvas = L.TileLayer.extend({
3047 initialize: function (options) {
3048 L.setOptions(this, options);
3051 redraw: function () {
3052 for (var i in this._tiles) {
3053 this._redrawTile(this._tiles[i]);
3058 _redrawTile: function (tile) {
3059 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3062 _createTileProto: function () {
3063 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
3064 proto.width = proto.height = this.options.tileSize;
3067 _createTile: function () {
3068 var tile = this._canvasProto.cloneNode(false);
3069 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3073 _loadTile: function (tile, tilePoint) {
3075 tile._tilePoint = tilePoint;
3077 this._redrawTile(tile);
3079 if (!this.options.async) {
3080 this.tileDrawn(tile);
3084 drawTile: function (/*tile, tilePoint*/) {
3085 // override with rendering code
3088 tileDrawn: function (tile) {
3089 this._tileOnLoad.call(tile);
3094 L.tileLayer.canvas = function (options) {
3095 return new L.TileLayer.Canvas(options);
3100 * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3103 L.ImageOverlay = L.Class.extend({
3104 includes: L.Mixin.Events,
3110 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3112 this._bounds = L.latLngBounds(bounds);
3114 L.setOptions(this, options);
3117 onAdd: function (map) {
3124 map._panes.overlayPane.appendChild(this._image);
3126 map.on('viewreset', this._reset, this);
3128 if (map.options.zoomAnimation && L.Browser.any3d) {
3129 map.on('zoomanim', this._animateZoom, this);
3135 onRemove: function (map) {
3136 map.getPanes().overlayPane.removeChild(this._image);
3138 map.off('viewreset', this._reset, this);
3140 if (map.options.zoomAnimation) {
3141 map.off('zoomanim', this._animateZoom, this);
3145 addTo: function (map) {
3150 setOpacity: function (opacity) {
3151 this.options.opacity = opacity;
3152 this._updateOpacity();
3156 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3157 bringToFront: function () {
3159 this._map._panes.overlayPane.appendChild(this._image);
3164 bringToBack: function () {
3165 var pane = this._map._panes.overlayPane;
3167 pane.insertBefore(this._image, pane.firstChild);
3172 _initImage: function () {
3173 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3175 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3176 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3178 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3181 this._updateOpacity();
3183 //TODO createImage util method to remove duplication
3184 L.extend(this._image, {
3186 onselectstart: L.Util.falseFn,
3187 onmousemove: L.Util.falseFn,
3188 onload: L.bind(this._onImageLoad, this),
3193 _animateZoom: function (e) {
3194 var map = this._map,
3195 image = this._image,
3196 scale = map.getZoomScale(e.zoom),
3197 nw = this._bounds.getNorthWest(),
3198 se = this._bounds.getSouthEast(),
3200 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3201 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3202 origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3204 image.style[L.DomUtil.TRANSFORM] =
3205 L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3208 _reset: function () {
3209 var image = this._image,
3210 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3211 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3213 L.DomUtil.setPosition(image, topLeft);
3215 image.style.width = size.x + 'px';
3216 image.style.height = size.y + 'px';
3219 _onImageLoad: function () {
3223 _updateOpacity: function () {
3224 L.DomUtil.setOpacity(this._image, this.options.opacity);
3228 L.imageOverlay = function (url, bounds, options) {
3229 return new L.ImageOverlay(url, bounds, options);
3234 * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3237 L.Icon = L.Class.extend({
3240 iconUrl: (String) (required)
3241 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3242 iconSize: (Point) (can be set through CSS)
3243 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3244 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3245 shadowUrl: (String) (no shadow by default)
3246 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3248 shadowAnchor: (Point)
3253 initialize: function (options) {
3254 L.setOptions(this, options);
3257 createIcon: function (oldIcon) {
3258 return this._createIcon('icon', oldIcon);
3261 createShadow: function (oldIcon) {
3262 return this._createIcon('shadow', oldIcon);
3265 _createIcon: function (name, oldIcon) {
3266 var src = this._getIconUrl(name);
3269 if (name === 'icon') {
3270 throw new Error('iconUrl not set in Icon options (see the docs).');
3276 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3277 img = this._createImg(src);
3279 img = this._createImg(src, oldIcon);
3281 this._setIconStyles(img, name);
3286 _setIconStyles: function (img, name) {
3287 var options = this.options,
3288 size = L.point(options[name + 'Size']),
3291 if (name === 'shadow') {
3292 anchor = L.point(options.shadowAnchor || options.iconAnchor);
3294 anchor = L.point(options.iconAnchor);
3297 if (!anchor && size) {
3298 anchor = size.divideBy(2, true);
3301 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3304 img.style.marginLeft = (-anchor.x) + 'px';
3305 img.style.marginTop = (-anchor.y) + 'px';
3309 img.style.width = size.x + 'px';
3310 img.style.height = size.y + 'px';
3314 _createImg: function (src, el) {
3316 if (!L.Browser.ie6) {
3318 el = document.createElement('img');
3323 el = document.createElement('div');
3326 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
3331 _getIconUrl: function (name) {
3332 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3333 return this.options[name + 'RetinaUrl'];
3335 return this.options[name + 'Url'];
3339 L.icon = function (options) {
3340 return new L.Icon(options);
3345 * L.Icon.Default is the blue marker icon used by default in Leaflet.
3348 L.Icon.Default = L.Icon.extend({
3352 iconAnchor: [12, 41],
3353 popupAnchor: [1, -34],
3355 shadowSize: [41, 41]
3358 _getIconUrl: function (name) {
3359 var key = name + 'Url';
3361 if (this.options[key]) {
3362 return this.options[key];
3365 if (L.Browser.retina && name === 'icon') {
3369 var path = L.Icon.Default.imagePath;
3372 throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3375 return path + '/marker-' + name + '.png';
3379 L.Icon.Default.imagePath = (function () {
3380 var scripts = document.getElementsByTagName('script'),
3381 leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3383 var i, len, src, matches, path;
3385 for (i = 0, len = scripts.length; i < len; i++) {
3386 src = scripts[i].src;
3387 matches = src.match(leafletRe);
3390 path = src.split(leafletRe)[0];
3391 return (path ? path + '/' : '') + 'images';
3398 * L.Marker is used to display clickable/draggable icons on the map.
3401 L.Marker = L.Class.extend({
3403 includes: L.Mixin.Events,
3406 icon: new L.Icon.Default(),
3417 initialize: function (latlng, options) {
3418 L.setOptions(this, options);
3419 this._latlng = L.latLng(latlng);
3422 onAdd: function (map) {
3425 map.on('viewreset', this.update, this);
3430 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3431 map.on('zoomanim', this._animateZoom, this);
3435 addTo: function (map) {
3440 onRemove: function (map) {
3441 if (this.dragging) {
3442 this.dragging.disable();
3446 this._removeShadow();
3448 this.fire('remove');
3451 'viewreset': this.update,
3452 'zoomanim': this._animateZoom
3458 getLatLng: function () {
3459 return this._latlng;
3462 setLatLng: function (latlng) {
3463 this._latlng = L.latLng(latlng);
3467 return this.fire('move', { latlng: this._latlng });
3470 setZIndexOffset: function (offset) {
3471 this.options.zIndexOffset = offset;
3477 setIcon: function (icon) {
3479 this.options.icon = icon;
3489 update: function () {
3491 var pos = this._map.latLngToLayerPoint(this._latlng).round();
3498 _initIcon: function () {
3499 var options = this.options,
3501 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3502 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3504 var icon = options.icon.createIcon(this._icon),
3507 // if we're not reusing the icon, remove the old one and init new one
3508 if (icon !== this._icon) {
3514 if (options.title) {
3515 icon.title = options.title;
3519 L.DomUtil.addClass(icon, classToAdd);
3521 if (options.keyboard) {
3522 icon.tabIndex = '0';
3527 this._initInteraction();
3529 if (options.riseOnHover) {
3531 .on(icon, 'mouseover', this._bringToFront, this)
3532 .on(icon, 'mouseout', this._resetZIndex, this);
3535 var newShadow = options.icon.createShadow(this._shadow),
3538 if (newShadow !== this._shadow) {
3539 this._removeShadow();
3543 L.DomUtil.addClass(newShadow, classToAdd);
3546 this._shadow = newShadow;
3549 if (options.opacity < 1) {
3550 this._updateOpacity();
3554 var panes = this._map._panes;
3557 panes.markerPane.appendChild(this._icon);
3560 if (newShadow && addShadow) {
3561 panes.shadowPane.appendChild(this._shadow);
3565 _removeIcon: function () {
3566 if (this.options.riseOnHover) {
3568 .off(this._icon, 'mouseover', this._bringToFront)
3569 .off(this._icon, 'mouseout', this._resetZIndex);
3572 this._map._panes.markerPane.removeChild(this._icon);
3577 _removeShadow: function () {
3579 this._map._panes.shadowPane.removeChild(this._shadow);
3581 this._shadow = null;
3584 _setPos: function (pos) {
3585 L.DomUtil.setPosition(this._icon, pos);
3588 L.DomUtil.setPosition(this._shadow, pos);
3591 this._zIndex = pos.y + this.options.zIndexOffset;
3593 this._resetZIndex();
3596 _updateZIndex: function (offset) {
3597 this._icon.style.zIndex = this._zIndex + offset;
3600 _animateZoom: function (opt) {
3601 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3606 _initInteraction: function () {
3608 if (!this.options.clickable) { return; }
3610 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3612 var icon = this._icon,
3613 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3615 L.DomUtil.addClass(icon, 'leaflet-clickable');
3616 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3617 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3619 for (var i = 0; i < events.length; i++) {
3620 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3623 if (L.Handler.MarkerDrag) {
3624 this.dragging = new L.Handler.MarkerDrag(this);
3626 if (this.options.draggable) {
3627 this.dragging.enable();
3632 _onMouseClick: function (e) {
3633 var wasDragged = this.dragging && this.dragging.moved();
3635 if (this.hasEventListeners(e.type) || wasDragged) {
3636 L.DomEvent.stopPropagation(e);
3639 if (wasDragged) { return; }
3641 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3645 latlng: this._latlng
3649 _onKeyPress: function (e) {
3650 if (e.keyCode === 13) {
3651 this.fire('click', {
3653 latlng: this._latlng
3658 _fireMouseEvent: function (e) {
3662 latlng: this._latlng
3665 // TODO proper custom event propagation
3666 // this line will always be called if marker is in a FeatureGroup
3667 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3668 L.DomEvent.preventDefault(e);
3670 if (e.type !== 'mousedown') {
3671 L.DomEvent.stopPropagation(e);
3673 L.DomEvent.preventDefault(e);
3677 setOpacity: function (opacity) {
3678 this.options.opacity = opacity;
3680 this._updateOpacity();
3684 _updateOpacity: function () {
3685 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3687 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3691 _bringToFront: function () {
3692 this._updateZIndex(this.options.riseOffset);
3695 _resetZIndex: function () {
3696 this._updateZIndex(0);
3700 L.marker = function (latlng, options) {
3701 return new L.Marker(latlng, options);
3706 * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3707 * to use with L.Marker.
3710 L.DivIcon = L.Icon.extend({
3712 iconSize: [12, 12], // also can be set through CSS
3715 popupAnchor: (Point)
3719 className: 'leaflet-div-icon',
3723 createIcon: function (oldIcon) {
3724 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3725 options = this.options;
3727 if (options.html !== false) {
3728 div.innerHTML = options.html;
3733 if (options.bgPos) {
3734 div.style.backgroundPosition =
3735 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3738 this._setIconStyles(div, 'icon');
3742 createShadow: function () {
3747 L.divIcon = function (options) {
3748 return new L.DivIcon(options);
3753 * L.Popup is used for displaying popups on the map.
3756 L.Map.mergeOptions({
3757 closePopupOnClick: true
3760 L.Popup = L.Class.extend({
3761 includes: L.Mixin.Events,
3770 autoPanPadding: [5, 5],
3776 initialize: function (options, source) {
3777 L.setOptions(this, options);
3779 this._source = source;
3780 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3781 this._isOpen = false;
3784 onAdd: function (map) {
3787 if (!this._container) {
3790 this._updateContent();
3792 var animFade = map.options.fadeAnimation;
3795 L.DomUtil.setOpacity(this._container, 0);
3797 map._panes.popupPane.appendChild(this._container);
3799 map.on(this._getEvents(), this);
3804 L.DomUtil.setOpacity(this._container, 1);
3809 map.fire('popupopen', {popup: this});
3812 this._source.fire('popupopen', {popup: this});
3816 addTo: function (map) {
3821 openOn: function (map) {
3822 map.openPopup(this);
3826 onRemove: function (map) {
3827 map._panes.popupPane.removeChild(this._container);
3829 L.Util.falseFn(this._container.offsetWidth); // force reflow
3831 map.off(this._getEvents(), this);
3833 if (map.options.fadeAnimation) {
3834 L.DomUtil.setOpacity(this._container, 0);
3841 map.fire('popupclose', {popup: this});
3844 this._source.fire('popupclose', {popup: this});
3848 setLatLng: function (latlng) {
3849 this._latlng = L.latLng(latlng);
3854 setContent: function (content) {
3855 this._content = content;
3860 _getEvents: function () {
3862 viewreset: this._updatePosition
3865 if (this._animated) {
3866 events.zoomanim = this._zoomAnimation;
3868 if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
3869 events.preclick = this._close;
3871 if (this.options.keepInView) {
3872 events.moveend = this._adjustPan;
3878 _close: function () {
3880 this._map.closePopup(this);
3884 _initLayout: function () {
3885 var prefix = 'leaflet-popup',
3886 containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
3887 (this._animated ? 'animated' : 'hide'),
3888 container = this._container = L.DomUtil.create('div', containerClass),
3891 if (this.options.closeButton) {
3892 closeButton = this._closeButton =
3893 L.DomUtil.create('a', prefix + '-close-button', container);
3894 closeButton.href = '#close';
3895 closeButton.innerHTML = '×';
3896 L.DomEvent.disableClickPropagation(closeButton);
3898 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3901 var wrapper = this._wrapper =
3902 L.DomUtil.create('div', prefix + '-content-wrapper', container);
3903 L.DomEvent.disableClickPropagation(wrapper);
3905 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3906 L.DomEvent.on(this._contentNode, 'wheel', L.DomEvent.stopPropagation);
3907 L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
3908 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3909 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3912 _update: function () {
3913 if (!this._map) { return; }
3915 this._container.style.visibility = 'hidden';
3917 this._updateContent();
3918 this._updateLayout();
3919 this._updatePosition();
3921 this._container.style.visibility = '';
3926 _updateContent: function () {
3927 if (!this._content) { return; }
3929 if (typeof this._content === 'string') {
3930 this._contentNode.innerHTML = this._content;
3932 while (this._contentNode.hasChildNodes()) {
3933 this._contentNode.removeChild(this._contentNode.firstChild);
3935 this._contentNode.appendChild(this._content);
3937 this.fire('contentupdate');
3940 _updateLayout: function () {
3941 var container = this._contentNode,
3942 style = container.style;
3945 style.whiteSpace = 'nowrap';
3947 var width = container.offsetWidth;
3948 width = Math.min(width, this.options.maxWidth);
3949 width = Math.max(width, this.options.minWidth);
3951 style.width = (width + 1) + 'px';
3952 style.whiteSpace = '';
3956 var height = container.offsetHeight,
3957 maxHeight = this.options.maxHeight,
3958 scrolledClass = 'leaflet-popup-scrolled';
3960 if (maxHeight && height > maxHeight) {
3961 style.height = maxHeight + 'px';
3962 L.DomUtil.addClass(container, scrolledClass);
3964 L.DomUtil.removeClass(container, scrolledClass);
3967 this._containerWidth = this._container.offsetWidth;
3970 _updatePosition: function () {
3971 if (!this._map) { return; }
3973 var pos = this._map.latLngToLayerPoint(this._latlng),
3974 animated = this._animated,
3975 offset = L.point(this.options.offset);
3978 L.DomUtil.setPosition(this._container, pos);
3981 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
3982 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
3984 // bottom position the popup in case the height of the popup changes (images loading etc)
3985 this._container.style.bottom = this._containerBottom + 'px';
3986 this._container.style.left = this._containerLeft + 'px';
3989 _zoomAnimation: function (opt) {
3990 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3992 L.DomUtil.setPosition(this._container, pos);
3995 _adjustPan: function () {
3996 if (!this.options.autoPan) { return; }
3998 var map = this._map,
3999 containerHeight = this._container.offsetHeight,
4000 containerWidth = this._containerWidth,
4002 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
4004 if (this._animated) {
4005 layerPos._add(L.DomUtil.getPosition(this._container));
4008 var containerPos = map.layerPointToContainerPoint(layerPos),
4009 padding = L.point(this.options.autoPanPadding),
4010 size = map.getSize(),
4014 if (containerPos.x + containerWidth > size.x) { // right
4015 dx = containerPos.x + containerWidth - size.x + padding.x;
4017 if (containerPos.x - dx < 0) { // left
4018 dx = containerPos.x - padding.x;
4020 if (containerPos.y + containerHeight > size.y) { // bottom
4021 dy = containerPos.y + containerHeight - size.y + padding.y;
4023 if (containerPos.y - dy < 0) { // top
4024 dy = containerPos.y - padding.y;
4029 .fire('autopanstart')
4034 _onCloseButtonClick: function (e) {
4040 L.popup = function (options, source) {
4041 return new L.Popup(options, source);
4046 openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
4049 if (!(popup instanceof L.Popup)) {
4050 var content = popup;
4052 popup = new L.Popup(options)
4054 .setContent(content);
4056 popup._isOpen = true;
4058 this._popup = popup;
4059 return this.addLayer(popup);
4062 closePopup: function (popup) {
4063 if (!popup || popup === this._popup) {
4064 popup = this._popup;
4068 this.removeLayer(popup);
4069 popup._isOpen = false;
4077 * Popup extension to L.Marker, adding popup-related methods.
4081 openPopup: function () {
4082 if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
4083 this._popup.setLatLng(this._latlng);
4084 this._map.openPopup(this._popup);
4090 closePopup: function () {
4092 this._popup._close();
4097 togglePopup: function () {
4099 if (this._popup._isOpen) {
4108 bindPopup: function (content, options) {
4109 var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
4111 anchor = anchor.add(L.Popup.prototype.options.offset);
4113 if (options && options.offset) {
4114 anchor = anchor.add(options.offset);
4117 options = L.extend({offset: anchor}, options);
4121 .on('click', this.togglePopup, this)
4122 .on('remove', this.closePopup, this)
4123 .on('move', this._movePopup, this);
4126 if (content instanceof L.Popup) {
4127 L.setOptions(content, options);
4128 this._popup = content;
4130 this._popup = new L.Popup(options, this)
4131 .setContent(content);
4137 setPopupContent: function (content) {
4139 this._popup.setContent(content);
4144 unbindPopup: function () {
4148 .off('click', this.togglePopup)
4149 .off('remove', this.closePopup)
4150 .off('move', this._movePopup);
4155 _movePopup: function (e) {
4156 this._popup.setLatLng(e.latlng);
4162 * L.LayerGroup is a class to combine several layers into one so that
4163 * you can manipulate the group (e.g. add/remove it) as one layer.
4166 L.LayerGroup = L.Class.extend({
4167 initialize: function (layers) {
4173 for (i = 0, len = layers.length; i < len; i++) {
4174 this.addLayer(layers[i]);
4179 addLayer: function (layer) {
4180 var id = this.getLayerId(layer);
4182 this._layers[id] = layer;
4185 this._map.addLayer(layer);
4191 removeLayer: function (layer) {
4192 var id = layer in this._layers ? layer : this.getLayerId(layer);
4194 if (this._map && this._layers[id]) {
4195 this._map.removeLayer(this._layers[id]);
4198 delete this._layers[id];
4203 hasLayer: function (layer) {
4204 if (!layer) { return false; }
4206 return (layer in this._layers || this.getLayerId(layer) in this._layers);
4209 clearLayers: function () {
4210 this.eachLayer(this.removeLayer, this);
4214 invoke: function (methodName) {
4215 var args = Array.prototype.slice.call(arguments, 1),
4218 for (i in this._layers) {
4219 layer = this._layers[i];
4221 if (layer[methodName]) {
4222 layer[methodName].apply(layer, args);
4229 onAdd: function (map) {
4231 this.eachLayer(map.addLayer, map);
4234 onRemove: function (map) {
4235 this.eachLayer(map.removeLayer, map);
4239 addTo: function (map) {
4244 eachLayer: function (method, context) {
4245 for (var i in this._layers) {
4246 method.call(context, this._layers[i]);
4251 getLayer: function (id) {
4252 return this._layers[id];
4255 getLayers: function () {
4258 for (var i in this._layers) {
4259 layers.push(this._layers[i]);
4264 setZIndex: function (zIndex) {
4265 return this.invoke('setZIndex', zIndex);
4268 getLayerId: function (layer) {
4269 return L.stamp(layer);
4273 L.layerGroup = function (layers) {
4274 return new L.LayerGroup(layers);
4279 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
4280 * shared between a group of interactive layers (like vectors or markers).
4283 L.FeatureGroup = L.LayerGroup.extend({
4284 includes: L.Mixin.Events,
4287 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
4290 addLayer: function (layer) {
4291 if (this.hasLayer(layer)) {
4295 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4297 L.LayerGroup.prototype.addLayer.call(this, layer);
4299 if (this._popupContent && layer.bindPopup) {
4300 layer.bindPopup(this._popupContent, this._popupOptions);
4303 return this.fire('layeradd', {layer: layer});
4306 removeLayer: function (layer) {
4307 if (layer in this._layers) {
4308 layer = this._layers[layer];
4311 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4313 L.LayerGroup.prototype.removeLayer.call(this, layer);
4315 if (this._popupContent) {
4316 this.invoke('unbindPopup');
4319 return this.fire('layerremove', {layer: layer});
4322 bindPopup: function (content, options) {
4323 this._popupContent = content;
4324 this._popupOptions = options;
4325 return this.invoke('bindPopup', content, options);
4328 setStyle: function (style) {
4329 return this.invoke('setStyle', style);
4332 bringToFront: function () {
4333 return this.invoke('bringToFront');
4336 bringToBack: function () {
4337 return this.invoke('bringToBack');
4340 getBounds: function () {
4341 var bounds = new L.LatLngBounds();
4343 this.eachLayer(function (layer) {
4344 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
4350 _propagateEvent: function (e) {
4356 this.fire(e.type, e);
4360 L.featureGroup = function (layers) {
4361 return new L.FeatureGroup(layers);
4366 * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
4369 L.Path = L.Class.extend({
4370 includes: [L.Mixin.Events],
4373 // how much to extend the clip area around the map view
4374 // (relative to its size, e.g. 0.5 is half the screen in each direction)
4375 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
4376 CLIP_PADDING: L.Browser.mobile ?
4377 Math.max(0, Math.min(0.5,
4378 (1280 / Math.max(window.innerWidth, window.innerHeight) - 1) / 2)) : 0.5
4389 fillColor: null, //same as color by default
4395 initialize: function (options) {
4396 L.setOptions(this, options);
4399 onAdd: function (map) {
4402 if (!this._container) {
4403 this._initElements();
4407 this.projectLatlngs();
4410 if (this._container) {
4411 this._map._pathRoot.appendChild(this._container);
4417 'viewreset': this.projectLatlngs,
4418 'moveend': this._updatePath
4422 addTo: function (map) {
4427 onRemove: function (map) {
4428 map._pathRoot.removeChild(this._container);
4430 // Need to fire remove event before we set _map to null as the event hooks might need the object
4431 this.fire('remove');
4434 if (L.Browser.vml) {
4435 this._container = null;
4436 this._stroke = null;
4441 'viewreset': this.projectLatlngs,
4442 'moveend': this._updatePath
4446 projectLatlngs: function () {
4447 // do all projection stuff here
4450 setStyle: function (style) {
4451 L.setOptions(this, style);
4453 if (this._container) {
4454 this._updateStyle();
4460 redraw: function () {
4462 this.projectLatlngs();
4470 _updatePathViewport: function () {
4471 var p = L.Path.CLIP_PADDING,
4472 size = this.getSize(),
4473 panePos = L.DomUtil.getPosition(this._mapPane),
4474 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4475 max = min.add(size.multiplyBy(1 + p * 2)._round());
4477 this._pathViewport = new L.Bounds(min, max);
4483 * Extends L.Path with SVG-specific rendering code.
4486 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4488 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4490 L.Path = L.Path.extend({
4495 bringToFront: function () {
4496 var root = this._map._pathRoot,
4497 path = this._container;
4499 if (path && root.lastChild !== path) {
4500 root.appendChild(path);
4505 bringToBack: function () {
4506 var root = this._map._pathRoot,
4507 path = this._container,
4508 first = root.firstChild;
4510 if (path && first !== path) {
4511 root.insertBefore(path, first);
4516 getPathString: function () {
4517 // form path string here
4520 _createElement: function (name) {
4521 return document.createElementNS(L.Path.SVG_NS, name);
4524 _initElements: function () {
4525 this._map._initPathRoot();
4530 _initPath: function () {
4531 this._container = this._createElement('g');
4533 this._path = this._createElement('path');
4534 this._container.appendChild(this._path);
4537 _initStyle: function () {
4538 if (this.options.stroke) {
4539 this._path.setAttribute('stroke-linejoin', 'round');
4540 this._path.setAttribute('stroke-linecap', 'round');
4542 if (this.options.fill) {
4543 this._path.setAttribute('fill-rule', 'evenodd');
4545 if (this.options.pointerEvents) {
4546 this._path.setAttribute('pointer-events', this.options.pointerEvents);
4548 if (!this.options.clickable && !this.options.pointerEvents) {
4549 this._path.setAttribute('pointer-events', 'none');
4551 this._updateStyle();
4554 _updateStyle: function () {
4555 if (this.options.stroke) {
4556 this._path.setAttribute('stroke', this.options.color);
4557 this._path.setAttribute('stroke-opacity', this.options.opacity);
4558 this._path.setAttribute('stroke-width', this.options.weight);
4559 if (this.options.dashArray) {
4560 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4562 this._path.removeAttribute('stroke-dasharray');
4565 this._path.setAttribute('stroke', 'none');
4567 if (this.options.fill) {
4568 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4569 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4571 this._path.setAttribute('fill', 'none');
4575 _updatePath: function () {
4576 var str = this.getPathString();
4578 // fix webkit empty string parsing bug
4581 this._path.setAttribute('d', str);
4584 // TODO remove duplication with L.Map
4585 _initEvents: function () {
4586 if (this.options.clickable) {
4587 if (L.Browser.svg || !L.Browser.vml) {
4588 this._path.setAttribute('class', 'leaflet-clickable');
4591 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4593 var events = ['dblclick', 'mousedown', 'mouseover',
4594 'mouseout', 'mousemove', 'contextmenu'];
4595 for (var i = 0; i < events.length; i++) {
4596 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4601 _onMouseClick: function (e) {
4602 if (this._map.dragging && this._map.dragging.moved()) { return; }
4604 this._fireMouseEvent(e);
4607 _fireMouseEvent: function (e) {
4608 if (!this.hasEventListeners(e.type)) { return; }
4610 var map = this._map,
4611 containerPoint = map.mouseEventToContainerPoint(e),
4612 layerPoint = map.containerPointToLayerPoint(containerPoint),
4613 latlng = map.layerPointToLatLng(layerPoint);
4617 layerPoint: layerPoint,
4618 containerPoint: containerPoint,
4622 if (e.type === 'contextmenu') {
4623 L.DomEvent.preventDefault(e);
4625 if (e.type !== 'mousemove') {
4626 L.DomEvent.stopPropagation(e);
4632 _initPathRoot: function () {
4633 if (!this._pathRoot) {
4634 this._pathRoot = L.Path.prototype._createElement('svg');
4635 this._panes.overlayPane.appendChild(this._pathRoot);
4637 if (this.options.zoomAnimation && L.Browser.any3d) {
4638 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
4641 'zoomanim': this._animatePathZoom,
4642 'zoomend': this._endPathZoom
4645 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
4648 this.on('moveend', this._updateSvgViewport);
4649 this._updateSvgViewport();
4653 _animatePathZoom: function (e) {
4654 var scale = this.getZoomScale(e.zoom),
4655 offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4657 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4658 L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4660 this._pathZooming = true;
4663 _endPathZoom: function () {
4664 this._pathZooming = false;
4667 _updateSvgViewport: function () {
4669 if (this._pathZooming) {
4670 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4671 // When the zoom animation ends we will be updated again anyway
4672 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4676 this._updatePathViewport();
4678 var vp = this._pathViewport,
4681 width = max.x - min.x,
4682 height = max.y - min.y,
4683 root = this._pathRoot,
4684 pane = this._panes.overlayPane;
4686 // Hack to make flicker on drag end on mobile webkit less irritating
4687 if (L.Browser.mobileWebkit) {
4688 pane.removeChild(root);
4691 L.DomUtil.setPosition(root, min);
4692 root.setAttribute('width', width);
4693 root.setAttribute('height', height);
4694 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4696 if (L.Browser.mobileWebkit) {
4697 pane.appendChild(root);
4704 * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4709 bindPopup: function (content, options) {
4711 if (content instanceof L.Popup) {
4712 this._popup = content;
4714 if (!this._popup || options) {
4715 this._popup = new L.Popup(options, this);
4717 this._popup.setContent(content);
4720 if (!this._popupHandlersAdded) {
4722 .on('click', this._openPopup, this)
4723 .on('remove', this.closePopup, this);
4725 this._popupHandlersAdded = true;
4731 unbindPopup: function () {
4735 .off('click', this._openPopup)
4736 .off('remove', this.closePopup);
4738 this._popupHandlersAdded = false;
4743 openPopup: function (latlng) {
4746 // open the popup from one of the path's points if not specified
4747 latlng = latlng || this._latlng ||
4748 this._latlngs[Math.floor(this._latlngs.length / 2)];
4750 this._openPopup({latlng: latlng});
4756 closePopup: function () {
4758 this._popup._close();
4763 _openPopup: function (e) {
4764 this._popup.setLatLng(e.latlng);
4765 this._map.openPopup(this._popup);
4771 * Vector rendering for IE6-8 through VML.
4772 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4775 L.Browser.vml = !L.Browser.svg && (function () {
4777 var div = document.createElement('div');
4778 div.innerHTML = '<v:shape adj="1"/>';
4780 var shape = div.firstChild;
4781 shape.style.behavior = 'url(#default#VML)';
4783 return shape && (typeof shape.adj === 'object');
4790 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4796 _createElement: (function () {
4798 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4799 return function (name) {
4800 return document.createElement('<lvml:' + name + ' class="lvml">');
4803 return function (name) {
4804 return document.createElement(
4805 '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4810 _initPath: function () {
4811 var container = this._container = this._createElement('shape');
4812 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4813 if (this.options.clickable) {
4814 L.DomUtil.addClass(container, 'leaflet-clickable');
4816 container.coordsize = '1 1';
4818 this._path = this._createElement('path');
4819 container.appendChild(this._path);
4821 this._map._pathRoot.appendChild(container);
4824 _initStyle: function () {
4825 this._updateStyle();
4828 _updateStyle: function () {
4829 var stroke = this._stroke,
4831 options = this.options,
4832 container = this._container;
4834 container.stroked = options.stroke;
4835 container.filled = options.fill;
4837 if (options.stroke) {
4839 stroke = this._stroke = this._createElement('stroke');
4840 stroke.endcap = 'round';
4841 container.appendChild(stroke);
4843 stroke.weight = options.weight + 'px';
4844 stroke.color = options.color;
4845 stroke.opacity = options.opacity;
4847 if (options.dashArray) {
4848 stroke.dashStyle = options.dashArray instanceof Array ?
4849 options.dashArray.join(' ') :
4850 options.dashArray.replace(/( *, *)/g, ' ');
4852 stroke.dashStyle = '';
4855 } else if (stroke) {
4856 container.removeChild(stroke);
4857 this._stroke = null;
4862 fill = this._fill = this._createElement('fill');
4863 container.appendChild(fill);
4865 fill.color = options.fillColor || options.color;
4866 fill.opacity = options.fillOpacity;
4869 container.removeChild(fill);
4874 _updatePath: function () {
4875 var style = this._container.style;
4877 style.display = 'none';
4878 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4883 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4884 _initPathRoot: function () {
4885 if (this._pathRoot) { return; }
4887 var root = this._pathRoot = document.createElement('div');
4888 root.className = 'leaflet-vml-container';
4889 this._panes.overlayPane.appendChild(root);
4891 this.on('moveend', this._updatePathViewport);
4892 this._updatePathViewport();
4898 * Vector rendering for all browsers that support canvas.
4901 L.Browser.canvas = (function () {
4902 return !!document.createElement('canvas').getContext;
4905 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4907 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4912 redraw: function () {
4914 this.projectLatlngs();
4915 this._requestUpdate();
4920 setStyle: function (style) {
4921 L.setOptions(this, style);
4924 this._updateStyle();
4925 this._requestUpdate();
4930 onRemove: function (map) {
4932 .off('viewreset', this.projectLatlngs, this)
4933 .off('moveend', this._updatePath, this);
4935 if (this.options.clickable) {
4936 this._map.off('click', this._onClick, this);
4937 this._map.off('mousemove', this._onMouseMove, this);
4940 this._requestUpdate();
4945 _requestUpdate: function () {
4946 if (this._map && !L.Path._updateRequest) {
4947 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4951 _fireMapMoveEnd: function () {
4952 L.Path._updateRequest = null;
4953 this.fire('moveend');
4956 _initElements: function () {
4957 this._map._initPathRoot();
4958 this._ctx = this._map._canvasCtx;
4961 _updateStyle: function () {
4962 var options = this.options;
4964 if (options.stroke) {
4965 this._ctx.lineWidth = options.weight;
4966 this._ctx.strokeStyle = options.color;
4969 this._ctx.fillStyle = options.fillColor || options.color;
4973 _drawPath: function () {
4974 var i, j, len, len2, point, drawMethod;
4976 this._ctx.beginPath();
4978 for (i = 0, len = this._parts.length; i < len; i++) {
4979 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4980 point = this._parts[i][j];
4981 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4983 this._ctx[drawMethod](point.x, point.y);
4985 // TODO refactor ugly hack
4986 if (this instanceof L.Polygon) {
4987 this._ctx.closePath();
4992 _checkIfEmpty: function () {
4993 return !this._parts.length;
4996 _updatePath: function () {
4997 if (this._checkIfEmpty()) { return; }
4999 var ctx = this._ctx,
5000 options = this.options;
5004 this._updateStyle();
5007 ctx.globalAlpha = options.fillOpacity;
5011 if (options.stroke) {
5012 ctx.globalAlpha = options.opacity;
5018 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
5021 _initEvents: function () {
5022 if (this.options.clickable) {
5024 this._map.on('mousemove', this._onMouseMove, this);
5025 this._map.on('click', this._onClick, this);
5029 _onClick: function (e) {
5030 if (this._containsPoint(e.layerPoint)) {
5031 this.fire('click', e);
5035 _onMouseMove: function (e) {
5036 if (!this._map || this._map._animatingZoom) { return; }
5038 // TODO don't do on each move
5039 if (this._containsPoint(e.layerPoint)) {
5040 this._ctx.canvas.style.cursor = 'pointer';
5041 this._mouseInside = true;
5042 this.fire('mouseover', e);
5044 } else if (this._mouseInside) {
5045 this._ctx.canvas.style.cursor = '';
5046 this._mouseInside = false;
5047 this.fire('mouseout', e);
5052 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
5053 _initPathRoot: function () {
5054 var root = this._pathRoot,
5058 root = this._pathRoot = document.createElement('canvas');
5059 root.style.position = 'absolute';
5060 ctx = this._canvasCtx = root.getContext('2d');
5062 ctx.lineCap = 'round';
5063 ctx.lineJoin = 'round';
5065 this._panes.overlayPane.appendChild(root);
5067 if (this.options.zoomAnimation) {
5068 this._pathRoot.className = 'leaflet-zoom-animated';
5069 this.on('zoomanim', this._animatePathZoom);
5070 this.on('zoomend', this._endPathZoom);
5072 this.on('moveend', this._updateCanvasViewport);
5073 this._updateCanvasViewport();
5077 _updateCanvasViewport: function () {
5078 // don't redraw while zooming. See _updateSvgViewport for more details
5079 if (this._pathZooming) { return; }
5080 this._updatePathViewport();
5082 var vp = this._pathViewport,
5084 size = vp.max.subtract(min),
5085 root = this._pathRoot;
5087 //TODO check if this works properly on mobile webkit
5088 L.DomUtil.setPosition(root, min);
5089 root.width = size.x;
5090 root.height = size.y;
5091 root.getContext('2d').translate(-min.x, -min.y);
5097 * L.LineUtil contains different utility functions for line segments
5098 * and polylines (clipping, simplification, distances, etc.)
5101 /*jshint bitwise:false */ // allow bitwise oprations for this file
5105 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
5106 // Improves rendering performance dramatically by lessening the number of points to draw.
5108 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
5109 if (!tolerance || !points.length) {
5110 return points.slice();
5113 var sqTolerance = tolerance * tolerance;
5115 // stage 1: vertex reduction
5116 points = this._reducePoints(points, sqTolerance);
5118 // stage 2: Douglas-Peucker simplification
5119 points = this._simplifyDP(points, sqTolerance);
5124 // distance from a point to a segment between two points
5125 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5126 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
5129 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5130 return this._sqClosestPointOnSegment(p, p1, p2);
5133 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
5134 _simplifyDP: function (points, sqTolerance) {
5136 var len = points.length,
5137 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
5138 markers = new ArrayConstructor(len);
5140 markers[0] = markers[len - 1] = 1;
5142 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
5147 for (i = 0; i < len; i++) {
5149 newPoints.push(points[i]);
5156 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
5161 for (i = first + 1; i <= last - 1; i++) {
5162 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
5164 if (sqDist > maxSqDist) {
5170 if (maxSqDist > sqTolerance) {
5173 this._simplifyDPStep(points, markers, sqTolerance, first, index);
5174 this._simplifyDPStep(points, markers, sqTolerance, index, last);
5178 // reduce points that are too close to each other to a single point
5179 _reducePoints: function (points, sqTolerance) {
5180 var reducedPoints = [points[0]];
5182 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
5183 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
5184 reducedPoints.push(points[i]);
5188 if (prev < len - 1) {
5189 reducedPoints.push(points[len - 1]);
5191 return reducedPoints;
5194 // Cohen-Sutherland line clipping algorithm.
5195 // Used to avoid rendering parts of a polyline that are not currently visible.
5197 clipSegment: function (a, b, bounds, useLastCode) {
5198 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
5199 codeB = this._getBitCode(b, bounds),
5201 codeOut, p, newCode;
5203 // save 2nd code to avoid calculating it on the next segment
5204 this._lastCode = codeB;
5207 // if a,b is inside the clip window (trivial accept)
5208 if (!(codeA | codeB)) {
5210 // if a,b is outside the clip window (trivial reject)
5211 } else if (codeA & codeB) {
5215 codeOut = codeA || codeB;
5216 p = this._getEdgeIntersection(a, b, codeOut, bounds);
5217 newCode = this._getBitCode(p, bounds);
5219 if (codeOut === codeA) {
5230 _getEdgeIntersection: function (a, b, code, bounds) {
5236 if (code & 8) { // top
5237 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
5238 } else if (code & 4) { // bottom
5239 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
5240 } else if (code & 2) { // right
5241 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
5242 } else if (code & 1) { // left
5243 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
5247 _getBitCode: function (/*Point*/ p, bounds) {
5250 if (p.x < bounds.min.x) { // left
5252 } else if (p.x > bounds.max.x) { // right
5255 if (p.y < bounds.min.y) { // bottom
5257 } else if (p.y > bounds.max.y) { // top
5264 // square distance (to avoid unnecessary Math.sqrt calls)
5265 _sqDist: function (p1, p2) {
5266 var dx = p2.x - p1.x,
5268 return dx * dx + dy * dy;
5271 // return closest point on segment or distance to that point
5272 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
5277 dot = dx * dx + dy * dy,
5281 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
5295 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
5301 * L.Polyline is used to display polylines on a map.
5304 L.Polyline = L.Path.extend({
5305 initialize: function (latlngs, options) {
5306 L.Path.prototype.initialize.call(this, options);
5308 this._latlngs = this._convertLatLngs(latlngs);
5312 // how much to simplify the polyline on each zoom level
5313 // more = better performance and smoother look, less = more accurate
5318 projectLatlngs: function () {
5319 this._originalPoints = [];
5321 for (var i = 0, len = this._latlngs.length; i < len; i++) {
5322 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
5326 getPathString: function () {
5327 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
5328 str += this._getPathPartStr(this._parts[i]);
5333 getLatLngs: function () {
5334 return this._latlngs;
5337 setLatLngs: function (latlngs) {
5338 this._latlngs = this._convertLatLngs(latlngs);
5339 return this.redraw();
5342 addLatLng: function (latlng) {
5343 this._latlngs.push(L.latLng(latlng));
5344 return this.redraw();
5347 spliceLatLngs: function () { // (Number index, Number howMany)
5348 var removed = [].splice.apply(this._latlngs, arguments);
5349 this._convertLatLngs(this._latlngs, true);
5354 closestLayerPoint: function (p) {
5355 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
5357 for (var j = 0, jLen = parts.length; j < jLen; j++) {
5358 var points = parts[j];
5359 for (var i = 1, len = points.length; i < len; i++) {
5362 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
5363 if (sqDist < minDistance) {
5364 minDistance = sqDist;
5365 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
5370 minPoint.distance = Math.sqrt(minDistance);
5375 getBounds: function () {
5376 return new L.LatLngBounds(this.getLatLngs());
5379 _convertLatLngs: function (latlngs, overwrite) {
5380 var i, len, target = overwrite ? latlngs : [];
5382 for (i = 0, len = latlngs.length; i < len; i++) {
5383 if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
5386 target[i] = L.latLng(latlngs[i]);
5391 _initEvents: function () {
5392 L.Path.prototype._initEvents.call(this);
5395 _getPathPartStr: function (points) {
5396 var round = L.Path.VML;
5398 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
5403 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
5408 _clipPoints: function () {
5409 var points = this._originalPoints,
5410 len = points.length,
5413 if (this.options.noClip) {
5414 this._parts = [points];
5420 var parts = this._parts,
5421 vp = this._map._pathViewport,
5424 for (i = 0, k = 0; i < len - 1; i++) {
5425 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
5430 parts[k] = parts[k] || [];
5431 parts[k].push(segment[0]);
5433 // if segment goes out of screen, or it's the last one, it's the end of the line part
5434 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
5435 parts[k].push(segment[1]);
5441 // simplify each clipped part of the polyline
5442 _simplifyPoints: function () {
5443 var parts = this._parts,
5446 for (var i = 0, len = parts.length; i < len; i++) {
5447 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
5451 _updatePath: function () {
5452 if (!this._map) { return; }
5455 this._simplifyPoints();
5457 L.Path.prototype._updatePath.call(this);
5461 L.polyline = function (latlngs, options) {
5462 return new L.Polyline(latlngs, options);
5467 * L.PolyUtil contains utility functions for polygons (clipping, etc.).
5470 /*jshint bitwise:false */ // allow bitwise operations here
5475 * Sutherland-Hodgeman polygon clipping algorithm.
5476 * Used to avoid rendering parts of a polygon that are not currently visible.
5478 L.PolyUtil.clipPolygon = function (points, bounds) {
5480 edges = [1, 4, 2, 8],
5486 for (i = 0, len = points.length; i < len; i++) {
5487 points[i]._code = lu._getBitCode(points[i], bounds);
5490 // for each edge (left, bottom, right, top)
5491 for (k = 0; k < 4; k++) {
5495 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5499 // if a is inside the clip window
5500 if (!(a._code & edge)) {
5501 // if b is outside the clip window (a->b goes out of screen)
5502 if (b._code & edge) {
5503 p = lu._getEdgeIntersection(b, a, edge, bounds);
5504 p._code = lu._getBitCode(p, bounds);
5505 clippedPoints.push(p);
5507 clippedPoints.push(a);
5509 // else if b is inside the clip window (a->b enters the screen)
5510 } else if (!(b._code & edge)) {
5511 p = lu._getEdgeIntersection(b, a, edge, bounds);
5512 p._code = lu._getBitCode(p, bounds);
5513 clippedPoints.push(p);
5516 points = clippedPoints;
5524 * L.Polygon is used to display polygons on a map.
5527 L.Polygon = L.Polyline.extend({
5532 initialize: function (latlngs, options) {
5535 L.Polyline.prototype.initialize.call(this, latlngs, options);
5537 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5538 this._latlngs = this._convertLatLngs(latlngs[0]);
5539 this._holes = latlngs.slice(1);
5541 for (i = 0, len = this._holes.length; i < len; i++) {
5542 hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
5543 if (hole[0].equals(hole[hole.length - 1])) {
5549 // filter out last point if its equal to the first one
5550 latlngs = this._latlngs;
5552 if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
5557 projectLatlngs: function () {
5558 L.Polyline.prototype.projectLatlngs.call(this);
5560 // project polygon holes points
5561 // TODO move this logic to Polyline to get rid of duplication
5562 this._holePoints = [];
5564 if (!this._holes) { return; }
5566 var i, j, len, len2;
5568 for (i = 0, len = this._holes.length; i < len; i++) {
5569 this._holePoints[i] = [];
5571 for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5572 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5577 _clipPoints: function () {
5578 var points = this._originalPoints,
5581 this._parts = [points].concat(this._holePoints);
5583 if (this.options.noClip) { return; }
5585 for (var i = 0, len = this._parts.length; i < len; i++) {
5586 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5587 if (clipped.length) {
5588 newParts.push(clipped);
5592 this._parts = newParts;
5595 _getPathPartStr: function (points) {
5596 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5597 return str + (L.Browser.svg ? 'z' : 'x');
5601 L.polygon = function (latlngs, options) {
5602 return new L.Polygon(latlngs, options);
5607 * Contains L.MultiPolyline and L.MultiPolygon layers.
5611 function createMulti(Klass) {
5613 return L.FeatureGroup.extend({
5615 initialize: function (latlngs, options) {
5617 this._options = options;
5618 this.setLatLngs(latlngs);
5621 setLatLngs: function (latlngs) {
5623 len = latlngs.length;
5625 this.eachLayer(function (layer) {
5627 layer.setLatLngs(latlngs[i++]);
5629 this.removeLayer(layer);
5634 this.addLayer(new Klass(latlngs[i++], this._options));
5642 L.MultiPolyline = createMulti(L.Polyline);
5643 L.MultiPolygon = createMulti(L.Polygon);
5645 L.multiPolyline = function (latlngs, options) {
5646 return new L.MultiPolyline(latlngs, options);
5649 L.multiPolygon = function (latlngs, options) {
5650 return new L.MultiPolygon(latlngs, options);
5656 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5659 L.Rectangle = L.Polygon.extend({
5660 initialize: function (latLngBounds, options) {
5661 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5664 setBounds: function (latLngBounds) {
5665 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5668 _boundsToLatLngs: function (latLngBounds) {
5669 latLngBounds = L.latLngBounds(latLngBounds);
5671 latLngBounds.getSouthWest(),
5672 latLngBounds.getNorthWest(),
5673 latLngBounds.getNorthEast(),
5674 latLngBounds.getSouthEast()
5679 L.rectangle = function (latLngBounds, options) {
5680 return new L.Rectangle(latLngBounds, options);
5685 * L.Circle is a circle overlay (with a certain radius in meters).
5688 L.Circle = L.Path.extend({
5689 initialize: function (latlng, radius, options) {
5690 L.Path.prototype.initialize.call(this, options);
5692 this._latlng = L.latLng(latlng);
5693 this._mRadius = radius;
5700 setLatLng: function (latlng) {
5701 this._latlng = L.latLng(latlng);
5702 return this.redraw();
5705 setRadius: function (radius) {
5706 this._mRadius = radius;
5707 return this.redraw();
5710 projectLatlngs: function () {
5711 var lngRadius = this._getLngRadius(),
5712 latlng = this._latlng,
5713 pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
5715 this._point = this._map.latLngToLayerPoint(latlng);
5716 this._radius = Math.max(this._point.x - pointLeft.x, 1);
5719 getBounds: function () {
5720 var lngRadius = this._getLngRadius(),
5721 latRadius = (this._mRadius / 40075017) * 360,
5722 latlng = this._latlng;
5724 return new L.LatLngBounds(
5725 [latlng.lat - latRadius, latlng.lng - lngRadius],
5726 [latlng.lat + latRadius, latlng.lng + lngRadius]);
5729 getLatLng: function () {
5730 return this._latlng;
5733 getPathString: function () {
5734 var p = this._point,
5737 if (this._checkIfEmpty()) {
5741 if (L.Browser.svg) {
5742 return 'M' + p.x + ',' + (p.y - r) +
5743 'A' + r + ',' + r + ',0,1,1,' +
5744 (p.x - 0.1) + ',' + (p.y - r) + ' z';
5748 return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
5752 getRadius: function () {
5753 return this._mRadius;
5756 // TODO Earth hardcoded, move into projection code!
5758 _getLatRadius: function () {
5759 return (this._mRadius / 40075017) * 360;
5762 _getLngRadius: function () {
5763 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5766 _checkIfEmpty: function () {
5770 var vp = this._map._pathViewport,
5774 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5775 p.x + r < vp.min.x || p.y + r < vp.min.y;
5779 L.circle = function (latlng, radius, options) {
5780 return new L.Circle(latlng, radius, options);
5785 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5788 L.CircleMarker = L.Circle.extend({
5794 initialize: function (latlng, options) {
5795 L.Circle.prototype.initialize.call(this, latlng, null, options);
5796 this._radius = this.options.radius;
5799 projectLatlngs: function () {
5800 this._point = this._map.latLngToLayerPoint(this._latlng);
5803 _updateStyle : function () {
5804 L.Circle.prototype._updateStyle.call(this);
5805 this.setRadius(this.options.radius);
5808 setRadius: function (radius) {
5809 this.options.radius = this._radius = radius;
5810 return this.redraw();
5814 L.circleMarker = function (latlng, options) {
5815 return new L.CircleMarker(latlng, options);
5820 * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
5823 L.Polyline.include(!L.Path.CANVAS ? {} : {
5824 _containsPoint: function (p, closed) {
5825 var i, j, k, len, len2, dist, part,
5826 w = this.options.weight / 2;
5828 if (L.Browser.touch) {
5829 w += 10; // polyline click tolerance on touch devices
5832 for (i = 0, len = this._parts.length; i < len; i++) {
5833 part = this._parts[i];
5834 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5835 if (!closed && (j === 0)) {
5839 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5852 * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
5855 L.Polygon.include(!L.Path.CANVAS ? {} : {
5856 _containsPoint: function (p) {
5862 // TODO optimization: check if within bounds first
5864 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5865 // click on polygon border
5869 // ray casting algorithm for detecting if point is in polygon
5871 for (i = 0, len = this._parts.length; i < len; i++) {
5872 part = this._parts[i];
5874 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5878 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5879 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5891 * Extends L.Circle with Canvas-specific code.
5894 L.Circle.include(!L.Path.CANVAS ? {} : {
5895 _drawPath: function () {
5896 var p = this._point;
5897 this._ctx.beginPath();
5898 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5901 _containsPoint: function (p) {
5902 var center = this._point,
5903 w2 = this.options.stroke ? this.options.weight / 2 : 0;
5905 return (p.distanceTo(center) <= this._radius + w2);
5911 * CircleMarker canvas specific drawing parts.
5914 L.CircleMarker.include(!L.Path.CANVAS ? {} : {
5915 _updateStyle: function () {
5916 L.Path.prototype._updateStyle.call(this);
5922 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
5925 L.GeoJSON = L.FeatureGroup.extend({
5927 initialize: function (geojson, options) {
5928 L.setOptions(this, options);
5933 this.addData(geojson);
5937 addData: function (geojson) {
5938 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
5942 for (i = 0, len = features.length; i < len; i++) {
5943 // Only add this if geometry or geometries are set and not null
5944 if (features[i].geometries || features[i].geometry || features[i].features) {
5945 this.addData(features[i]);
5951 var options = this.options;
5953 if (options.filter && !options.filter(geojson)) { return; }
5955 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng);
5956 layer.feature = L.GeoJSON.asFeature(geojson);
5958 layer.defaultOptions = layer.options;
5959 this.resetStyle(layer);
5961 if (options.onEachFeature) {
5962 options.onEachFeature(geojson, layer);
5965 return this.addLayer(layer);
5968 resetStyle: function (layer) {
5969 var style = this.options.style;
5971 // reset any custom styles
5972 L.Util.extend(layer.options, layer.defaultOptions);
5974 this._setLayerStyle(layer, style);
5978 setStyle: function (style) {
5979 this.eachLayer(function (layer) {
5980 this._setLayerStyle(layer, style);
5984 _setLayerStyle: function (layer, style) {
5985 if (typeof style === 'function') {
5986 style = style(layer.feature);
5988 if (layer.setStyle) {
5989 layer.setStyle(style);
5994 L.extend(L.GeoJSON, {
5995 geometryToLayer: function (geojson, pointToLayer, coordsToLatLng) {
5996 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
5997 coords = geometry.coordinates,
5999 latlng, latlngs, i, len, layer;
6001 coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
6003 switch (geometry.type) {
6005 latlng = coordsToLatLng(coords);
6006 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6009 for (i = 0, len = coords.length; i < len; i++) {
6010 latlng = coordsToLatLng(coords[i]);
6011 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6014 return new L.FeatureGroup(layers);
6017 latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
6018 return new L.Polyline(latlngs);
6021 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6022 return new L.Polygon(latlngs);
6024 case 'MultiLineString':
6025 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6026 return new L.MultiPolyline(latlngs);
6028 case 'MultiPolygon':
6029 latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
6030 return new L.MultiPolygon(latlngs);
6032 case 'GeometryCollection':
6033 for (i = 0, len = geometry.geometries.length; i < len; i++) {
6035 layer = this.geometryToLayer({
6036 geometry: geometry.geometries[i],
6038 properties: geojson.properties
6039 }, pointToLayer, coordsToLatLng);
6043 return new L.FeatureGroup(layers);
6046 throw new Error('Invalid GeoJSON object.');
6050 coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
6051 return new L.LatLng(coords[1], coords[0]);
6054 coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
6058 for (i = 0, len = coords.length; i < len; i++) {
6059 latlng = levelsDeep ?
6060 this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
6061 (coordsToLatLng || this.coordsToLatLng)(coords[i]);
6063 latlngs.push(latlng);
6069 latLngToCoords: function (latLng) {
6070 return [latLng.lng, latLng.lat];
6073 latLngsToCoords: function (latLngs) {
6076 for (var i = 0, len = latLngs.length; i < len; i++) {
6077 coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
6083 getFeature: function (layer, newGeometry) {
6084 return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
6087 asFeature: function (geoJSON) {
6088 if (geoJSON.type === 'Feature') {
6100 var PointToGeoJSON = {
6101 toGeoJSON: function () {
6102 return L.GeoJSON.getFeature(this, {
6104 coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
6109 L.Marker.include(PointToGeoJSON);
6110 L.Circle.include(PointToGeoJSON);
6111 L.CircleMarker.include(PointToGeoJSON);
6113 L.Polyline.include({
6114 toGeoJSON: function () {
6115 return L.GeoJSON.getFeature(this, {
6117 coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
6123 toGeoJSON: function () {
6124 var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
6127 coords[0].push(coords[0][0]);
6130 for (i = 0, len = this._holes.length; i < len; i++) {
6131 hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
6137 return L.GeoJSON.getFeature(this, {
6145 function includeMulti(Klass, type) {
6147 toGeoJSON: function () {
6150 this.eachLayer(function (layer) {
6151 coords.push(layer.toGeoJSON().geometry.coordinates);
6154 return L.GeoJSON.getFeature(this, {
6162 includeMulti(L.MultiPolyline, 'MultiLineString');
6163 includeMulti(L.MultiPolygon, 'MultiPolygon');
6166 L.LayerGroup.include({
6167 toGeoJSON: function () {
6170 this.eachLayer(function (layer) {
6171 if (layer.toGeoJSON) {
6172 features.push(L.GeoJSON.asFeature(layer.toGeoJSON()));
6177 type: 'FeatureCollection',
6183 L.geoJson = function (geojson, options) {
6184 return new L.GeoJSON(geojson, options);
6189 * L.DomEvent contains functions for working with DOM events.
6194 'onwheel' in document ? 'wheel' :
6195 'onmousewheel' in document ? 'mousewheel' :
6196 'MozMousePixelScroll',
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 (type === 'wheel' || type === 'mousewheel') {
6219 type = L.DomEvent.WHEEL;
6222 if ('addEventListener' in obj) {
6224 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 (type === 'wheel' || type === 'mousewheel') {
6265 type = L.DomEvent.WHEEL;
6268 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
6269 this.removeMsTouchListener(obj, type, id);
6270 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
6271 this.removeDoubleTapListener(obj, id);
6273 } else if ('removeEventListener' in obj) {
6275 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 body = document.body,
6328 docEl = document.documentElement,
6329 x = e.pageX ? e.pageX : e.clientX + body.scrollLeft + docEl.scrollLeft,
6330 y = e.pageY ? e.pageY : e.clientY + body.scrollTop + docEl.scrollTop,
6331 pos = new L.Point(x, y);
6333 return (container ? pos._subtract(L.DomUtil.getViewportOffset(container)) : pos);
6336 getWheelDelta: function (e) {
6339 if (e.type === 'wheel') {
6340 delta = -e.deltaY / (e.deltaMode ? 1 : 120);
6341 } else if (e.type === 'mousewheel') {
6342 delta = e.wheelDelta / 120;
6343 } else if (e.type === 'MozMousePixelScroll') {
6350 _fakeStop: function stop(e) {
6351 // fakes stopPropagation by setting a special event flag checked in Map mouse events handler
6352 // jshint camelcase: false
6353 e._leaflet_stop = true;
6356 // check if element really left/entered the event target (for mouseenter/mouseleave)
6357 _checkMouse: function (el, e) {
6359 var related = e.relatedTarget;
6361 if (!related) { return true; }
6364 while (related && (related !== el)) {
6365 related = related.parentNode;
6370 return (related !== el);
6373 _getEvent: function () { // evil magic for IE
6374 /*jshint noarg:false */
6375 var e = window.event;
6377 var caller = arguments.callee.caller;
6379 e = caller['arguments'][0];
6380 if (e && window.Event === e.constructor) {
6383 caller = caller.caller;
6389 // this is a horrible workaround for a bug in Android where a single touch triggers two click events
6390 _filterClick: function (e, handler) {
6391 var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
6392 elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
6394 // are they closer together than 1000ms yet more than 100ms?
6395 // Android typically triggers them ~300ms apart while multiple listeners
6396 // on the same event should be triggered far faster;
6397 // or check if click is simulated on the element, and if it is, reject any non-simulated events
6399 if ((elapsed && elapsed > 100 && elapsed < 1000) || (e.target._simulatedClick && !e._simulated)) {
6403 L.DomEvent._lastClick = timeStamp;
6409 L.DomEvent.on = L.DomEvent.addListener;
6410 L.DomEvent.off = L.DomEvent.removeListener;
6414 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
6417 L.Draggable = L.Class.extend({
6418 includes: L.Mixin.Events,
6421 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
6423 mousedown: 'mouseup',
6424 touchstart: 'touchend',
6425 MSPointerDown: 'touchend'
6428 mousedown: 'mousemove',
6429 touchstart: 'touchmove',
6430 MSPointerDown: 'touchmove'
6434 initialize: function (element, dragStartTarget) {
6435 this._element = element;
6436 this._dragStartTarget = dragStartTarget || element;
6439 enable: function () {
6440 if (this._enabled) { return; }
6442 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6443 L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6446 this._enabled = true;
6449 disable: function () {
6450 if (!this._enabled) { return; }
6452 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6453 L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6456 this._enabled = false;
6457 this._moved = false;
6460 _onDown: function (e) {
6461 if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
6464 .stopPropagation(e);
6466 if (L.Draggable._disabled) { return; }
6468 L.DomUtil.disableImageDrag();
6470 var first = e.touches ? e.touches[0] : e,
6473 // if touching a link, highlight it
6474 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
6475 L.DomUtil.addClass(el, 'leaflet-active');
6478 this._moved = false;
6480 if (this._moving) { return; }
6482 this._startPoint = new L.Point(first.clientX, first.clientY);
6483 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
6486 .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
6487 .on(document, L.Draggable.END[e.type], this._onUp, this);
6490 _onMove: function (e) {
6491 if (e.touches && e.touches.length > 1) { return; }
6493 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
6494 newPoint = new L.Point(first.clientX, first.clientY),
6495 offset = newPoint.subtract(this._startPoint);
6497 if (!offset.x && !offset.y) { return; }
6499 L.DomEvent.preventDefault(e);
6502 this.fire('dragstart');
6505 this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
6507 if (!L.Browser.touch) {
6508 L.DomUtil.disableTextSelection();
6509 L.DomUtil.addClass(document.body, 'leaflet-dragging');
6513 this._newPos = this._startPos.add(offset);
6514 this._moving = true;
6516 L.Util.cancelAnimFrame(this._animRequest);
6517 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
6520 _updatePosition: function () {
6521 this.fire('predrag');
6522 L.DomUtil.setPosition(this._element, this._newPos);
6526 _onUp: function () {
6527 if (!L.Browser.touch) {
6528 L.DomUtil.enableTextSelection();
6529 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
6532 for (var i in L.Draggable.MOVE) {
6534 .off(document, L.Draggable.MOVE[i], this._onMove)
6535 .off(document, L.Draggable.END[i], this._onUp);
6538 L.DomUtil.enableImageDrag();
6541 // ensure drag is not fired after dragend
6542 L.Util.cancelAnimFrame(this._animRequest);
6544 this.fire('dragend');
6547 this._moving = false;
6553 L.Handler is a base class for handler classes that are used internally to inject
6554 interaction features like dragging to classes like Map and Marker.
6557 L.Handler = L.Class.extend({
6558 initialize: function (map) {
6562 enable: function () {
6563 if (this._enabled) { return; }
6565 this._enabled = true;
6569 disable: function () {
6570 if (!this._enabled) { return; }
6572 this._enabled = false;
6576 enabled: function () {
6577 return !!this._enabled;
6583 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
6586 L.Map.mergeOptions({
6589 inertia: !L.Browser.android23,
6590 inertiaDeceleration: 3400, // px/s^2
6591 inertiaMaxSpeed: Infinity, // px/s
6592 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
6593 easeLinearity: 0.25,
6595 // TODO refactor, move to CRS
6596 worldCopyJump: false
6599 L.Map.Drag = L.Handler.extend({
6600 addHooks: function () {
6601 if (!this._draggable) {
6602 var map = this._map;
6604 this._draggable = new L.Draggable(map._mapPane, map._container);
6606 this._draggable.on({
6607 'dragstart': this._onDragStart,
6608 'drag': this._onDrag,
6609 'dragend': this._onDragEnd
6612 if (map.options.worldCopyJump) {
6613 this._draggable.on('predrag', this._onPreDrag, this);
6614 map.on('viewreset', this._onViewReset, this);
6617 this._draggable.enable();
6620 removeHooks: function () {
6621 this._draggable.disable();
6624 moved: function () {
6625 return this._draggable && this._draggable._moved;
6628 _onDragStart: function () {
6629 var map = this._map;
6632 map._panAnim.stop();
6639 if (map.options.inertia) {
6640 this._positions = [];
6645 _onDrag: function () {
6646 if (this._map.options.inertia) {
6647 var time = this._lastTime = +new Date(),
6648 pos = this._lastPos = this._draggable._newPos;
6650 this._positions.push(pos);
6651 this._times.push(time);
6653 if (time - this._times[0] > 200) {
6654 this._positions.shift();
6655 this._times.shift();
6664 _onViewReset: function () {
6665 // TODO fix hardcoded Earth values
6666 var pxCenter = this._map.getSize()._divideBy(2),
6667 pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
6669 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6670 this._worldWidth = this._map.project([0, 180]).x;
6673 _onPreDrag: function () {
6674 // TODO refactor to be able to adjust map pane position after zoom
6675 var worldWidth = this._worldWidth,
6676 halfWidth = Math.round(worldWidth / 2),
6677 dx = this._initialWorldOffset,
6678 x = this._draggable._newPos.x,
6679 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6680 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6681 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6683 this._draggable._newPos.x = newX;
6686 _onDragEnd: function () {
6687 var map = this._map,
6688 options = map.options,
6689 delay = +new Date() - this._lastTime,
6691 noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6693 map.fire('dragend');
6696 map.fire('moveend');
6700 var direction = this._lastPos.subtract(this._positions[0]),
6701 duration = (this._lastTime + delay - this._times[0]) / 1000,
6702 ease = options.easeLinearity,
6704 speedVector = direction.multiplyBy(ease / duration),
6705 speed = speedVector.distanceTo([0, 0]),
6707 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6708 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6710 decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6711 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6713 if (!offset.x || !offset.y) {
6714 map.fire('moveend');
6717 L.Util.requestAnimFrame(function () {
6719 duration: decelerationDuration,
6720 easeLinearity: ease,
6729 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6733 * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6736 L.Map.mergeOptions({
6737 doubleClickZoom: true
6740 L.Map.DoubleClickZoom = L.Handler.extend({
6741 addHooks: function () {
6742 this._map.on('dblclick', this._onDoubleClick);
6745 removeHooks: function () {
6746 this._map.off('dblclick', this._onDoubleClick);
6749 _onDoubleClick: function (e) {
6750 this.setZoomAround(e.containerPoint, this._zoom + 1);
6754 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
6758 * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
6761 L.Map.mergeOptions({
6762 scrollWheelZoom: true
6765 L.Map.ScrollWheelZoom = L.Handler.extend({
6766 addHooks: function () {
6767 L.DomEvent.on(this._map._container, 'wheel', this._onWheelScroll, this);
6771 removeHooks: function () {
6772 L.DomEvent.off(this._map._container, 'wheel', this._onWheelScroll);
6775 _onWheelScroll: function (e) {
6776 var delta = L.DomEvent.getWheelDelta(e);
6778 this._delta += delta;
6779 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
6781 if (!this._startTime) {
6782 this._startTime = +new Date();
6785 var left = Math.max(40 - (+new Date() - this._startTime), 0);
6787 clearTimeout(this._timer);
6788 this._timer = setTimeout(L.bind(this._performZoom, this), left);
6790 L.DomEvent.preventDefault(e);
6791 L.DomEvent.stopPropagation(e);
6794 _performZoom: function () {
6795 var map = this._map,
6796 delta = this._delta,
6797 zoom = map.getZoom();
6799 delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
6800 delta = Math.max(Math.min(delta, 4), -4);
6801 delta = map._limitZoom(zoom + delta) - zoom;
6804 this._startTime = null;
6806 if (!delta) { return; }
6808 map.setZoomAround(this._lastMousePos, zoom + delta);
6812 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
6816 * Extends the event handling code with double tap support for mobile browsers.
6819 L.extend(L.DomEvent, {
6821 _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
6822 _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
6824 // inspired by Zepto touch code by Thomas Fuchs
6825 addDoubleTapListener: function (obj, handler, id) {
6831 touchstart = this._touchstart,
6832 touchend = this._touchend,
6833 trackedTouches = [];
6835 function onTouchStart(e) {
6838 if (L.Browser.msTouch) {
6839 trackedTouches.push(e.pointerId);
6840 count = trackedTouches.length;
6842 count = e.touches.length;
6848 var now = Date.now(),
6849 delta = now - (last || now);
6851 touch = e.touches ? e.touches[0] : e;
6852 doubleTap = (delta > 0 && delta <= delay);
6856 function onTouchEnd(e) {
6857 if (L.Browser.msTouch) {
6858 var idx = trackedTouches.indexOf(e.pointerId);
6862 trackedTouches.splice(idx, 1);
6866 if (L.Browser.msTouch) {
6867 // work around .type being readonly with MSPointer* events
6871 // jshint forin:false
6872 for (var i in touch) {
6874 if (typeof prop === 'function') {
6875 newTouch[i] = prop.bind(touch);
6882 touch.type = 'dblclick';
6887 obj[pre + touchstart + id] = onTouchStart;
6888 obj[pre + touchend + id] = onTouchEnd;
6890 // on msTouch we need to listen on the document, otherwise a drag starting on the map and moving off screen
6891 // will not come through to us, so we will lose track of how many touches are ongoing
6892 var endElement = L.Browser.msTouch ? document.documentElement : obj;
6894 obj.addEventListener(touchstart, onTouchStart, false);
6895 endElement.addEventListener(touchend, onTouchEnd, false);
6897 if (L.Browser.msTouch) {
6898 endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
6904 removeDoubleTapListener: function (obj, id) {
6905 var pre = '_leaflet_';
6907 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
6908 (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(
6909 this._touchend, obj[pre + this._touchend + id], false);
6911 if (L.Browser.msTouch) {
6912 document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
6921 * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
6924 L.extend(L.DomEvent, {
6927 _msDocumentListener: false,
6929 // Provides a touch events wrapper for msPointer events.
6930 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
6932 addMsTouchListener: function (obj, type, handler, id) {
6936 return this.addMsTouchListenerStart(obj, type, handler, id);
6938 return this.addMsTouchListenerEnd(obj, type, handler, id);
6940 return this.addMsTouchListenerMove(obj, type, handler, id);
6942 throw 'Unknown touch event type';
6946 addMsTouchListenerStart: function (obj, type, handler, id) {
6947 var pre = '_leaflet_',
6948 touches = this._msTouches;
6950 var cb = function (e) {
6952 var alreadyInArray = false;
6953 for (var i = 0; i < touches.length; i++) {
6954 if (touches[i].pointerId === e.pointerId) {
6955 alreadyInArray = true;
6959 if (!alreadyInArray) {
6963 e.touches = touches.slice();
6964 e.changedTouches = [e];
6969 obj[pre + 'touchstart' + id] = cb;
6970 obj.addEventListener('MSPointerDown', cb, false);
6972 // need to also listen for end events to keep the _msTouches list accurate
6973 // this needs to be on the body and never go away
6974 if (!this._msDocumentListener) {
6975 var internalCb = function (e) {
6976 for (var i = 0; i < touches.length; i++) {
6977 if (touches[i].pointerId === e.pointerId) {
6978 touches.splice(i, 1);
6983 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
6984 document.documentElement.addEventListener('MSPointerUp', internalCb, false);
6985 document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
6987 this._msDocumentListener = true;
6993 addMsTouchListenerMove: function (obj, type, handler, id) {
6994 var pre = '_leaflet_',
6995 touches = this._msTouches;
6999 // don't fire touch moves when mouse isn't down
7000 if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) { return; }
7002 for (var i = 0; i < touches.length; i++) {
7003 if (touches[i].pointerId === e.pointerId) {
7009 e.touches = touches.slice();
7010 e.changedTouches = [e];
7015 obj[pre + 'touchmove' + id] = cb;
7016 obj.addEventListener('MSPointerMove', cb, false);
7021 addMsTouchListenerEnd: function (obj, type, handler, id) {
7022 var pre = '_leaflet_',
7023 touches = this._msTouches;
7025 var cb = function (e) {
7026 for (var i = 0; i < touches.length; i++) {
7027 if (touches[i].pointerId === e.pointerId) {
7028 touches.splice(i, 1);
7033 e.touches = touches.slice();
7034 e.changedTouches = [e];
7039 obj[pre + 'touchend' + id] = cb;
7040 obj.addEventListener('MSPointerUp', cb, false);
7041 obj.addEventListener('MSPointerCancel', cb, false);
7046 removeMsTouchListener: function (obj, type, id) {
7047 var pre = '_leaflet_',
7048 cb = obj[pre + type + id];
7052 obj.removeEventListener('MSPointerDown', cb, false);
7055 obj.removeEventListener('MSPointerMove', cb, false);
7058 obj.removeEventListener('MSPointerUp', cb, false);
7059 obj.removeEventListener('MSPointerCancel', cb, false);
7069 * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
7072 L.Map.mergeOptions({
7073 touchZoom: L.Browser.touch && !L.Browser.android23
7076 L.Map.TouchZoom = L.Handler.extend({
7077 addHooks: function () {
7078 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
7081 removeHooks: function () {
7082 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
7085 _onTouchStart: function (e) {
7086 var map = this._map;
7088 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
7090 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7091 p2 = map.mouseEventToLayerPoint(e.touches[1]),
7092 viewCenter = map._getCenterLayerPoint();
7094 this._startCenter = p1.add(p2)._divideBy(2);
7095 this._startDist = p1.distanceTo(p2);
7097 this._moved = false;
7098 this._zooming = true;
7100 this._centerOffset = viewCenter.subtract(this._startCenter);
7103 map._panAnim.stop();
7107 .on(document, 'touchmove', this._onTouchMove, this)
7108 .on(document, 'touchend', this._onTouchEnd, this);
7110 L.DomEvent.preventDefault(e);
7113 _onTouchMove: function (e) {
7114 var map = this._map;
7116 if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
7118 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7119 p2 = map.mouseEventToLayerPoint(e.touches[1]);
7121 this._scale = p1.distanceTo(p2) / this._startDist;
7122 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
7124 if (this._scale === 1) { return; }
7127 L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
7136 L.Util.cancelAnimFrame(this._animRequest);
7137 this._animRequest = L.Util.requestAnimFrame(
7138 this._updateOnMove, this, true, this._map._container);
7140 L.DomEvent.preventDefault(e);
7143 _updateOnMove: function () {
7144 var map = this._map,
7145 origin = this._getScaleOrigin(),
7146 center = map.layerPointToLatLng(origin),
7147 zoom = map.getScaleZoom(this._scale);
7149 map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta);
7152 _onTouchEnd: function () {
7153 if (!this._moved || !this._zooming) {
7154 this._zooming = false;
7158 var map = this._map;
7160 this._zooming = false;
7161 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
7162 L.Util.cancelAnimFrame(this._animRequest);
7165 .off(document, 'touchmove', this._onTouchMove)
7166 .off(document, 'touchend', this._onTouchEnd);
7168 var origin = this._getScaleOrigin(),
7169 center = map.layerPointToLatLng(origin),
7171 oldZoom = map.getZoom(),
7172 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
7173 roundZoomDelta = (floatZoomDelta > 0 ?
7174 Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
7176 zoom = map._limitZoom(oldZoom + roundZoomDelta),
7177 scale = map.getZoomScale(zoom) / this._scale;
7179 map._animateZoom(center, zoom, origin, scale);
7182 _getScaleOrigin: function () {
7183 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
7184 return this._startCenter.add(centerOffset);
7188 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
7192 * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
7195 L.Map.mergeOptions({
7200 L.Map.Tap = L.Handler.extend({
7201 addHooks: function () {
7202 L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
7205 removeHooks: function () {
7206 L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
7209 _onDown: function (e) {
7210 if (!e.touches) { return; }
7212 L.DomEvent.preventDefault(e);
7214 this._fireClick = true;
7216 // don't simulate click or track longpress if more than 1 touch
7217 if (e.touches.length > 1) {
7218 this._fireClick = false;
7219 clearTimeout(this._holdTimeout);
7223 var first = e.touches[0],
7226 this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
7228 // if touching a link, highlight it
7229 if (el.tagName.toLowerCase() === 'a') {
7230 L.DomUtil.addClass(el, 'leaflet-active');
7233 // simulate long hold but setting a timeout
7234 this._holdTimeout = setTimeout(L.bind(function () {
7235 if (this._isTapValid()) {
7236 this._fireClick = false;
7238 this._simulateEvent('contextmenu', first);
7243 .on(document, 'touchmove', this._onMove, this)
7244 .on(document, 'touchend', this._onUp, this);
7247 _onUp: function (e) {
7248 clearTimeout(this._holdTimeout);
7251 .off(document, 'touchmove', this._onMove, this)
7252 .off(document, 'touchend', this._onUp, this);
7254 if (this._fireClick && e && e.changedTouches) {
7256 var first = e.changedTouches[0],
7259 if (el.tagName.toLowerCase() === 'a') {
7260 L.DomUtil.removeClass(el, 'leaflet-active');
7263 // simulate click if the touch didn't move too much
7264 if (this._isTapValid()) {
7265 this._simulateEvent('click', first);
7270 _isTapValid: function () {
7271 return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
7274 _onMove: function (e) {
7275 var first = e.touches[0];
7276 this._newPos = new L.Point(first.clientX, first.clientY);
7279 _simulateEvent: function (type, e) {
7280 var simulatedEvent = document.createEvent('MouseEvents');
7282 simulatedEvent._simulated = true;
7283 e.target._simulatedClick = true;
7285 simulatedEvent.initMouseEvent(
7286 type, true, true, window, 1,
7287 e.screenX, e.screenY,
7288 e.clientX, e.clientY,
7289 false, false, false, false, 0, null);
7291 e.target.dispatchEvent(simulatedEvent);
7295 if (L.Browser.touch && !L.Browser.msTouch) {
7296 L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
7301 * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
7302 * (zoom to a selected bounding box), enabled by default.
7305 L.Map.mergeOptions({
7309 L.Map.BoxZoom = L.Handler.extend({
7310 initialize: function (map) {
7312 this._container = map._container;
7313 this._pane = map._panes.overlayPane;
7316 addHooks: function () {
7317 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
7320 removeHooks: function () {
7321 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
7324 _onMouseDown: function (e) {
7325 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
7327 L.DomUtil.disableTextSelection();
7328 L.DomUtil.disableImageDrag();
7330 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
7332 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
7333 L.DomUtil.setPosition(this._box, this._startLayerPoint);
7335 //TODO refactor: move cursor to styles
7336 this._container.style.cursor = 'crosshair';
7339 .on(document, 'mousemove', this._onMouseMove, this)
7340 .on(document, 'mouseup', this._onMouseUp, this)
7341 .on(document, 'keydown', this._onKeyDown, this);
7343 this._map.fire('boxzoomstart');
7346 _onMouseMove: function (e) {
7347 var startPoint = this._startLayerPoint,
7350 layerPoint = this._map.mouseEventToLayerPoint(e),
7351 offset = layerPoint.subtract(startPoint),
7353 newPos = new L.Point(
7354 Math.min(layerPoint.x, startPoint.x),
7355 Math.min(layerPoint.y, startPoint.y));
7357 L.DomUtil.setPosition(box, newPos);
7359 // TODO refactor: remove hardcoded 4 pixels
7360 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
7361 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
7364 _finish: function () {
7365 this._pane.removeChild(this._box);
7366 this._container.style.cursor = '';
7368 L.DomUtil.enableTextSelection();
7369 L.DomUtil.enableImageDrag();
7372 .off(document, 'mousemove', this._onMouseMove)
7373 .off(document, 'mouseup', this._onMouseUp)
7374 .off(document, 'keydown', this._onKeyDown);
7377 _onMouseUp: function (e) {
7381 var map = this._map,
7382 layerPoint = map.mouseEventToLayerPoint(e);
7384 if (this._startLayerPoint.equals(layerPoint)) { return; }
7386 var bounds = new L.LatLngBounds(
7387 map.layerPointToLatLng(this._startLayerPoint),
7388 map.layerPointToLatLng(layerPoint));
7390 map.fitBounds(bounds);
7392 map.fire('boxzoomend', {
7393 boxZoomBounds: bounds
7397 _onKeyDown: function (e) {
7398 if (e.keyCode === 27) {
7404 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
7408 * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
7411 L.Map.mergeOptions({
7413 keyboardPanOffset: 80,
7414 keyboardZoomOffset: 1
7417 L.Map.Keyboard = L.Handler.extend({
7424 zoomIn: [187, 107, 61],
7425 zoomOut: [189, 109, 173]
7428 initialize: function (map) {
7431 this._setPanOffset(map.options.keyboardPanOffset);
7432 this._setZoomOffset(map.options.keyboardZoomOffset);
7435 addHooks: function () {
7436 var container = this._map._container;
7438 // make the container focusable by tabbing
7439 if (container.tabIndex === -1) {
7440 container.tabIndex = '0';
7444 .on(container, 'focus', this._onFocus, this)
7445 .on(container, 'blur', this._onBlur, this)
7446 .on(container, 'mousedown', this._onMouseDown, this);
7449 .on('focus', this._addHooks, this)
7450 .on('blur', this._removeHooks, this);
7453 removeHooks: function () {
7454 this._removeHooks();
7456 var container = this._map._container;
7459 .off(container, 'focus', this._onFocus, this)
7460 .off(container, 'blur', this._onBlur, this)
7461 .off(container, 'mousedown', this._onMouseDown, this);
7464 .off('focus', this._addHooks, this)
7465 .off('blur', this._removeHooks, this);
7468 _onMouseDown: function () {
7469 if (this._focused) { return; }
7471 var body = document.body,
7472 docEl = document.documentElement,
7473 top = body.scrollTop || docEl.scrollTop,
7474 left = body.scrollTop || docEl.scrollLeft;
7476 this._map._container.focus();
7478 window.scrollTo(left, top);
7481 _onFocus: function () {
7482 this._focused = true;
7483 this._map.fire('focus');
7486 _onBlur: function () {
7487 this._focused = false;
7488 this._map.fire('blur');
7491 _setPanOffset: function (pan) {
7492 var keys = this._panKeys = {},
7493 codes = this.keyCodes,
7496 for (i = 0, len = codes.left.length; i < len; i++) {
7497 keys[codes.left[i]] = [-1 * pan, 0];
7499 for (i = 0, len = codes.right.length; i < len; i++) {
7500 keys[codes.right[i]] = [pan, 0];
7502 for (i = 0, len = codes.down.length; i < len; i++) {
7503 keys[codes.down[i]] = [0, pan];
7505 for (i = 0, len = codes.up.length; i < len; i++) {
7506 keys[codes.up[i]] = [0, -1 * pan];
7510 _setZoomOffset: function (zoom) {
7511 var keys = this._zoomKeys = {},
7512 codes = this.keyCodes,
7515 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
7516 keys[codes.zoomIn[i]] = zoom;
7518 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
7519 keys[codes.zoomOut[i]] = -zoom;
7523 _addHooks: function () {
7524 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
7527 _removeHooks: function () {
7528 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
7531 _onKeyDown: function (e) {
7532 var key = e.keyCode,
7535 if (key in this._panKeys) {
7537 if (map._panAnim && map._panAnim._inProgress) { return; }
7539 map.panBy(this._panKeys[key]);
7541 if (map.options.maxBounds) {
7542 map.panInsideBounds(map.options.maxBounds);
7545 } else if (key in this._zoomKeys) {
7546 map.setZoom(map.getZoom() + this._zoomKeys[key]);
7556 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
7560 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
7563 L.Handler.MarkerDrag = L.Handler.extend({
7564 initialize: function (marker) {
7565 this._marker = marker;
7568 addHooks: function () {
7569 var icon = this._marker._icon;
7570 if (!this._draggable) {
7571 this._draggable = new L.Draggable(icon, icon);
7575 .on('dragstart', this._onDragStart, this)
7576 .on('drag', this._onDrag, this)
7577 .on('dragend', this._onDragEnd, this);
7578 this._draggable.enable();
7581 removeHooks: function () {
7583 .off('dragstart', this._onDragStart, this)
7584 .off('drag', this._onDrag, this)
7585 .off('dragend', this._onDragEnd, this);
7587 this._draggable.disable();
7590 moved: function () {
7591 return this._draggable && this._draggable._moved;
7594 _onDragStart: function () {
7601 _onDrag: function () {
7602 var marker = this._marker,
7603 shadow = marker._shadow,
7604 iconPos = L.DomUtil.getPosition(marker._icon),
7605 latlng = marker._map.layerPointToLatLng(iconPos);
7607 // update shadow position
7609 L.DomUtil.setPosition(shadow, iconPos);
7612 marker._latlng = latlng;
7615 .fire('move', {latlng: latlng})
7619 _onDragEnd: function () {
7628 * L.Control is a base class for implementing map controls. Handles positioning.
7629 * All other controls extend from this class.
7632 L.Control = L.Class.extend({
7634 position: 'topright'
7637 initialize: function (options) {
7638 L.setOptions(this, options);
7641 getPosition: function () {
7642 return this.options.position;
7645 setPosition: function (position) {
7646 var map = this._map;
7649 map.removeControl(this);
7652 this.options.position = position;
7655 map.addControl(this);
7661 getContainer: function () {
7662 return this._container;
7665 addTo: function (map) {
7668 var container = this._container = this.onAdd(map),
7669 pos = this.getPosition(),
7670 corner = map._controlCorners[pos];
7672 L.DomUtil.addClass(container, 'leaflet-control');
7674 if (pos.indexOf('bottom') !== -1) {
7675 corner.insertBefore(container, corner.firstChild);
7677 corner.appendChild(container);
7683 removeFrom: function (map) {
7684 var pos = this.getPosition(),
7685 corner = map._controlCorners[pos];
7687 corner.removeChild(this._container);
7690 if (this.onRemove) {
7698 L.control = function (options) {
7699 return new L.Control(options);
7703 // adds control-related methods to L.Map
7706 addControl: function (control) {
7707 control.addTo(this);
7711 removeControl: function (control) {
7712 control.removeFrom(this);
7716 _initControlPos: function () {
7717 var corners = this._controlCorners = {},
7719 container = this._controlContainer =
7720 L.DomUtil.create('div', l + 'control-container', this._container);
7722 function createCorner(vSide, hSide) {
7723 var className = l + vSide + ' ' + l + hSide;
7725 corners[vSide + hSide] = L.DomUtil.create('div', className, container);
7728 createCorner('top', 'left');
7729 createCorner('top', 'right');
7730 createCorner('bottom', 'left');
7731 createCorner('bottom', 'right');
7734 _clearControlPos: function () {
7735 this._container.removeChild(this._controlContainer);
7741 * L.Control.Zoom is used for the default zoom buttons on the map.
7744 L.Control.Zoom = L.Control.extend({
7749 onAdd: function (map) {
7750 var zoomName = 'leaflet-control-zoom',
7751 container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
7755 this._zoomInButton = this._createButton(
7756 '+', 'Zoom in', zoomName + '-in', container, this._zoomIn, this);
7757 this._zoomOutButton = this._createButton(
7758 '-', 'Zoom out', zoomName + '-out', container, this._zoomOut, this);
7760 map.on('zoomend zoomlevelschange', this._updateDisabled, this);
7765 onRemove: function (map) {
7766 map.off('zoomend zoomlevelschange', this._updateDisabled, this);
7769 _zoomIn: function (e) {
7770 this._map.zoomIn(e.shiftKey ? 3 : 1);
7773 _zoomOut: function (e) {
7774 this._map.zoomOut(e.shiftKey ? 3 : 1);
7777 _createButton: function (html, title, className, container, fn, context) {
7778 var link = L.DomUtil.create('a', className, container);
7779 link.innerHTML = html;
7783 var stop = L.DomEvent.stopPropagation;
7786 .on(link, 'click', stop)
7787 .on(link, 'mousedown', stop)
7788 .on(link, 'dblclick', stop)
7789 .on(link, 'click', L.DomEvent.preventDefault)
7790 .on(link, 'click', fn, context);
7795 _updateDisabled: function () {
7796 var map = this._map,
7797 className = 'leaflet-disabled';
7799 L.DomUtil.removeClass(this._zoomInButton, className);
7800 L.DomUtil.removeClass(this._zoomOutButton, className);
7802 if (map._zoom === map.getMinZoom()) {
7803 L.DomUtil.addClass(this._zoomOutButton, className);
7805 if (map._zoom === map.getMaxZoom()) {
7806 L.DomUtil.addClass(this._zoomInButton, className);
7811 L.Map.mergeOptions({
7815 L.Map.addInitHook(function () {
7816 if (this.options.zoomControl) {
7817 this.zoomControl = new L.Control.Zoom();
7818 this.addControl(this.zoomControl);
7822 L.control.zoom = function (options) {
7823 return new L.Control.Zoom(options);
7829 * L.Control.Attribution is used for displaying attribution on the map (added by default).
7832 L.Control.Attribution = L.Control.extend({
7834 position: 'bottomright',
7835 prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
7838 initialize: function (options) {
7839 L.setOptions(this, options);
7841 this._attributions = {};
7844 onAdd: function (map) {
7845 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
7846 L.DomEvent.disableClickPropagation(this._container);
7849 .on('layeradd', this._onLayerAdd, this)
7850 .on('layerremove', this._onLayerRemove, this);
7854 return this._container;
7857 onRemove: function (map) {
7859 .off('layeradd', this._onLayerAdd)
7860 .off('layerremove', this._onLayerRemove);
7864 setPrefix: function (prefix) {
7865 this.options.prefix = prefix;
7870 addAttribution: function (text) {
7871 if (!text) { return; }
7873 if (!this._attributions[text]) {
7874 this._attributions[text] = 0;
7876 this._attributions[text]++;
7883 removeAttribution: function (text) {
7884 if (!text) { return; }
7886 if (this._attributions[text]) {
7887 this._attributions[text]--;
7894 _update: function () {
7895 if (!this._map) { return; }
7899 for (var i in this._attributions) {
7900 if (this._attributions[i]) {
7905 var prefixAndAttribs = [];
7907 if (this.options.prefix) {
7908 prefixAndAttribs.push(this.options.prefix);
7910 if (attribs.length) {
7911 prefixAndAttribs.push(attribs.join(', '));
7914 this._container.innerHTML = prefixAndAttribs.join(' | ');
7917 _onLayerAdd: function (e) {
7918 if (e.layer.getAttribution) {
7919 this.addAttribution(e.layer.getAttribution());
7923 _onLayerRemove: function (e) {
7924 if (e.layer.getAttribution) {
7925 this.removeAttribution(e.layer.getAttribution());
7930 L.Map.mergeOptions({
7931 attributionControl: true
7934 L.Map.addInitHook(function () {
7935 if (this.options.attributionControl) {
7936 this.attributionControl = (new L.Control.Attribution()).addTo(this);
7940 L.control.attribution = function (options) {
7941 return new L.Control.Attribution(options);
7946 * L.Control.Scale is used for displaying metric/imperial scale on the map.
7949 L.Control.Scale = L.Control.extend({
7951 position: 'bottomleft',
7955 updateWhenIdle: false
7958 onAdd: function (map) {
7961 var className = 'leaflet-control-scale',
7962 container = L.DomUtil.create('div', className),
7963 options = this.options;
7965 this._addScales(options, className, container);
7967 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
7968 map.whenReady(this._update, this);
7973 onRemove: function (map) {
7974 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
7977 _addScales: function (options, className, container) {
7978 if (options.metric) {
7979 this._mScale = L.DomUtil.create('div', className + '-line', container);
7981 if (options.imperial) {
7982 this._iScale = L.DomUtil.create('div', className + '-line', container);
7986 _update: function () {
7987 var bounds = this._map.getBounds(),
7988 centerLat = bounds.getCenter().lat,
7989 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
7990 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
7992 size = this._map.getSize(),
7993 options = this.options,
7997 maxMeters = dist * (options.maxWidth / size.x);
8000 this._updateScales(options, maxMeters);
8003 _updateScales: function (options, maxMeters) {
8004 if (options.metric && maxMeters) {
8005 this._updateMetric(maxMeters);
8008 if (options.imperial && maxMeters) {
8009 this._updateImperial(maxMeters);
8013 _updateMetric: function (maxMeters) {
8014 var meters = this._getRoundNum(maxMeters);
8016 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
8017 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
8020 _updateImperial: function (maxMeters) {
8021 var maxFeet = maxMeters * 3.2808399,
8022 scale = this._iScale,
8023 maxMiles, miles, feet;
8025 if (maxFeet > 5280) {
8026 maxMiles = maxFeet / 5280;
8027 miles = this._getRoundNum(maxMiles);
8029 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
8030 scale.innerHTML = miles + ' mi';
8033 feet = this._getRoundNum(maxFeet);
8035 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
8036 scale.innerHTML = feet + ' ft';
8040 _getScaleWidth: function (ratio) {
8041 return Math.round(this.options.maxWidth * ratio) - 10;
8044 _getRoundNum: function (num) {
8045 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
8048 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
8054 L.control.scale = function (options) {
8055 return new L.Control.Scale(options);
8060 * L.Control.Layers is a control to allow users to switch between different layers on the map.
8063 L.Control.Layers = L.Control.extend({
8066 position: 'topright',
8070 initialize: function (baseLayers, overlays, options) {
8071 L.setOptions(this, options);
8074 this._lastZIndex = 0;
8075 this._handlingClick = false;
8077 for (var i in baseLayers) {
8078 this._addLayer(baseLayers[i], i);
8081 for (i in overlays) {
8082 this._addLayer(overlays[i], i, true);
8086 onAdd: function (map) {
8091 .on('layeradd', this._onLayerChange, this)
8092 .on('layerremove', this._onLayerChange, this);
8094 return this._container;
8097 onRemove: function (map) {
8099 .off('layeradd', this._onLayerChange)
8100 .off('layerremove', this._onLayerChange);
8103 addBaseLayer: function (layer, name) {
8104 this._addLayer(layer, name);
8109 addOverlay: function (layer, name) {
8110 this._addLayer(layer, name, true);
8115 removeLayer: function (layer) {
8116 var id = L.stamp(layer);
8117 delete this._layers[id];
8122 _initLayout: function () {
8123 var className = 'leaflet-control-layers',
8124 container = this._container = L.DomUtil.create('div', className);
8126 //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
8127 container.setAttribute('aria-haspopup', true);
8129 if (!L.Browser.touch) {
8130 L.DomEvent.disableClickPropagation(container);
8131 L.DomEvent.on(container, 'wheel', L.DomEvent.stopPropagation);
8133 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
8136 var form = this._form = L.DomUtil.create('form', className + '-list');
8138 if (this.options.collapsed) {
8139 if (!L.Browser.android) {
8141 .on(container, 'mouseover', this._expand, this)
8142 .on(container, 'mouseout', this._collapse, this);
8144 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
8146 link.title = 'Layers';
8148 if (L.Browser.touch) {
8150 .on(link, 'click', L.DomEvent.stop)
8151 .on(link, 'click', this._expand, this);
8154 L.DomEvent.on(link, 'focus', this._expand, this);
8157 this._map.on('click', this._collapse, this);
8158 // TODO keyboard accessibility
8163 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
8164 this._separator = L.DomUtil.create('div', className + '-separator', form);
8165 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
8167 container.appendChild(form);
8170 _addLayer: function (layer, name, overlay) {
8171 var id = L.stamp(layer);
8173 this._layers[id] = {
8179 if (this.options.autoZIndex && layer.setZIndex) {
8181 layer.setZIndex(this._lastZIndex);
8185 _update: function () {
8186 if (!this._container) {
8190 this._baseLayersList.innerHTML = '';
8191 this._overlaysList.innerHTML = '';
8193 var baseLayersPresent = false,
8194 overlaysPresent = false,
8197 for (i in this._layers) {
8198 obj = this._layers[i];
8200 overlaysPresent = overlaysPresent || obj.overlay;
8201 baseLayersPresent = baseLayersPresent || !obj.overlay;
8204 this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
8207 _onLayerChange: function (e) {
8208 var obj = this._layers[L.stamp(e.layer)];
8210 if (!obj) { return; }
8212 if (!this._handlingClick) {
8216 var type = obj.overlay ?
8217 (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
8218 (e.type === 'layeradd' ? 'baselayerchange' : null);
8221 this._map.fire(type, obj);
8225 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
8226 _createRadioElement: function (name, checked) {
8228 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
8230 radioHtml += ' checked="checked"';
8234 var radioFragment = document.createElement('div');
8235 radioFragment.innerHTML = radioHtml;
8237 return radioFragment.firstChild;
8240 _addItem: function (obj) {
8241 var label = document.createElement('label'),
8243 checked = this._map.hasLayer(obj.layer);
8246 input = document.createElement('input');
8247 input.type = 'checkbox';
8248 input.className = 'leaflet-control-layers-selector';
8249 input.defaultChecked = checked;
8251 input = this._createRadioElement('leaflet-base-layers', checked);
8254 input.layerId = L.stamp(obj.layer);
8256 L.DomEvent.on(input, 'click', this._onInputClick, this);
8258 var name = document.createElement('span');
8259 name.innerHTML = ' ' + obj.name;
8261 label.appendChild(input);
8262 label.appendChild(name);
8264 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
8265 container.appendChild(label);
8270 _onInputClick: function () {
8272 inputs = this._form.getElementsByTagName('input'),
8273 inputsLen = inputs.length;
8275 this._handlingClick = true;
8277 for (i = 0; i < inputsLen; i++) {
8279 obj = this._layers[input.layerId];
8281 if (input.checked && !this._map.hasLayer(obj.layer)) {
8282 this._map.addLayer(obj.layer);
8284 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
8285 this._map.removeLayer(obj.layer);
8289 this._handlingClick = false;
8292 _expand: function () {
8293 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
8296 _collapse: function () {
8297 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
8301 L.control.layers = function (baseLayers, overlays, options) {
8302 return new L.Control.Layers(baseLayers, overlays, options);
8307 * L.PosAnimation is used by Leaflet internally for pan animations.
8310 L.PosAnimation = L.Class.extend({
8311 includes: L.Mixin.Events,
8313 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8317 this._inProgress = true;
8318 this._newPos = newPos;
8322 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
8323 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
8325 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8326 L.DomUtil.setPosition(el, newPos);
8328 // toggle reflow, Chrome flickers for some reason if you don't do this
8329 L.Util.falseFn(el.offsetWidth);
8331 // there's no native way to track value updates of transitioned properties, so we imitate this
8332 this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
8336 if (!this._inProgress) { return; }
8338 // if we just removed the transition property, the element would jump to its final position,
8339 // so we need to make it stay at the current position
8341 L.DomUtil.setPosition(this._el, this._getPos());
8342 this._onTransitionEnd();
8343 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
8346 _onStep: function () {
8347 // jshint camelcase: false
8348 // make L.DomUtil.getPosition return intermediate position value during animation
8349 this._el._leaflet_pos = this._getPos();
8354 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
8355 // we need to parse computed style (in case of transform it returns matrix string)
8357 _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
8359 _getPos: function () {
8360 var left, top, matches,
8362 style = window.getComputedStyle(el);
8364 if (L.Browser.any3d) {
8365 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
8366 left = matches ? parseFloat(matches[1]) : 0;
8367 top = matches ? parseFloat(matches[2]) : 0;
8369 left = parseFloat(style.left);
8370 top = parseFloat(style.top);
8373 return new L.Point(left, top, true);
8376 _onTransitionEnd: function () {
8377 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8379 if (!this._inProgress) { return; }
8380 this._inProgress = false;
8382 this._el.style[L.DomUtil.TRANSITION] = '';
8384 // jshint camelcase: false
8385 // make sure L.DomUtil.getPosition returns the final position value after animation
8386 this._el._leaflet_pos = this._newPos;
8388 clearInterval(this._stepTimer);
8390 this.fire('step').fire('end');
8397 * Extends L.Map to handle panning animations.
8402 setView: function (center, zoom, options) {
8404 zoom = this._limitZoom(zoom);
8405 center = L.latLng(center);
8406 options = options || {};
8408 if (this._panAnim) {
8409 this._panAnim.stop();
8412 if (this._loaded && !options.reset && options !== true) {
8414 if (options.animate !== undefined) {
8415 options.zoom = L.extend({animate: options.animate}, options.zoom);
8416 options.pan = L.extend({animate: options.animate}, options.pan);
8419 // try animating pan or zoom
8420 var animated = (this._zoom !== zoom) ?
8421 this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
8422 this._tryAnimatedPan(center, options.pan);
8425 // prevent resize handler call, the view will refresh after animation anyway
8426 clearTimeout(this._sizeTimer);
8431 // animation didn't start, just reset the map view
8432 this._resetView(center, zoom);
8437 panBy: function (offset, options) {
8438 offset = L.point(offset).round();
8439 options = options || {};
8441 if (!offset.x && !offset.y) {
8445 if (!this._panAnim) {
8446 this._panAnim = new L.PosAnimation();
8449 'step': this._onPanTransitionStep,
8450 'end': this._onPanTransitionEnd
8454 // don't fire movestart if animating inertia
8455 if (!options.noMoveStart) {
8456 this.fire('movestart');
8459 // animate pan unless animate: false specified
8460 if (options.animate !== false) {
8461 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
8463 var newPos = this._getMapPanePos().subtract(offset);
8464 this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
8466 this._rawPanBy(offset);
8467 this.fire('move').fire('moveend');
8473 _onPanTransitionStep: function () {
8477 _onPanTransitionEnd: function () {
8478 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
8479 this.fire('moveend');
8482 _tryAnimatedPan: function (center, options) {
8483 // difference between the new and current centers in pixels
8484 var offset = this._getCenterOffset(center)._floor();
8486 // don't animate too far unless animate: true specified in options
8487 if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
8489 this.panBy(offset, options);
8497 * L.PosAnimation fallback implementation that powers Leaflet pan animations
8498 * in browsers that don't support CSS3 Transitions.
8501 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8503 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8507 this._inProgress = true;
8508 this._duration = duration || 0.25;
8509 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8511 this._startPos = L.DomUtil.getPosition(el);
8512 this._offset = newPos.subtract(this._startPos);
8513 this._startTime = +new Date();
8521 if (!this._inProgress) { return; }
8527 _animate: function () {
8529 this._animId = L.Util.requestAnimFrame(this._animate, this);
8533 _step: function () {
8534 var elapsed = (+new Date()) - this._startTime,
8535 duration = this._duration * 1000;
8537 if (elapsed < duration) {
8538 this._runFrame(this._easeOut(elapsed / duration));
8545 _runFrame: function (progress) {
8546 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8547 L.DomUtil.setPosition(this._el, pos);
8552 _complete: function () {
8553 L.Util.cancelAnimFrame(this._animId);
8555 this._inProgress = false;
8559 _easeOut: function (t) {
8560 return 1 - Math.pow(1 - t, this._easeOutPower);
8566 * Extends L.Map to handle zoom animations.
8569 L.Map.mergeOptions({
8570 zoomAnimation: true,
8571 zoomAnimationThreshold: 4
8574 if (L.DomUtil.TRANSITION) {
8576 L.Map.addInitHook(function () {
8577 // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
8578 this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
8579 L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
8581 // zoom transitions run with the same duration for all layers, so if one of transitionend events
8582 // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
8583 if (this._zoomAnimated) {
8584 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8589 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8591 _catchTransitionEnd: function () {
8592 if (this._animatingZoom) {
8593 this._onZoomTransitionEnd();
8597 _tryAnimatedZoom: function (center, zoom, options) {
8599 if (this._animatingZoom) { return true; }
8601 options = options || {};
8603 // don't animate if disabled, not supported or zoom difference is too large
8604 if (!this._zoomAnimated || options.animate === false ||
8605 Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
8607 // offset is the pixel coords of the zoom origin relative to the current center
8608 var scale = this.getZoomScale(zoom),
8609 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
8610 origin = this._getCenterLayerPoint()._add(offset);
8612 // don't animate if the zoom origin isn't within one screen from the current center, unless forced
8613 if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
8619 this._animateZoom(center, zoom, origin, scale, null, true);
8624 _animateZoom: function (center, zoom, origin, scale, delta, backwards) {
8626 this._animatingZoom = true;
8628 // put transform transition on all layers with leaflet-zoom-animated class
8629 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8631 // remember what center/zoom to set after animation
8632 this._animateToCenter = center;
8633 this._animateToZoom = zoom;
8635 // disable any dragging during animation
8637 L.Draggable._disabled = true;
8640 this.fire('zoomanim', {
8646 backwards: backwards
8650 _onZoomTransitionEnd: function () {
8652 this._animatingZoom = false;
8654 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8656 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8659 L.Draggable._disabled = false;
8666 Zoom animation logic for L.TileLayer.
8669 L.TileLayer.include({
8670 _animateZoom: function (e) {
8671 var firstFrame = false;
8673 if (!this._animating) {
8674 this._animating = true;
8679 this._prepareBgBuffer();
8682 var bg = this._bgBuffer;
8685 //prevent bg buffer from clearing right after zoom
8686 clearTimeout(this._clearBgBufferTimer);
8688 // hack to make sure transform is updated before running animation
8689 L.Util.falseFn(bg.offsetWidth);
8692 var transform = L.DomUtil.TRANSFORM,
8693 initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
8694 scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
8696 bg.style[transform] = e.backwards ?
8697 scaleStr + ' ' + initialTransform :
8698 initialTransform + ' ' + scaleStr;
8701 _endZoomAnim: function () {
8702 var front = this._tileContainer,
8703 bg = this._bgBuffer;
8705 front.style.visibility = '';
8706 front.style.zIndex = 2;
8708 bg.style.zIndex = 1;
8711 L.Util.falseFn(bg.offsetWidth);
8713 this._animating = false;
8716 _clearBgBuffer: function () {
8717 var map = this._map;
8719 if (map && !map._animatingZoom && !map.touchZoom._zooming) {
8720 this._bgBuffer.innerHTML = '';
8721 this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
8725 _prepareBgBuffer: function () {
8727 var front = this._tileContainer,
8728 bg = this._bgBuffer;
8730 // if foreground layer doesn't have many tiles but bg layer does,
8731 // keep the existing bg layer and just zoom it some more
8733 var bgLoaded = this._getLoadedTilesPercentage(bg),
8734 frontLoaded = this._getLoadedTilesPercentage(front);
8736 if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
8738 front.style.visibility = 'hidden';
8739 this._stopLoadingImages(front);
8743 // prepare the buffer to become the front tile pane
8744 bg.style.visibility = 'hidden';
8745 bg.style[L.DomUtil.TRANSFORM] = '';
8747 // switch out the current layer to be the new bg layer (and vice-versa)
8748 this._tileContainer = bg;
8749 bg = this._bgBuffer = front;
8751 this._stopLoadingImages(bg);
8754 _getLoadedTilesPercentage: function (container) {
8755 var tiles = container.getElementsByTagName('img'),
8758 for (i = 0, len = tiles.length; i < len; i++) {
8759 if (tiles[i].complete) {
8766 // stops loading all tiles in the background layer
8767 _stopLoadingImages: function (container) {
8768 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
8771 for (i = 0, len = tiles.length; i < len; i++) {
8774 if (!tile.complete) {
8775 tile.onload = L.Util.falseFn;
8776 tile.onerror = L.Util.falseFn;
8777 tile.src = L.Util.emptyImageUrl;
8779 tile.parentNode.removeChild(tile);
8787 * Provides L.Map with convenient shortcuts for using browser geolocation features.
8791 _defaultLocateOptions: {
8797 enableHighAccuracy: false
8800 locate: function (/*Object*/ options) {
8802 options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
8804 if (!navigator.geolocation) {
8805 this._handleGeolocationError({
8807 message: 'Geolocation not supported.'
8812 var onResponse = L.bind(this._handleGeolocationResponse, this),
8813 onError = L.bind(this._handleGeolocationError, this);
8815 if (options.watch) {
8816 this._locationWatchId =
8817 navigator.geolocation.watchPosition(onResponse, onError, options);
8819 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
8824 stopLocate: function () {
8825 if (navigator.geolocation) {
8826 navigator.geolocation.clearWatch(this._locationWatchId);
8828 if (this._locateOptions) {
8829 this._locateOptions.setView = false;
8834 _handleGeolocationError: function (error) {
8836 message = error.message ||
8837 (c === 1 ? 'permission denied' :
8838 (c === 2 ? 'position unavailable' : 'timeout'));
8840 if (this._locateOptions.setView && !this._loaded) {
8844 this.fire('locationerror', {
8846 message: 'Geolocation error: ' + message + '.'
8850 _handleGeolocationResponse: function (pos) {
8851 var lat = pos.coords.latitude,
8852 lng = pos.coords.longitude,
8853 latlng = new L.LatLng(lat, lng),
8855 latAccuracy = 180 * pos.coords.accuracy / 40075017,
8856 lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
8858 bounds = L.latLngBounds(
8859 [lat - latAccuracy, lng - lngAccuracy],
8860 [lat + latAccuracy, lng + lngAccuracy]),
8862 options = this._locateOptions;
8864 if (options.setView) {
8865 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
8866 this.setView(latlng, zoom);
8874 for (var i in pos.coords) {
8875 if (typeof pos.coords[i] === 'number') {
8876 data[i] = pos.coords[i];
8880 this.fire('locationfound', data);
8885 }(window, document));