2 Copyright (c) 2010-2012, CloudMade, Vladimir Agafonkin
3 Leaflet is an open-source JavaScript library for mobile-friendly interactive maps.
4 http://leaflet.cloudmade.com
6 (function (window, undefined) {
10 if (typeof exports !== undefined + '') {
16 L.noConflict = function () {
28 * L.Util is a namespace for various utility functions.
32 extend: function (/*Object*/ dest) /*-> Object*/ { // merge src properties into dest
33 var sources = Array.prototype.slice.call(arguments, 1);
34 for (var j = 0, len = sources.length, src; j < len; j++) {
35 src = sources[j] || {};
37 if (src.hasOwnProperty(i)) {
45 bind: function (fn, obj) { // (Function, Object) -> Function
46 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
48 return fn.apply(obj, args || arguments);
53 var lastId = 0, key = '_leaflet_id';
54 return function (/*Object*/ obj) {
55 obj[key] = obj[key] || ++lastId;
60 limitExecByInterval: function (fn, time, context) {
61 var lock, execOnUnlock;
63 return function wrapperFn() {
73 setTimeout(function () {
77 wrapperFn.apply(context, args);
82 fn.apply(context, args);
86 falseFn: function () {
90 formatNum: function (num, digits) {
91 var pow = Math.pow(10, digits || 5);
92 return Math.round(num * pow) / pow;
95 splitWords: function (str) {
96 return str.replace(/^\s+|\s+$/g, '').split(/\s+/);
99 setOptions: function (obj, options) {
100 obj.options = L.Util.extend({}, obj.options, options);
104 getParamString: function (obj) {
107 if (obj.hasOwnProperty(i)) {
108 params.push(i + '=' + obj[i]);
111 return '?' + params.join('&');
114 template: function (str, data) {
115 return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
116 var value = data[key];
117 if (!data.hasOwnProperty(key)) {
118 throw new Error('No value provided for variable ' + str);
124 emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
129 // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
131 function getPrefixed(name) {
133 prefixes = ['webkit', 'moz', 'o', 'ms'];
135 for (i = 0; i < prefixes.length && !fn; i++) {
136 fn = window[prefixes[i] + name];
144 function timeoutDefer(fn) {
145 var time = +new Date(),
146 timeToCall = Math.max(0, 16 - (time - lastTime));
148 lastTime = time + timeToCall;
149 return window.setTimeout(fn, timeToCall);
152 var requestFn = window.requestAnimationFrame ||
153 getPrefixed('RequestAnimationFrame') || timeoutDefer;
155 var cancelFn = window.cancelAnimationFrame ||
156 getPrefixed('CancelAnimationFrame') ||
157 getPrefixed('CancelRequestAnimationFrame') ||
159 window.clearTimeout(id);
163 L.Util.requestAnimFrame = function (fn, context, immediate, element) {
164 fn = L.Util.bind(fn, context);
166 if (immediate && requestFn === timeoutDefer) {
169 return requestFn.call(window, fn, element);
173 L.Util.cancelAnimFrame = function (id) {
175 cancelFn.call(window, id);
183 * Class powers the OOP facilities of the library. Thanks to John Resig and Dean Edwards for inspiration!
186 L.Class = function () {};
188 L.Class.extend = function (/*Object*/ props) /*-> Class*/ {
190 // extended class with the new prototype
191 var NewClass = function () {
192 if (this.initialize) {
193 this.initialize.apply(this, arguments);
197 // instantiate class without calling constructor
198 var F = function () {};
199 F.prototype = this.prototype;
202 proto.constructor = NewClass;
204 NewClass.prototype = proto;
206 //inherit parent's statics
207 for (var i in this) {
208 if (this.hasOwnProperty(i) && i !== 'prototype') {
209 NewClass[i] = this[i];
213 // mix static properties into the class
215 L.Util.extend(NewClass, props.statics);
216 delete props.statics;
219 // mix includes into the prototype
220 if (props.includes) {
221 L.Util.extend.apply(null, [proto].concat(props.includes));
222 delete props.includes;
226 if (props.options && proto.options) {
227 props.options = L.Util.extend({}, proto.options, props.options);
230 // mix given properties into the prototype
231 L.Util.extend(proto, props);
237 // method for adding properties to prototype
238 L.Class.include = function (props) {
239 L.Util.extend(this.prototype, props);
242 L.Class.mergeOptions = function (options) {
243 L.Util.extend(this.prototype.options, options);
247 * L.Mixin.Events adds custom events functionality to Leaflet classes
250 var key = '_leaflet_events';
256 addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
257 var events = this[key] = this[key] || {},
260 // Types can be a map of types/handlers
261 if (typeof types === 'object') {
262 for (type in types) {
263 if (types.hasOwnProperty(type)) {
264 this.addEventListener(type, types[type], fn);
271 types = L.Util.splitWords(types);
273 for (i = 0, len = types.length; i < len; i++) {
274 events[types[i]] = events[types[i]] || [];
275 events[types[i]].push({
277 context: context || this
284 hasEventListeners: function (type) { // (String) -> Boolean
285 return (key in this) && (type in this[key]) && (this[key][type].length > 0);
288 removeEventListener: function (types, fn, context) { // (String[, Function, Object]) or (Object[, Object])
289 var events = this[key],
290 type, i, len, listeners, j;
292 if (typeof types === 'object') {
293 for (type in types) {
294 if (types.hasOwnProperty(type)) {
295 this.removeEventListener(type, types[type], fn);
302 types = L.Util.splitWords(types);
304 for (i = 0, len = types.length; i < len; i++) {
306 if (this.hasEventListeners(types[i])) {
307 listeners = events[types[i]];
309 for (j = listeners.length - 1; j >= 0; j--) {
311 (!fn || listeners[j].action === fn) &&
312 (!context || (listeners[j].context === context))
314 listeners.splice(j, 1);
323 fireEvent: function (type, data) { // (String[, Object])
324 if (!this.hasEventListeners(type)) {
328 var event = L.Util.extend({
333 var listeners = this[key][type].slice();
335 for (var i = 0, len = listeners.length; i < len; i++) {
336 listeners[i].action.call(listeners[i].context || this, event);
343 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
344 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
345 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
349 var ua = navigator.userAgent.toLowerCase(),
350 ie = !!window.ActiveXObject,
351 ie6 = ie && !window.XMLHttpRequest,
352 webkit = ua.indexOf("webkit") !== -1,
353 gecko = ua.indexOf("gecko") !== -1,
354 //Terrible browser detection to work around a safari / iOS / android browser bug. See TileLayer._addTile and debug/hacks/jitter.html
355 chrome = ua.indexOf("chrome") !== -1,
356 opera = window.opera,
357 android = ua.indexOf("android") !== -1,
358 android23 = ua.search("android [23]") !== -1,
359 mobile = typeof orientation !== undefined + '' ? true : false,
360 doc = document.documentElement,
361 ie3d = ie && ('transition' in doc.style),
362 webkit3d = webkit && ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
363 gecko3d = gecko && ('MozPerspective' in doc.style),
364 opera3d = opera && ('OTransition' in doc.style);
366 var touch = !window.L_NO_TOUCH && (function () {
367 var startName = 'ontouchstart';
370 if (startName in doc) {
375 var div = document.createElement('div'),
378 if (!div.setAttribute) {
381 div.setAttribute(startName, 'return;');
383 if (typeof div[startName] === 'function') {
387 div.removeAttribute(startName);
393 var retina = (('devicePixelRatio' in window && window.devicePixelRatio > 1) || ('matchMedia' in window && window.matchMedia("(min-resolution:144dpi)").matches));
403 android23: android23,
411 any3d: !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d),
414 mobileWebkit: mobile && webkit,
415 mobileWebkit3d: mobile && webkit3d,
416 mobileOpera: mobile && opera,
426 * L.Point represents a point with x and y coordinates.
429 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
430 this.x = (round ? Math.round(x) : x);
431 this.y = (round ? Math.round(y) : y);
434 L.Point.prototype = {
437 return new L.Point(this.x, this.y);
440 // non-destructive, returns a new point
441 add: function (point) {
442 return this.clone()._add(L.point(point));
445 // destructive, used directly for performance in situations where it's safe to modify existing point
446 _add: function (point) {
452 subtract: function (point) {
453 return this.clone()._subtract(L.point(point));
456 _subtract: function (point) {
462 divideBy: function (num) {
463 return this.clone()._divideBy(num);
466 _divideBy: function (num) {
472 multiplyBy: function (num) {
473 return this.clone()._multiplyBy(num);
476 _multiplyBy: function (num) {
483 return this.clone()._round();
486 _round: function () {
487 this.x = Math.round(this.x);
488 this.y = Math.round(this.y);
493 return this.clone()._floor();
496 _floor: function () {
497 this.x = Math.floor(this.x);
498 this.y = Math.floor(this.y);
502 distanceTo: function (point) {
503 point = L.point(point);
505 var x = point.x - this.x,
506 y = point.y - this.y;
508 return Math.sqrt(x * x + y * y);
511 toString: function () {
513 L.Util.formatNum(this.x) + ', ' +
514 L.Util.formatNum(this.y) + ')';
518 L.point = function (x, y, round) {
519 if (x instanceof L.Point) {
522 if (x instanceof Array) {
523 return new L.Point(x[0], x[1]);
528 return new L.Point(x, y, round);
533 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
536 L.Bounds = L.Class.extend({
538 initialize: function (a, b) { //(Point, Point) or Point[]
541 var points = b ? [a, b] : a;
543 for (var i = 0, len = points.length; i < len; i++) {
544 this.extend(points[i]);
548 // extend the bounds to contain the given point
549 extend: function (point) { // (Point)
550 point = L.point(point);
552 if (!this.min && !this.max) {
553 this.min = point.clone();
554 this.max = point.clone();
556 this.min.x = Math.min(point.x, this.min.x);
557 this.max.x = Math.max(point.x, this.max.x);
558 this.min.y = Math.min(point.y, this.min.y);
559 this.max.y = Math.max(point.y, this.max.y);
564 getCenter: function (round) { // (Boolean) -> Point
566 (this.min.x + this.max.x) / 2,
567 (this.min.y + this.max.y) / 2, round);
570 getBottomLeft: function () { // -> Point
571 return new L.Point(this.min.x, this.max.y);
574 getTopRight: function () { // -> Point
575 return new L.Point(this.max.x, this.min.y);
578 contains: function (obj) { // (Bounds) or (Point) -> Boolean
581 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
587 if (obj instanceof L.Bounds) {
594 return (min.x >= this.min.x) &&
595 (max.x <= this.max.x) &&
596 (min.y >= this.min.y) &&
597 (max.y <= this.max.y);
600 intersects: function (bounds) { // (Bounds) -> Boolean
601 bounds = L.bounds(bounds);
608 var xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
609 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
611 return xIntersects && yIntersects;
614 isValid: function () {
615 return !!(this.min && this.max);
619 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
620 if (!a || a instanceof L.Bounds) {
623 return new L.Bounds(a, b);
628 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
631 L.Transformation = L.Class.extend({
632 initialize: function (/*Number*/ a, /*Number*/ b, /*Number*/ c, /*Number*/ d) {
639 transform: function (point, scale) {
640 return this._transform(point.clone(), scale);
643 // destructive transform (faster)
644 _transform: function (/*Point*/ point, /*Number*/ scale) /*-> Point*/ {
646 point.x = scale * (this._a * point.x + this._b);
647 point.y = scale * (this._c * point.y + this._d);
651 untransform: function (/*Point*/ point, /*Number*/ scale) /*-> Point*/ {
654 (point.x / scale - this._b) / this._a,
655 (point.y / scale - this._d) / this._c);
661 * L.DomUtil contains various utility functions for working with DOM.
666 return (typeof id === 'string' ? document.getElementById(id) : id);
669 getStyle: function (el, style) {
671 var value = el.style[style];
673 if (!value && el.currentStyle) {
674 value = el.currentStyle[style];
677 if (!value || value === 'auto') {
678 var css = document.defaultView.getComputedStyle(el, null);
679 value = css ? css[style] : null;
682 return value === 'auto' ? null : value;
685 getViewportOffset: function (element) {
690 docBody = document.body,
694 top += el.offsetTop || 0;
695 left += el.offsetLeft || 0;
696 pos = L.DomUtil.getStyle(el, 'position');
698 if (el.offsetParent === docBody && pos === 'absolute') { break; }
700 if (pos === 'fixed') {
701 top += docBody.scrollTop || 0;
702 left += docBody.scrollLeft || 0;
705 el = el.offsetParent;
712 if (el === docBody) { break; }
714 top -= el.scrollTop || 0;
715 left -= el.scrollLeft || 0;
720 return new L.Point(left, top);
723 create: function (tagName, className, container) {
725 var el = document.createElement(tagName);
726 el.className = className;
729 container.appendChild(el);
735 disableTextSelection: function () {
736 if (document.selection && document.selection.empty) {
737 document.selection.empty();
739 if (!this._onselectstart) {
740 this._onselectstart = document.onselectstart;
741 document.onselectstart = L.Util.falseFn;
745 enableTextSelection: function () {
746 if (document.onselectstart === L.Util.falseFn) {
747 document.onselectstart = this._onselectstart;
748 this._onselectstart = null;
752 hasClass: function (el, name) {
753 return (el.className.length > 0) &&
754 new RegExp("(^|\\s)" + name + "(\\s|$)").test(el.className);
757 addClass: function (el, name) {
758 if (!L.DomUtil.hasClass(el, name)) {
759 el.className += (el.className ? ' ' : '') + name;
763 removeClass: function (el, name) {
765 function replaceFn(w, match) {
766 if (match === name) { return ''; }
770 el.className = el.className
771 .replace(/(\S+)\s*/g, replaceFn)
772 .replace(/(^\s+|\s+$)/, '');
775 setOpacity: function (el, value) {
777 if ('opacity' in el.style) {
778 el.style.opacity = value;
780 } else if (L.Browser.ie) {
783 filterName = 'DXImageTransform.Microsoft.Alpha';
785 // filters collection throws an error if we try to retrieve a filter that doesn't exist
786 try { filter = el.filters.item(filterName); } catch (e) {}
788 value = Math.round(value * 100);
791 filter.Enabled = (value !== 100);
792 filter.Opacity = value;
794 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
799 testProp: function (props) {
801 var style = document.documentElement.style;
803 for (var i = 0; i < props.length; i++) {
804 if (props[i] in style) {
811 getTranslateString: function (point) {
812 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
813 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
814 // (same speed either way), Opera 12 doesn't support translate3d
816 var is3d = L.Browser.webkit3d,
817 open = 'translate' + (is3d ? '3d' : '') + '(',
818 close = (is3d ? ',0' : '') + ')';
820 return open + point.x + 'px,' + point.y + 'px' + close;
823 getScaleString: function (scale, origin) {
825 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
826 scaleStr = ' scale(' + scale + ') ';
828 return preTranslateStr + scaleStr;
831 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
833 el._leaflet_pos = point;
835 if (!disable3D && L.Browser.any3d) {
836 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
838 // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
839 if (L.Browser.mobileWebkit3d) {
840 el.style.WebkitBackfaceVisibility = 'hidden';
843 el.style.left = point.x + 'px';
844 el.style.top = point.y + 'px';
848 getPosition: function (el) {
849 // this method is only used for elements previously positioned using setPosition,
850 // so it's safe to cache the position for performance
851 return el._leaflet_pos;
856 // prefix style property names
858 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
859 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
861 L.DomUtil.TRANSITION = L.DomUtil.testProp(
862 ['transition', 'webkitTransition', 'OTransition', 'MozTransition', 'msTransition']);
864 L.DomUtil.TRANSITION_END =
865 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
866 L.DomUtil.TRANSITION + 'End' : 'transitionend';
870 CM.LatLng represents a geographical point with latitude and longtitude coordinates.
873 L.LatLng = function (rawLat, rawLng, noWrap) { // (Number, Number[, Boolean])
874 var lat = parseFloat(rawLat),
875 lng = parseFloat(rawLng);
877 if (isNaN(lat) || isNaN(lng)) {
878 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
881 if (noWrap !== true) {
882 lat = Math.max(Math.min(lat, 90), -90); // clamp latitude into -90..90
883 lng = (lng + 180) % 360 + ((lng < -180 || lng === 180) ? 180 : -180); // wrap longtitude into -180..180
890 L.Util.extend(L.LatLng, {
891 DEG_TO_RAD: Math.PI / 180,
892 RAD_TO_DEG: 180 / Math.PI,
893 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
896 L.LatLng.prototype = {
897 equals: function (obj) { // (LatLng) -> Boolean
898 if (!obj) { return false; }
902 var margin = Math.max(Math.abs(this.lat - obj.lat), Math.abs(this.lng - obj.lng));
903 return margin <= L.LatLng.MAX_MARGIN;
906 toString: function (precision) { // -> String
908 L.Util.formatNum(this.lat, precision) + ', ' +
909 L.Util.formatNum(this.lng, precision) + ')';
912 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
913 distanceTo: function (other) { // (LatLng) -> Number
914 other = L.latLng(other);
916 var R = 6378137, // earth radius in meters
917 d2r = L.LatLng.DEG_TO_RAD,
918 dLat = (other.lat - this.lat) * d2r,
919 dLon = (other.lng - this.lng) * d2r,
920 lat1 = this.lat * d2r,
921 lat2 = other.lat * d2r,
922 sin1 = Math.sin(dLat / 2),
923 sin2 = Math.sin(dLon / 2);
925 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
927 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
931 L.latLng = function (a, b, c) { // (LatLng) or ([Number, Number]) or (Number, Number, Boolean)
932 if (a instanceof L.LatLng) {
935 if (a instanceof Array) {
936 return new L.LatLng(a[0], a[1]);
941 return new L.LatLng(a, b, c);
947 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
950 L.LatLngBounds = L.Class.extend({
951 initialize: function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
952 if (!southWest) { return; }
954 var latlngs = northEast ? [southWest, northEast] : southWest;
956 for (var i = 0, len = latlngs.length; i < len; i++) {
957 this.extend(latlngs[i]);
961 // extend the bounds to contain the given point or bounds
962 extend: function (obj) { // (LatLng) or (LatLngBounds)
963 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
966 obj = L.latLngBounds(obj);
969 if (obj instanceof L.LatLng) {
970 if (!this._southWest && !this._northEast) {
971 this._southWest = new L.LatLng(obj.lat, obj.lng, true);
972 this._northEast = new L.LatLng(obj.lat, obj.lng, true);
974 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
975 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
977 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
978 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
980 } else if (obj instanceof L.LatLngBounds) {
981 this.extend(obj._southWest);
982 this.extend(obj._northEast);
987 // extend the bounds by a percentage
988 pad: function (bufferRatio) { // (Number) -> LatLngBounds
989 var sw = this._southWest,
990 ne = this._northEast,
991 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
992 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
994 return new L.LatLngBounds(
995 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
996 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
999 getCenter: function () { // -> LatLng
1000 return new L.LatLng(
1001 (this._southWest.lat + this._northEast.lat) / 2,
1002 (this._southWest.lng + this._northEast.lng) / 2);
1005 getSouthWest: function () {
1006 return this._southWest;
1009 getNorthEast: function () {
1010 return this._northEast;
1013 getNorthWest: function () {
1014 return new L.LatLng(this._northEast.lat, this._southWest.lng, true);
1017 getSouthEast: function () {
1018 return new L.LatLng(this._southWest.lat, this._northEast.lng, true);
1021 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1022 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1023 obj = L.latLng(obj);
1025 obj = L.latLngBounds(obj);
1028 var sw = this._southWest,
1029 ne = this._northEast,
1032 if (obj instanceof L.LatLngBounds) {
1033 sw2 = obj.getSouthWest();
1034 ne2 = obj.getNorthEast();
1039 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1040 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1043 intersects: function (bounds) { // (LatLngBounds)
1044 bounds = L.latLngBounds(bounds);
1046 var sw = this._southWest,
1047 ne = this._northEast,
1048 sw2 = bounds.getSouthWest(),
1049 ne2 = bounds.getNorthEast();
1051 var latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1052 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1054 return latIntersects && lngIntersects;
1057 toBBoxString: function () {
1058 var sw = this._southWest,
1059 ne = this._northEast;
1060 return [sw.lng, sw.lat, ne.lng, ne.lat].join(',');
1063 equals: function (bounds) { // (LatLngBounds)
1064 if (!bounds) { return false; }
1066 bounds = L.latLngBounds(bounds);
1068 return this._southWest.equals(bounds.getSouthWest()) &&
1069 this._northEast.equals(bounds.getNorthEast());
1072 isValid: function () {
1073 return !!(this._southWest && this._northEast);
1077 //TODO International date line?
1079 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1080 if (!a || a instanceof L.LatLngBounds) {
1083 return new L.LatLngBounds(a, b);
1088 * L.Projection contains various geographical projections used by CRS classes.
1095 L.Projection.SphericalMercator = {
1096 MAX_LATITUDE: 85.0511287798,
1098 project: function (latlng) { // (LatLng) -> Point
1099 var d = L.LatLng.DEG_TO_RAD,
1100 max = this.MAX_LATITUDE,
1101 lat = Math.max(Math.min(max, latlng.lat), -max),
1104 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1106 return new L.Point(x, y);
1109 unproject: function (point) { // (Point, Boolean) -> LatLng
1110 var d = L.LatLng.RAD_TO_DEG,
1112 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1114 // TODO refactor LatLng wrapping
1115 return new L.LatLng(lat, lng, true);
1121 L.Projection.LonLat = {
1122 project: function (latlng) {
1123 return new L.Point(latlng.lng, latlng.lat);
1126 unproject: function (point) {
1127 return new L.LatLng(point.y, point.x, true);
1134 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1135 var projectedPoint = this.projection.project(latlng),
1136 scale = this.scale(zoom);
1138 return this.transformation._transform(projectedPoint, scale);
1141 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1142 var scale = this.scale(zoom),
1143 untransformedPoint = this.transformation.untransform(point, scale);
1145 return this.projection.unproject(untransformedPoint);
1148 project: function (latlng) {
1149 return this.projection.project(latlng);
1152 scale: function (zoom) {
1153 return 256 * Math.pow(2, zoom);
1159 L.CRS.EPSG3857 = L.Util.extend({}, L.CRS, {
1162 projection: L.Projection.SphericalMercator,
1163 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1165 project: function (latlng) { // (LatLng) -> Point
1166 var projectedPoint = this.projection.project(latlng),
1167 earthRadius = 6378137;
1168 return projectedPoint.multiplyBy(earthRadius);
1172 L.CRS.EPSG900913 = L.Util.extend({}, L.CRS.EPSG3857, {
1178 L.CRS.EPSG4326 = L.Util.extend({}, L.CRS, {
1181 projection: L.Projection.LonLat,
1182 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1187 * L.Map is the central class of the API - it is used to create a map.
1190 L.Map = L.Class.extend({
1192 includes: L.Mixin.Events,
1195 crs: L.CRS.EPSG3857,
1203 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1205 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1208 initialize: function (id, options) { // (HTMLElement or String, Object)
1209 options = L.Util.setOptions(this, options);
1211 this._initContainer(id);
1216 if (options.maxBounds) {
1217 this.setMaxBounds(options.maxBounds);
1220 if (options.center && options.zoom !== undefined) {
1221 this.setView(L.latLng(options.center), options.zoom, true);
1224 this._initLayers(options.layers);
1228 // public methods that modify map state
1230 // replaced by animation-powered implementation in Map.PanAnimation.js
1231 setView: function (center, zoom) {
1232 this._resetView(L.latLng(center), this._limitZoom(zoom));
1236 setZoom: function (zoom) { // (Number)
1237 return this.setView(this.getCenter(), zoom);
1240 zoomIn: function (delta) {
1241 return this.setZoom(this._zoom + (delta || 1));
1244 zoomOut: function (delta) {
1245 return this.setZoom(this._zoom - (delta || 1));
1248 fitBounds: function (bounds) { // (LatLngBounds)
1249 var zoom = this.getBoundsZoom(bounds);
1250 return this.setView(L.latLngBounds(bounds).getCenter(), zoom);
1253 fitWorld: function () {
1254 var sw = new L.LatLng(-60, -170),
1255 ne = new L.LatLng(85, 179);
1257 return this.fitBounds(new L.LatLngBounds(sw, ne));
1260 panTo: function (center) { // (LatLng)
1261 return this.setView(center, this._zoom);
1264 panBy: function (offset) { // (Point)
1265 // replaced with animated panBy in Map.Animation.js
1266 this.fire('movestart');
1268 this._rawPanBy(L.point(offset));
1271 return this.fire('moveend');
1274 setMaxBounds: function (bounds) {
1275 bounds = L.latLngBounds(bounds);
1277 this.options.maxBounds = bounds;
1280 this._boundsMinZoom = null;
1284 var minZoom = this.getBoundsZoom(bounds, true);
1286 this._boundsMinZoom = minZoom;
1289 if (this._zoom < minZoom) {
1290 this.setView(bounds.getCenter(), minZoom);
1292 this.panInsideBounds(bounds);
1299 panInsideBounds: function (bounds) {
1300 bounds = L.latLngBounds(bounds);
1302 var viewBounds = this.getBounds(),
1303 viewSw = this.project(viewBounds.getSouthWest()),
1304 viewNe = this.project(viewBounds.getNorthEast()),
1305 sw = this.project(bounds.getSouthWest()),
1306 ne = this.project(bounds.getNorthEast()),
1310 if (viewNe.y < ne.y) { // north
1311 dy = ne.y - viewNe.y;
1313 if (viewNe.x > ne.x) { // east
1314 dx = ne.x - viewNe.x;
1316 if (viewSw.y > sw.y) { // south
1317 dy = sw.y - viewSw.y;
1319 if (viewSw.x < sw.x) { // west
1320 dx = sw.x - viewSw.x;
1323 return this.panBy(new L.Point(dx, dy, true));
1326 addLayer: function (layer) {
1327 // TODO method is too big, refactor
1329 var id = L.Util.stamp(layer);
1331 if (this._layers[id]) { return this; }
1333 this._layers[id] = layer;
1335 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1336 if (layer.options && !isNaN(layer.options.maxZoom)) {
1337 this._layersMaxZoom = Math.max(this._layersMaxZoom || 0, layer.options.maxZoom);
1339 if (layer.options && !isNaN(layer.options.minZoom)) {
1340 this._layersMinZoom = Math.min(this._layersMinZoom || Infinity, layer.options.minZoom);
1343 // TODO looks ugly, refactor!!!
1344 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1345 this._tileLayersNum++;
1346 this._tileLayersToLoad++;
1347 layer.on('load', this._onTileLayerLoad, this);
1350 this.whenReady(function () {
1352 this.fire('layeradd', {layer: layer});
1358 removeLayer: function (layer) {
1359 var id = L.Util.stamp(layer);
1361 if (!this._layers[id]) { return; }
1363 layer.onRemove(this);
1365 delete this._layers[id];
1367 // TODO looks ugly, refactor
1368 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1369 this._tileLayersNum--;
1370 this._tileLayersToLoad--;
1371 layer.off('load', this._onTileLayerLoad, this);
1374 return this.fire('layerremove', {layer: layer});
1377 hasLayer: function (layer) {
1378 var id = L.Util.stamp(layer);
1379 return this._layers.hasOwnProperty(id);
1382 invalidateSize: function (animate) {
1383 var oldSize = this.getSize();
1385 this._sizeChanged = true;
1387 if (this.options.maxBounds) {
1388 this.setMaxBounds(this.options.maxBounds);
1391 if (!this._loaded) { return this; }
1393 var offset = oldSize._subtract(this.getSize())._divideBy(2)._round();
1395 if (animate === true) {
1398 this._rawPanBy(offset);
1402 clearTimeout(this._sizeTimer);
1403 this._sizeTimer = setTimeout(L.Util.bind(this.fire, this, 'moveend'), 200);
1408 // TODO handler.addTo
1409 addHandler: function (name, HandlerClass) {
1410 if (!HandlerClass) { return; }
1412 this[name] = new HandlerClass(this);
1414 if (this.options[name]) {
1415 this[name].enable();
1422 // public methods for getting map state
1424 getCenter: function () { // (Boolean) -> LatLng
1425 return this.layerPointToLatLng(this._getCenterLayerPoint());
1428 getZoom: function () {
1432 getBounds: function () {
1433 var bounds = this.getPixelBounds(),
1434 sw = this.unproject(bounds.getBottomLeft()),
1435 ne = this.unproject(bounds.getTopRight());
1437 return new L.LatLngBounds(sw, ne);
1440 getMinZoom: function () {
1441 var z1 = this.options.minZoom || 0,
1442 z2 = this._layersMinZoom || 0,
1443 z3 = this._boundsMinZoom || 0;
1445 return Math.max(z1, z2, z3);
1448 getMaxZoom: function () {
1449 var z1 = this.options.maxZoom === undefined ? Infinity : this.options.maxZoom,
1450 z2 = this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom;
1452 return Math.min(z1, z2);
1455 getBoundsZoom: function (bounds, inside) { // (LatLngBounds, Boolean) -> Number
1456 bounds = L.latLngBounds(bounds);
1458 var size = this.getSize(),
1459 zoom = this.options.minZoom || 0,
1460 maxZoom = this.getMaxZoom(),
1461 ne = bounds.getNorthEast(),
1462 sw = bounds.getSouthWest(),
1466 zoomNotFound = true;
1474 nePoint = this.project(ne, zoom);
1475 swPoint = this.project(sw, zoom);
1476 boundsSize = new L.Point(Math.abs(nePoint.x - swPoint.x), Math.abs(swPoint.y - nePoint.y));
1479 zoomNotFound = boundsSize.x <= size.x && boundsSize.y <= size.y;
1481 zoomNotFound = boundsSize.x < size.x || boundsSize.y < size.y;
1483 } while (zoomNotFound && zoom <= maxZoom);
1485 if (zoomNotFound && inside) {
1489 return inside ? zoom : zoom - 1;
1492 getSize: function () {
1493 if (!this._size || this._sizeChanged) {
1494 this._size = new L.Point(
1495 this._container.clientWidth,
1496 this._container.clientHeight);
1498 this._sizeChanged = false;
1500 return this._size.clone();
1503 getPixelBounds: function () {
1504 var topLeftPoint = this._getTopLeftPoint();
1505 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1508 getPixelOrigin: function () {
1509 return this._initialTopLeftPoint;
1512 getPanes: function () {
1516 getContainer: function () {
1517 return this._container;
1521 // TODO replace with universal implementation after refactoring projections
1523 getZoomScale: function (toZoom) {
1524 var crs = this.options.crs;
1525 return crs.scale(toZoom) / crs.scale(this._zoom);
1528 getScaleZoom: function (scale) {
1529 return this._zoom + (Math.log(scale) / Math.LN2);
1533 // conversion methods
1535 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1536 zoom = zoom === undefined ? this._zoom : zoom;
1537 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1540 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1541 zoom = zoom === undefined ? this._zoom : zoom;
1542 return this.options.crs.pointToLatLng(L.point(point), zoom);
1545 layerPointToLatLng: function (point) { // (Point)
1546 var projectedPoint = L.point(point).add(this._initialTopLeftPoint);
1547 return this.unproject(projectedPoint);
1550 latLngToLayerPoint: function (latlng) { // (LatLng)
1551 var projectedPoint = this.project(L.latLng(latlng))._round();
1552 return projectedPoint._subtract(this._initialTopLeftPoint);
1555 containerPointToLayerPoint: function (point) { // (Point)
1556 return L.point(point).subtract(this._getMapPanePos());
1559 layerPointToContainerPoint: function (point) { // (Point)
1560 return L.point(point).add(this._getMapPanePos());
1563 containerPointToLatLng: function (point) {
1564 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1565 return this.layerPointToLatLng(layerPoint);
1568 latLngToContainerPoint: function (latlng) {
1569 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1572 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1573 return L.DomEvent.getMousePosition(e, this._container);
1576 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1577 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1580 mouseEventToLatLng: function (e) { // (MouseEvent)
1581 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1585 // map initialization methods
1587 _initContainer: function (id) {
1588 var container = this._container = L.DomUtil.get(id);
1590 if (container._leaflet) {
1591 throw new Error("Map container is already initialized.");
1594 container._leaflet = true;
1597 _initLayout: function () {
1598 var container = this._container;
1600 container.innerHTML = '';
1601 L.DomUtil.addClass(container, 'leaflet-container');
1603 if (L.Browser.touch) {
1604 L.DomUtil.addClass(container, 'leaflet-touch');
1607 if (this.options.fadeAnimation) {
1608 L.DomUtil.addClass(container, 'leaflet-fade-anim');
1611 var position = L.DomUtil.getStyle(container, 'position');
1613 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
1614 container.style.position = 'relative';
1619 if (this._initControlPos) {
1620 this._initControlPos();
1624 _initPanes: function () {
1625 var panes = this._panes = {};
1627 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
1629 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
1630 this._objectsPane = panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
1632 panes.shadowPane = this._createPane('leaflet-shadow-pane');
1633 panes.overlayPane = this._createPane('leaflet-overlay-pane');
1634 panes.markerPane = this._createPane('leaflet-marker-pane');
1635 panes.popupPane = this._createPane('leaflet-popup-pane');
1637 var zoomHide = ' leaflet-zoom-hide';
1639 if (!this.options.markerZoomAnimation) {
1640 L.DomUtil.addClass(panes.markerPane, zoomHide);
1641 L.DomUtil.addClass(panes.shadowPane, zoomHide);
1642 L.DomUtil.addClass(panes.popupPane, zoomHide);
1646 _createPane: function (className, container) {
1647 return L.DomUtil.create('div', className, container || this._objectsPane);
1652 _initHooks: function () {
1654 for (i = 0, len = this._initializers.length; i < len; i++) {
1655 this._initializers[i].call(this);
1659 _initLayers: function (layers) {
1660 layers = layers ? (layers instanceof Array ? layers : [layers]) : [];
1663 this._tileLayersNum = 0;
1667 for (i = 0, len = layers.length; i < len; i++) {
1668 this.addLayer(layers[i]);
1673 // private methods that modify map state
1675 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
1677 var zoomChanged = (this._zoom !== zoom);
1679 if (!afterZoomAnim) {
1680 this.fire('movestart');
1683 this.fire('zoomstart');
1689 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
1691 if (!preserveMapOffset) {
1692 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
1694 this._initialTopLeftPoint._add(this._getMapPanePos());
1697 this._tileLayersToLoad = this._tileLayersNum;
1699 var loading = !this._loaded;
1700 this._loaded = true;
1702 this.fire('viewreset', {hard: !preserveMapOffset});
1706 if (zoomChanged || afterZoomAnim) {
1707 this.fire('zoomend');
1710 this.fire('moveend', {hard: !preserveMapOffset});
1717 _rawPanBy: function (offset) {
1718 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
1724 _initEvents: function () {
1725 if (!L.DomEvent) { return; }
1727 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
1729 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter', 'mouseleave', 'mousemove', 'contextmenu'],
1732 for (i = 0, len = events.length; i < len; i++) {
1733 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
1736 if (this.options.trackResize) {
1737 L.DomEvent.on(window, 'resize', this._onResize, this);
1741 _onResize: function () {
1742 L.Util.cancelAnimFrame(this._resizeRequest);
1743 this._resizeRequest = L.Util.requestAnimFrame(this.invalidateSize, this, false, this._container);
1746 _onMouseClick: function (e) {
1747 if (!this._loaded || (this.dragging && this.dragging.moved())) { return; }
1749 this.fire('preclick');
1750 this._fireMouseEvent(e);
1753 _fireMouseEvent: function (e) {
1754 if (!this._loaded) { return; }
1758 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
1760 if (!this.hasEventListeners(type)) { return; }
1762 if (type === 'contextmenu') {
1763 L.DomEvent.preventDefault(e);
1766 var containerPoint = this.mouseEventToContainerPoint(e),
1767 layerPoint = this.containerPointToLayerPoint(containerPoint),
1768 latlng = this.layerPointToLatLng(layerPoint);
1772 layerPoint: layerPoint,
1773 containerPoint: containerPoint,
1778 _onTileLayerLoad: function () {
1779 // TODO super-ugly, refactor!!!
1780 // clear scaled tiles after all new tiles are loaded (for performance)
1781 this._tileLayersToLoad--;
1782 if (this._tileLayersNum && !this._tileLayersToLoad && this._tileBg) {
1783 clearTimeout(this._clearTileBgTimer);
1784 this._clearTileBgTimer = setTimeout(L.Util.bind(this._clearTileBg, this), 500);
1788 whenReady: function (callback, context) {
1790 callback.call(context || this, this);
1792 this.on('load', callback, context);
1798 // private methods for getting map state
1800 _getMapPanePos: function () {
1801 return L.DomUtil.getPosition(this._mapPane);
1804 _getTopLeftPoint: function () {
1805 if (!this._loaded) {
1806 throw new Error('Set map center and zoom first.');
1809 return this._initialTopLeftPoint.subtract(this._getMapPanePos());
1812 _getNewTopLeftPoint: function (center, zoom) {
1813 var viewHalf = this.getSize()._divideBy(2);
1814 // TODO round on display, not calculation to increase precision?
1815 return this.project(center, zoom)._subtract(viewHalf)._round();
1818 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
1819 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
1820 return this.project(latlng, newZoom)._subtract(topLeft);
1823 _getCenterLayerPoint: function () {
1824 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
1827 _getCenterOffset: function (center) {
1828 return this.latLngToLayerPoint(center).subtract(this._getCenterLayerPoint());
1831 _limitZoom: function (zoom) {
1832 var min = this.getMinZoom(),
1833 max = this.getMaxZoom();
1835 return Math.max(min, Math.min(max, zoom));
1839 L.Map.addInitHook = function (fn) {
1840 var args = Array.prototype.slice.call(arguments, 1);
1842 var init = typeof fn === 'function' ? fn : function () {
1843 this[fn].apply(this, args);
1846 this.prototype._initializers.push(init);
1849 L.map = function (id, options) {
1850 return new L.Map(id, options);
1855 L.Projection.Mercator = {
1856 MAX_LATITUDE: 85.0840591556,
1858 R_MINOR: 6356752.3142,
1861 project: function (latlng) { // (LatLng) -> Point
1862 var d = L.LatLng.DEG_TO_RAD,
1863 max = this.MAX_LATITUDE,
1864 lat = Math.max(Math.min(max, latlng.lat), -max),
1867 x = latlng.lng * d * r,
1870 eccent = Math.sqrt(1.0 - tmp * tmp),
1871 con = eccent * Math.sin(y);
1873 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
1875 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
1876 y = -r2 * Math.log(ts);
1878 return new L.Point(x, y);
1881 unproject: function (point) { // (Point, Boolean) -> LatLng
1882 var d = L.LatLng.RAD_TO_DEG,
1885 lng = point.x * d / r,
1887 eccent = Math.sqrt(1 - (tmp * tmp)),
1888 ts = Math.exp(- point.y / r2),
1889 phi = (Math.PI / 2) - 2 * Math.atan(ts),
1896 while ((Math.abs(dphi) > tol) && (--i > 0)) {
1897 con = eccent * Math.sin(phi);
1898 dphi = (Math.PI / 2) - 2 * Math.atan(ts * Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
1902 return new L.LatLng(phi * d, lng, true);
1908 L.CRS.EPSG3395 = L.Util.extend({}, L.CRS, {
1911 projection: L.Projection.Mercator,
1913 transformation: (function () {
1914 var m = L.Projection.Mercator,
1918 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
1924 * L.TileLayer is used for standard xyz-numbered tile layers.
1927 L.TileLayer = L.Class.extend({
1928 includes: L.Mixin.Events,
1939 /* (undefined works too)
1942 continuousWorld: false,
1945 detectRetina: false,
1948 unloadInvisibleTiles: L.Browser.mobile,
1949 updateWhenIdle: L.Browser.mobile
1952 initialize: function (url, options) {
1953 options = L.Util.setOptions(this, options);
1955 // detecting retina displays, adjusting tileSize and zoom levels
1956 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
1958 options.tileSize = Math.floor(options.tileSize / 2);
1959 options.zoomOffset++;
1961 if (options.minZoom > 0) {
1964 this.options.maxZoom--;
1969 var subdomains = this.options.subdomains;
1971 if (typeof subdomains === 'string') {
1972 this.options.subdomains = subdomains.split('');
1976 onAdd: function (map) {
1979 // create a container div for tiles
1980 this._initContainer();
1982 // create an image to clone for tiles
1983 this._createTileProto();
1987 'viewreset': this._resetCallback,
1988 'moveend': this._update
1991 if (!this.options.updateWhenIdle) {
1992 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
1993 map.on('move', this._limitedUpdate, this);
2000 addTo: function (map) {
2005 onRemove: function (map) {
2006 map._panes.tilePane.removeChild(this._container);
2009 'viewreset': this._resetCallback,
2010 'moveend': this._update
2013 if (!this.options.updateWhenIdle) {
2014 map.off('move', this._limitedUpdate, this);
2017 this._container = null;
2021 bringToFront: function () {
2022 var pane = this._map._panes.tilePane;
2024 if (this._container) {
2025 pane.appendChild(this._container);
2026 this._setAutoZIndex(pane, Math.max);
2032 bringToBack: function () {
2033 var pane = this._map._panes.tilePane;
2035 if (this._container) {
2036 pane.insertBefore(this._container, pane.firstChild);
2037 this._setAutoZIndex(pane, Math.min);
2043 getAttribution: function () {
2044 return this.options.attribution;
2047 setOpacity: function (opacity) {
2048 this.options.opacity = opacity;
2051 this._updateOpacity();
2057 setZIndex: function (zIndex) {
2058 this.options.zIndex = zIndex;
2059 this._updateZIndex();
2064 setUrl: function (url, noRedraw) {
2074 redraw: function () {
2076 this._map._panes.tilePane.empty = false;
2083 _updateZIndex: function () {
2084 if (this._container && this.options.zIndex !== undefined) {
2085 this._container.style.zIndex = this.options.zIndex;
2089 _setAutoZIndex: function (pane, compare) {
2091 var layers = pane.getElementsByClassName('leaflet-layer'),
2092 edgeZIndex = -compare(Infinity, -Infinity), // -Ifinity for max, Infinity for min
2095 for (var i = 0, len = layers.length; i < len; i++) {
2097 if (layers[i] !== this._container) {
2098 zIndex = parseInt(layers[i].style.zIndex, 10);
2100 if (!isNaN(zIndex)) {
2101 edgeZIndex = compare(edgeZIndex, zIndex);
2106 this.options.zIndex = this._container.style.zIndex = (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2109 _updateOpacity: function () {
2110 L.DomUtil.setOpacity(this._container, this.options.opacity);
2112 // stupid webkit hack to force redrawing of tiles
2114 tiles = this._tiles;
2116 if (L.Browser.webkit) {
2118 if (tiles.hasOwnProperty(i)) {
2119 tiles[i].style.webkitTransform += ' translate(0,0)';
2125 _initContainer: function () {
2126 var tilePane = this._map._panes.tilePane;
2128 if (!this._container || tilePane.empty) {
2129 this._container = L.DomUtil.create('div', 'leaflet-layer');
2131 this._updateZIndex();
2133 tilePane.appendChild(this._container);
2135 if (this.options.opacity < 1) {
2136 this._updateOpacity();
2141 _resetCallback: function (e) {
2142 this._reset(e.hard);
2145 _reset: function (clearOldContainer) {
2147 tiles = this._tiles;
2149 for (key in tiles) {
2150 if (tiles.hasOwnProperty(key)) {
2151 this.fire('tileunload', {tile: tiles[key]});
2156 this._tilesToLoad = 0;
2158 if (this.options.reuseTiles) {
2159 this._unusedTiles = [];
2162 if (clearOldContainer && this._container) {
2163 this._container.innerHTML = "";
2166 this._initContainer();
2169 _update: function (e) {
2171 if (!this._map) { return; }
2173 var bounds = this._map.getPixelBounds(),
2174 zoom = this._map.getZoom(),
2175 tileSize = this.options.tileSize;
2177 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2181 var nwTilePoint = new L.Point(
2182 Math.floor(bounds.min.x / tileSize),
2183 Math.floor(bounds.min.y / tileSize)),
2184 seTilePoint = new L.Point(
2185 Math.floor(bounds.max.x / tileSize),
2186 Math.floor(bounds.max.y / tileSize)),
2187 tileBounds = new L.Bounds(nwTilePoint, seTilePoint);
2189 this._addTilesFromCenterOut(tileBounds);
2191 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2192 this._removeOtherTiles(tileBounds);
2196 _addTilesFromCenterOut: function (bounds) {
2198 center = bounds.getCenter();
2202 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2203 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2204 point = new L.Point(i, j);
2206 if (this._tileShouldBeLoaded(point)) {
2212 var tilesToLoad = queue.length;
2214 if (tilesToLoad === 0) { return; }
2216 // load tiles in order of their distance to center
2217 queue.sort(function (a, b) {
2218 return a.distanceTo(center) - b.distanceTo(center);
2221 var fragment = document.createDocumentFragment();
2223 // if its the first batch of tiles to load
2224 if (!this._tilesToLoad) {
2225 this.fire('loading');
2228 this._tilesToLoad += tilesToLoad;
2230 for (i = 0; i < tilesToLoad; i++) {
2231 this._addTile(queue[i], fragment);
2234 this._container.appendChild(fragment);
2237 _tileShouldBeLoaded: function (tilePoint) {
2238 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2239 return false; // already loaded
2242 if (!this.options.continuousWorld) {
2243 var limit = this._getWrapTileNum();
2245 if (this.options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit) ||
2246 tilePoint.y < 0 || tilePoint.y >= limit) {
2247 return false; // exceeds world bounds
2254 _removeOtherTiles: function (bounds) {
2255 var kArr, x, y, key;
2257 for (key in this._tiles) {
2258 if (this._tiles.hasOwnProperty(key)) {
2259 kArr = key.split(':');
2260 x = parseInt(kArr[0], 10);
2261 y = parseInt(kArr[1], 10);
2263 // remove tile if it's out of bounds
2264 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2265 this._removeTile(key);
2271 _removeTile: function (key) {
2272 var tile = this._tiles[key];
2274 this.fire("tileunload", {tile: tile, url: tile.src});
2276 if (this.options.reuseTiles) {
2277 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2278 this._unusedTiles.push(tile);
2279 } else if (tile.parentNode === this._container) {
2280 this._container.removeChild(tile);
2283 if (!L.Browser.android) { //For https://github.com/CloudMade/Leaflet/issues/137
2284 tile.src = L.Util.emptyImageUrl;
2287 delete this._tiles[key];
2290 _addTile: function (tilePoint, container) {
2291 var tilePos = this._getTilePos(tilePoint);
2293 // get unused tile - or create a new tile
2294 var tile = this._getTile();
2296 // Chrome 20 layouts much faster with top/left (Verify with timeline, frames)
2297 // android 4 browser has display issues with top/left and requires transform instead
2298 // android 3 browser not tested
2299 // android 2 browser requires top/left or tiles disappear on load or first drag (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2300 // (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2301 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2303 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2305 this._loadTile(tile, tilePoint);
2307 if (tile.parentNode !== this._container) {
2308 container.appendChild(tile);
2312 _getZoomForUrl: function () {
2314 var options = this.options,
2315 zoom = this._map.getZoom();
2317 if (options.zoomReverse) {
2318 zoom = options.maxZoom - zoom;
2321 return zoom + options.zoomOffset;
2324 _getTilePos: function (tilePoint) {
2325 var origin = this._map.getPixelOrigin(),
2326 tileSize = this.options.tileSize;
2328 return tilePoint.multiplyBy(tileSize).subtract(origin);
2331 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2333 getTileUrl: function (tilePoint) {
2334 this._adjustTilePoint(tilePoint);
2336 return L.Util.template(this._url, L.Util.extend({
2337 s: this._getSubdomain(tilePoint),
2338 z: this._getZoomForUrl(),
2344 _getWrapTileNum: function () {
2345 // TODO refactor, limit is not valid for non-standard projections
2346 return Math.pow(2, this._getZoomForUrl());
2349 _adjustTilePoint: function (tilePoint) {
2351 var limit = this._getWrapTileNum();
2353 // wrap tile coordinates
2354 if (!this.options.continuousWorld && !this.options.noWrap) {
2355 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2358 if (this.options.tms) {
2359 tilePoint.y = limit - tilePoint.y - 1;
2363 _getSubdomain: function (tilePoint) {
2364 var index = (tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2365 return this.options.subdomains[index];
2368 _createTileProto: function () {
2369 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2370 img.galleryimg = 'no';
2372 var tileSize = this.options.tileSize;
2373 img.style.width = tileSize + 'px';
2374 img.style.height = tileSize + 'px';
2377 _getTile: function () {
2378 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2379 var tile = this._unusedTiles.pop();
2380 this._resetTile(tile);
2383 return this._createTile();
2386 _resetTile: function (tile) {
2387 // Override if data stored on a tile needs to be cleaned up before reuse
2390 _createTile: function () {
2391 var tile = this._tileImg.cloneNode(false);
2392 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2396 _loadTile: function (tile, tilePoint) {
2398 tile.onload = this._tileOnLoad;
2399 tile.onerror = this._tileOnError;
2401 tile.src = this.getTileUrl(tilePoint);
2404 _tileLoaded: function () {
2405 this._tilesToLoad--;
2406 if (!this._tilesToLoad) {
2411 _tileOnLoad: function (e) {
2412 var layer = this._layer;
2414 //Only if we are loading an actual image
2415 if (this.src !== L.Util.emptyImageUrl) {
2416 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2418 layer.fire('tileload', {
2424 layer._tileLoaded();
2427 _tileOnError: function (e) {
2428 var layer = this._layer;
2430 layer.fire('tileerror', {
2435 var newUrl = layer.options.errorTileUrl;
2440 layer._tileLoaded();
2444 L.tileLayer = function (url, options) {
2445 return new L.TileLayer(url, options);
2449 L.TileLayer.WMS = L.TileLayer.extend({
2457 format: 'image/jpeg',
2461 initialize: function (url, options) { // (String, Object)
2465 var wmsParams = L.Util.extend({}, this.defaultWmsParams);
2467 if (options.detectRetina && L.Browser.retina) {
2468 wmsParams.width = wmsParams.height = this.options.tileSize * 2;
2470 wmsParams.width = wmsParams.height = this.options.tileSize;
2473 for (var i in options) {
2474 // all keys that are not TileLayer options go to WMS params
2475 if (!this.options.hasOwnProperty(i)) {
2476 wmsParams[i] = options[i];
2480 this.wmsParams = wmsParams;
2482 L.Util.setOptions(this, options);
2485 onAdd: function (map) {
2487 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2488 this.wmsParams[projectionKey] = map.options.crs.code;
2490 L.TileLayer.prototype.onAdd.call(this, map);
2493 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
2495 var map = this._map,
2496 crs = map.options.crs,
2497 tileSize = this.options.tileSize,
2499 nwPoint = tilePoint.multiplyBy(tileSize),
2500 sePoint = nwPoint.add(new L.Point(tileSize, tileSize)),
2502 nw = crs.project(map.unproject(nwPoint, zoom)),
2503 se = crs.project(map.unproject(sePoint, zoom)),
2505 bbox = [nw.x, se.y, se.x, nw.y].join(','),
2507 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
2509 return url + L.Util.getParamString(this.wmsParams) + "&bbox=" + bbox;
2512 setParams: function (params, noRedraw) {
2514 L.Util.extend(this.wmsParams, params);
2524 L.tileLayer.wms = function (url, options) {
2525 return new L.TileLayer.WMS(url, options);
2529 L.TileLayer.Canvas = L.TileLayer.extend({
2534 initialize: function (options) {
2535 L.Util.setOptions(this, options);
2538 redraw: function () {
2540 tiles = this._tiles;
2543 if (tiles.hasOwnProperty(i)) {
2544 this._redrawTile(tiles[i]);
2549 _redrawTile: function (tile) {
2550 this.drawTile(tile, tile._tilePoint, tile._zoom);
2553 _createTileProto: function () {
2554 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
2556 var tileSize = this.options.tileSize;
2557 proto.width = tileSize;
2558 proto.height = tileSize;
2561 _createTile: function () {
2562 var tile = this._canvasProto.cloneNode(false);
2563 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2567 _loadTile: function (tile, tilePoint, zoom) {
2569 tile._tilePoint = tilePoint;
2572 this.drawTile(tile, tilePoint, zoom);
2574 if (!this.options.async) {
2575 this.tileDrawn(tile);
2579 drawTile: function (tile, tilePoint, zoom) {
2580 // override with rendering code
2583 tileDrawn: function (tile) {
2584 this._tileOnLoad.call(tile);
2589 L.tileLayer.canvas = function (options) {
2590 return new L.TileLayer.Canvas(options);
2593 L.ImageOverlay = L.Class.extend({
2594 includes: L.Mixin.Events,
2600 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
2602 this._bounds = L.latLngBounds(bounds);
2604 L.Util.setOptions(this, options);
2607 onAdd: function (map) {
2614 map._panes.overlayPane.appendChild(this._image);
2616 map.on('viewreset', this._reset, this);
2618 if (map.options.zoomAnimation && L.Browser.any3d) {
2619 map.on('zoomanim', this._animateZoom, this);
2625 onRemove: function (map) {
2626 map.getPanes().overlayPane.removeChild(this._image);
2628 map.off('viewreset', this._reset, this);
2630 if (map.options.zoomAnimation) {
2631 map.off('zoomanim', this._animateZoom, this);
2635 addTo: function (map) {
2640 setOpacity: function (opacity) {
2641 this.options.opacity = opacity;
2642 this._updateOpacity();
2646 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
2647 bringToFront: function () {
2649 this._map._panes.overlayPane.appendChild(this._image);
2654 bringToBack: function () {
2655 var pane = this._map._panes.overlayPane;
2657 pane.insertBefore(this._image, pane.firstChild);
2662 _initImage: function () {
2663 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
2665 if (this._map.options.zoomAnimation && L.Browser.any3d) {
2666 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
2668 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
2671 this._updateOpacity();
2673 //TODO createImage util method to remove duplication
2674 L.Util.extend(this._image, {
2676 onselectstart: L.Util.falseFn,
2677 onmousemove: L.Util.falseFn,
2678 onload: L.Util.bind(this._onImageLoad, this),
2683 _animateZoom: function (e) {
2684 var map = this._map,
2685 image = this._image,
2686 scale = map.getZoomScale(e.zoom),
2687 nw = this._bounds.getNorthWest(),
2688 se = this._bounds.getSouthEast(),
2690 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
2691 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
2692 currentSize = map.latLngToLayerPoint(se)._subtract(map.latLngToLayerPoint(nw)),
2693 origin = topLeft._add(size._subtract(currentSize)._divideBy(2));
2695 image.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
2698 _reset: function () {
2699 var image = this._image,
2700 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
2701 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
2703 L.DomUtil.setPosition(image, topLeft);
2705 image.style.width = size.x + 'px';
2706 image.style.height = size.y + 'px';
2709 _onImageLoad: function () {
2713 _updateOpacity: function () {
2714 L.DomUtil.setOpacity(this._image, this.options.opacity);
2718 L.imageOverlay = function (url, bounds, options) {
2719 return new L.ImageOverlay(url, bounds, options);
2723 L.Icon = L.Class.extend({
2726 iconUrl: (String) (required)
2727 iconSize: (Point) (can be set through CSS)
2728 iconAnchor: (Point) (centered by default if size is specified, can be set in CSS with negative margins)
2729 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
2730 shadowUrl: (Point) (no shadow by default)
2732 shadowAnchor: (Point)
2737 initialize: function (options) {
2738 L.Util.setOptions(this, options);
2741 createIcon: function () {
2742 return this._createIcon('icon');
2745 createShadow: function () {
2746 return this._createIcon('shadow');
2749 _createIcon: function (name) {
2750 var src = this._getIconUrl(name);
2753 if (name === 'icon') {
2754 throw new Error("iconUrl not set in Icon options (see the docs).");
2759 var img = this._createImg(src);
2760 this._setIconStyles(img, name);
2765 _setIconStyles: function (img, name) {
2766 var options = this.options,
2767 size = L.point(options[name + 'Size']),
2770 if (name === 'shadow') {
2771 anchor = L.point(options.shadowAnchor || options.iconAnchor);
2773 anchor = L.point(options.iconAnchor);
2776 if (!anchor && size) {
2777 anchor = size.divideBy(2, true);
2780 img.className = 'leaflet-marker-' + name + ' ' + options.className;
2783 img.style.marginLeft = (-anchor.x) + 'px';
2784 img.style.marginTop = (-anchor.y) + 'px';
2788 img.style.width = size.x + 'px';
2789 img.style.height = size.y + 'px';
2793 _createImg: function (src) {
2796 if (!L.Browser.ie6) {
2797 el = document.createElement('img');
2800 el = document.createElement('div');
2801 el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
2806 _getIconUrl: function (name) {
2807 return this.options[name + 'Url'];
2811 L.icon = function (options) {
2812 return new L.Icon(options);
2817 L.Icon.Default = L.Icon.extend({
2820 iconSize: new L.Point(25, 41),
2821 iconAnchor: new L.Point(12, 41),
2822 popupAnchor: new L.Point(1, -34),
2824 shadowSize: new L.Point(41, 41)
2827 _getIconUrl: function (name) {
2828 var key = name + 'Url';
2830 if (this.options[key]) {
2831 return this.options[key];
2834 var path = L.Icon.Default.imagePath;
2837 throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");
2840 return path + '/marker-' + name + '.png';
2844 L.Icon.Default.imagePath = (function () {
2845 var scripts = document.getElementsByTagName('script'),
2846 leafletRe = /\/?leaflet[\-\._]?([\w\-\._]*)\.js\??/;
2848 var i, len, src, matches;
2850 for (i = 0, len = scripts.length; i < len; i++) {
2851 src = scripts[i].src;
2852 matches = src.match(leafletRe);
2855 return src.split(leafletRe)[0] + '/images';
2862 * L.Marker is used to display clickable/draggable icons on the map.
2865 L.Marker = L.Class.extend({
2867 includes: L.Mixin.Events,
2870 icon: new L.Icon.Default(),
2878 initialize: function (latlng, options) {
2879 L.Util.setOptions(this, options);
2880 this._latlng = L.latLng(latlng);
2883 onAdd: function (map) {
2886 map.on('viewreset', this.update, this);
2891 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
2892 map.on('zoomanim', this._animateZoom, this);
2896 addTo: function (map) {
2901 onRemove: function (map) {
2904 this.fire('remove');
2907 'viewreset': this.update,
2908 'zoomanim': this._animateZoom
2914 getLatLng: function () {
2915 return this._latlng;
2918 setLatLng: function (latlng) {
2919 this._latlng = L.latLng(latlng);
2923 this.fire('move', { latlng: this._latlng });
2926 setZIndexOffset: function (offset) {
2927 this.options.zIndexOffset = offset;
2931 setIcon: function (icon) {
2936 this.options.icon = icon;
2944 update: function () {
2945 if (!this._icon) { return; }
2947 var pos = this._map.latLngToLayerPoint(this._latlng).round();
2951 _initIcon: function () {
2952 var options = this.options,
2954 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
2955 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide',
2956 needOpacityUpdate = false;
2959 this._icon = options.icon.createIcon();
2961 if (options.title) {
2962 this._icon.title = options.title;
2965 this._initInteraction();
2966 needOpacityUpdate = (this.options.opacity < 1);
2968 L.DomUtil.addClass(this._icon, classToAdd);
2970 if (!this._shadow) {
2971 this._shadow = options.icon.createShadow();
2974 L.DomUtil.addClass(this._shadow, classToAdd);
2975 needOpacityUpdate = (this.options.opacity < 1);
2979 if (needOpacityUpdate) {
2980 this._updateOpacity();
2983 var panes = this._map._panes;
2985 panes.markerPane.appendChild(this._icon);
2988 panes.shadowPane.appendChild(this._shadow);
2992 _removeIcon: function () {
2993 var panes = this._map._panes;
2995 panes.markerPane.removeChild(this._icon);
2998 panes.shadowPane.removeChild(this._shadow);
3001 this._icon = this._shadow = null;
3004 _setPos: function (pos) {
3005 L.DomUtil.setPosition(this._icon, pos);
3008 L.DomUtil.setPosition(this._shadow, pos);
3011 this._icon.style.zIndex = pos.y + this.options.zIndexOffset;
3014 _animateZoom: function (opt) {
3015 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3020 _initInteraction: function () {
3021 if (!this.options.clickable) {
3025 var icon = this._icon,
3026 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout'];
3028 L.DomUtil.addClass(icon, 'leaflet-clickable');
3029 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3031 for (var i = 0; i < events.length; i++) {
3032 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3035 if (L.Handler.MarkerDrag) {
3036 this.dragging = new L.Handler.MarkerDrag(this);
3038 if (this.options.draggable) {
3039 this.dragging.enable();
3044 _onMouseClick: function (e) {
3045 if (this.hasEventListeners(e.type)) {
3046 L.DomEvent.stopPropagation(e);
3048 if (this.dragging && this.dragging.moved()) { return; }
3049 if (this._map.dragging && this._map.dragging.moved()) { return; }
3055 _fireMouseEvent: function (e) {
3059 if (e.type !== 'mousedown') {
3060 L.DomEvent.stopPropagation(e);
3064 setOpacity: function (opacity) {
3065 this.options.opacity = opacity;
3067 this._updateOpacity();
3071 _updateOpacity: function () {
3072 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3074 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3079 L.marker = function (latlng, options) {
3080 return new L.Marker(latlng, options);
3084 L.DivIcon = L.Icon.extend({
3086 iconSize: new L.Point(12, 12), // also can be set through CSS
3089 popupAnchor: (Point)
3093 className: 'leaflet-div-icon'
3096 createIcon: function () {
3097 var div = document.createElement('div'),
3098 options = this.options;
3101 div.innerHTML = options.html;
3104 if (options.bgPos) {
3105 div.style.backgroundPosition =
3106 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3109 this._setIconStyles(div, 'icon');
3113 createShadow: function () {
3118 L.divIcon = function (options) {
3119 return new L.DivIcon(options);
3124 L.Map.mergeOptions({
3125 closePopupOnClick: true
3128 L.Popup = L.Class.extend({
3129 includes: L.Mixin.Events,
3137 offset: new L.Point(0, 6),
3138 autoPanPadding: new L.Point(5, 5),
3142 initialize: function (options, source) {
3143 L.Util.setOptions(this, options);
3145 this._source = source;
3148 onAdd: function (map) {
3151 if (!this._container) {
3154 this._updateContent();
3156 var animFade = map.options.fadeAnimation;
3159 L.DomUtil.setOpacity(this._container, 0);
3161 map._panes.popupPane.appendChild(this._container);
3163 map.on('viewreset', this._updatePosition, this);
3165 if (L.Browser.any3d) {
3166 map.on('zoomanim', this._zoomAnimation, this);
3169 if (map.options.closePopupOnClick) {
3170 map.on('preclick', this._close, this);
3176 L.DomUtil.setOpacity(this._container, 1);
3180 addTo: function (map) {
3185 openOn: function (map) {
3186 map.openPopup(this);
3190 onRemove: function (map) {
3191 map._panes.popupPane.removeChild(this._container);
3193 L.Util.falseFn(this._container.offsetWidth); // force reflow
3196 viewreset: this._updatePosition,
3197 preclick: this._close,
3198 zoomanim: this._zoomAnimation
3201 if (map.options.fadeAnimation) {
3202 L.DomUtil.setOpacity(this._container, 0);
3208 setLatLng: function (latlng) {
3209 this._latlng = L.latLng(latlng);
3214 setContent: function (content) {
3215 this._content = content;
3220 _close: function () {
3221 var map = this._map;
3228 .fire('popupclose', {popup: this});
3232 _initLayout: function () {
3233 var prefix = 'leaflet-popup',
3234 container = this._container = L.DomUtil.create('div', prefix + ' ' + this.options.className + ' leaflet-zoom-animated'),
3237 if (this.options.closeButton) {
3238 closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
3239 closeButton.href = '#close';
3240 closeButton.innerHTML = '×';
3242 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3245 var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
3246 L.DomEvent.disableClickPropagation(wrapper);
3248 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3249 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
3251 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3252 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3255 _update: function () {
3256 if (!this._map) { return; }
3258 this._container.style.visibility = 'hidden';
3260 this._updateContent();
3261 this._updateLayout();
3262 this._updatePosition();
3264 this._container.style.visibility = '';
3269 _updateContent: function () {
3270 if (!this._content) { return; }
3272 if (typeof this._content === 'string') {
3273 this._contentNode.innerHTML = this._content;
3275 while (this._contentNode.hasChildNodes()) {
3276 this._contentNode.removeChild(this._contentNode.firstChild);
3278 this._contentNode.appendChild(this._content);
3280 this.fire('contentupdate');
3283 _updateLayout: function () {
3284 var container = this._contentNode,
3285 style = container.style;
3288 style.whiteSpace = 'nowrap';
3290 var width = container.offsetWidth;
3291 width = Math.min(width, this.options.maxWidth);
3292 width = Math.max(width, this.options.minWidth);
3294 style.width = (width + 1) + 'px';
3295 style.whiteSpace = '';
3299 var height = container.offsetHeight,
3300 maxHeight = this.options.maxHeight,
3301 scrolledClass = 'leaflet-popup-scrolled';
3303 if (maxHeight && height > maxHeight) {
3304 style.height = maxHeight + 'px';
3305 L.DomUtil.addClass(container, scrolledClass);
3307 L.DomUtil.removeClass(container, scrolledClass);
3310 this._containerWidth = this._container.offsetWidth;
3313 _updatePosition: function () {
3314 var pos = this._map.latLngToLayerPoint(this._latlng),
3315 is3d = L.Browser.any3d,
3316 offset = this.options.offset;
3319 L.DomUtil.setPosition(this._container, pos);
3322 this._containerBottom = -offset.y - (is3d ? 0 : pos.y);
3323 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (is3d ? 0 : pos.x);
3325 //Bottom position the popup in case the height of the popup changes (images loading etc)
3326 this._container.style.bottom = this._containerBottom + 'px';
3327 this._container.style.left = this._containerLeft + 'px';
3330 _zoomAnimation: function (opt) {
3331 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3333 L.DomUtil.setPosition(this._container, pos);
3336 _adjustPan: function () {
3337 if (!this.options.autoPan) { return; }
3339 var map = this._map,
3340 containerHeight = this._container.offsetHeight,
3341 containerWidth = this._containerWidth,
3343 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
3345 if (L.Browser.any3d) {
3346 layerPos._add(L.DomUtil.getPosition(this._container));
3349 var containerPos = map.layerPointToContainerPoint(layerPos),
3350 padding = this.options.autoPanPadding,
3351 size = map.getSize(),
3355 if (containerPos.x < 0) {
3356 dx = containerPos.x - padding.x;
3358 if (containerPos.x + containerWidth > size.x) {
3359 dx = containerPos.x + containerWidth - size.x + padding.x;
3361 if (containerPos.y < 0) {
3362 dy = containerPos.y - padding.y;
3364 if (containerPos.y + containerHeight > size.y) {
3365 dy = containerPos.y + containerHeight - size.y + padding.y;
3369 map.panBy(new L.Point(dx, dy));
3373 _onCloseButtonClick: function (e) {
3379 L.popup = function (options, source) {
3380 return new L.Popup(options, source);
3385 * Popup extension to L.Marker, adding openPopup & bindPopup methods.
3389 openPopup: function () {
3390 if (this._popup && this._map) {
3391 this._popup.setLatLng(this._latlng);
3392 this._map.openPopup(this._popup);
3398 closePopup: function () {
3400 this._popup._close();
3405 bindPopup: function (content, options) {
3406 var anchor = L.point(this.options.icon.options.popupAnchor) || new L.Point(0, 0);
3408 anchor = anchor.add(L.Popup.prototype.options.offset);
3410 if (options && options.offset) {
3411 anchor = anchor.add(options.offset);
3414 options = L.Util.extend({offset: anchor}, options);
3418 .on('click', this.openPopup, this)
3419 .on('remove', this.closePopup, this)
3420 .on('move', this._movePopup, this);
3423 this._popup = new L.Popup(options, this)
3424 .setContent(content);
3429 unbindPopup: function () {
3433 .off('click', this.openPopup)
3434 .off('remove', this.closePopup)
3435 .off('move', this._movePopup);
3440 _movePopup: function (e) {
3441 this._popup.setLatLng(e.latlng);
3448 openPopup: function (popup) {
3451 this._popup = popup;
3455 .fire('popupopen', {popup: this._popup});
3458 closePopup: function () {
3460 this._popup._close();
3467 * L.LayerGroup is a class to combine several layers so you can manipulate the group (e.g. add/remove it) as one layer.
3470 L.LayerGroup = L.Class.extend({
3471 initialize: function (layers) {
3477 for (i = 0, len = layers.length; i < len; i++) {
3478 this.addLayer(layers[i]);
3483 addLayer: function (layer) {
3484 var id = L.Util.stamp(layer);
3486 this._layers[id] = layer;
3489 this._map.addLayer(layer);
3495 removeLayer: function (layer) {
3496 var id = L.Util.stamp(layer);
3498 delete this._layers[id];
3501 this._map.removeLayer(layer);
3507 clearLayers: function () {
3508 this.eachLayer(this.removeLayer, this);
3512 invoke: function (methodName) {
3513 var args = Array.prototype.slice.call(arguments, 1),
3516 for (i in this._layers) {
3517 if (this._layers.hasOwnProperty(i)) {
3518 layer = this._layers[i];
3520 if (layer[methodName]) {
3521 layer[methodName].apply(layer, args);
3529 onAdd: function (map) {
3531 this.eachLayer(map.addLayer, map);
3534 onRemove: function (map) {
3535 this.eachLayer(map.removeLayer, map);
3539 addTo: function (map) {
3544 eachLayer: function (method, context) {
3545 for (var i in this._layers) {
3546 if (this._layers.hasOwnProperty(i)) {
3547 method.call(context, this._layers[i]);
3553 L.layerGroup = function (layers) {
3554 return new L.LayerGroup(layers);
3559 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and bindPopup method shared between a group of layers.
3562 L.FeatureGroup = L.LayerGroup.extend({
3563 includes: L.Mixin.Events,
3565 addLayer: function (layer) {
3566 if (this._layers[L.Util.stamp(layer)]) {
3570 layer.on('click dblclick mouseover mouseout mousemove contextmenu', this._propagateEvent, this);
3572 L.LayerGroup.prototype.addLayer.call(this, layer);
3574 if (this._popupContent && layer.bindPopup) {
3575 layer.bindPopup(this._popupContent);
3581 removeLayer: function (layer) {
3582 layer.off('click dblclick mouseover mouseout mousemove contextmenu', this._propagateEvent, this);
3584 L.LayerGroup.prototype.removeLayer.call(this, layer);
3586 if (this._popupContent) {
3587 return this.invoke('unbindPopup');
3593 bindPopup: function (content) {
3594 this._popupContent = content;
3595 return this.invoke('bindPopup', content);
3598 setStyle: function (style) {
3599 return this.invoke('setStyle', style);
3602 bringToFront: function () {
3603 return this.invoke('bringToFront');
3606 bringToBack: function () {
3607 return this.invoke('bringToBack');
3610 getBounds: function () {
3611 var bounds = new L.LatLngBounds();
3612 this.eachLayer(function (layer) {
3613 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
3618 _propagateEvent: function (e) {
3622 this.fire(e.type, e);
3626 L.featureGroup = function (layers) {
3627 return new L.FeatureGroup(layers);
3632 * L.Path is a base class for rendering vector paths on a map. It's inherited by Polyline, Circle, etc.
3635 L.Path = L.Class.extend({
3636 includes: [L.Mixin.Events],
3639 // how much to extend the clip area around the map view
3640 // (relative to its size, e.g. 0.5 is half the screen in each direction)
3641 // set in such way that SVG element doesn't exceed 1280px (vector layers flicker on dragend if it is)
3642 CLIP_PADDING: L.Browser.mobile ?
3643 Math.max(0, Math.min(0.5,
3644 (1280 / Math.max(window.innerWidth, window.innerHeight) - 1) / 2))
3656 fillColor: null, //same as color by default
3662 initialize: function (options) {
3663 L.Util.setOptions(this, options);
3666 onAdd: function (map) {
3669 if (!this._container) {
3670 this._initElements();
3674 this.projectLatlngs();
3677 if (this._container) {
3678 this._map._pathRoot.appendChild(this._container);
3682 'viewreset': this.projectLatlngs,
3683 'moveend': this._updatePath
3687 addTo: function (map) {
3692 onRemove: function (map) {
3693 map._pathRoot.removeChild(this._container);
3697 if (L.Browser.vml) {
3698 this._container = null;
3699 this._stroke = null;
3703 this.fire('remove');
3706 'viewreset': this.projectLatlngs,
3707 'moveend': this._updatePath
3711 projectLatlngs: function () {
3712 // do all projection stuff here
3715 setStyle: function (style) {
3716 L.Util.setOptions(this, style);
3718 if (this._container) {
3719 this._updateStyle();
3725 redraw: function () {
3727 this.projectLatlngs();
3735 _updatePathViewport: function () {
3736 var p = L.Path.CLIP_PADDING,
3737 size = this.getSize(),
3738 panePos = L.DomUtil.getPosition(this._mapPane),
3739 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
3740 max = min.add(size.multiplyBy(1 + p * 2)._round());
3742 this._pathViewport = new L.Bounds(min, max);
3747 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
3749 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
3751 L.Path = L.Path.extend({
3756 bringToFront: function () {
3757 var root = this._map._pathRoot,
3758 path = this._container;
3760 if (path && root.lastChild !== path) {
3761 root.appendChild(path);
3766 bringToBack: function () {
3767 var root = this._map._pathRoot,
3768 path = this._container,
3769 first = root.firstChild;
3771 if (path && first !== path) {
3772 root.insertBefore(path, first);
3777 getPathString: function () {
3778 // form path string here
3781 _createElement: function (name) {
3782 return document.createElementNS(L.Path.SVG_NS, name);
3785 _initElements: function () {
3786 this._map._initPathRoot();
3791 _initPath: function () {
3792 this._container = this._createElement('g');
3794 this._path = this._createElement('path');
3795 this._container.appendChild(this._path);
3798 _initStyle: function () {
3799 if (this.options.stroke) {
3800 this._path.setAttribute('stroke-linejoin', 'round');
3801 this._path.setAttribute('stroke-linecap', 'round');
3803 if (this.options.fill) {
3804 this._path.setAttribute('fill-rule', 'evenodd');
3806 this._updateStyle();
3809 _updateStyle: function () {
3810 if (this.options.stroke) {
3811 this._path.setAttribute('stroke', this.options.color);
3812 this._path.setAttribute('stroke-opacity', this.options.opacity);
3813 this._path.setAttribute('stroke-width', this.options.weight);
3814 if (this.options.dashArray) {
3815 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
3817 this._path.removeAttribute('stroke-dasharray');
3820 this._path.setAttribute('stroke', 'none');
3822 if (this.options.fill) {
3823 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
3824 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
3826 this._path.setAttribute('fill', 'none');
3830 _updatePath: function () {
3831 var str = this.getPathString();
3833 // fix webkit empty string parsing bug
3836 this._path.setAttribute('d', str);
3839 // TODO remove duplication with L.Map
3840 _initEvents: function () {
3841 if (this.options.clickable) {
3842 if (L.Browser.svg || !L.Browser.vml) {
3843 this._path.setAttribute('class', 'leaflet-clickable');
3846 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
3848 var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'mousemove', 'contextmenu'];
3849 for (var i = 0; i < events.length; i++) {
3850 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
3855 _onMouseClick: function (e) {
3856 if (this._map.dragging && this._map.dragging.moved()) {
3860 this._fireMouseEvent(e);
3863 _fireMouseEvent: function (e) {
3864 if (!this.hasEventListeners(e.type)) {
3868 var map = this._map,
3869 containerPoint = map.mouseEventToContainerPoint(e),
3870 layerPoint = map.containerPointToLayerPoint(containerPoint),
3871 latlng = map.layerPointToLatLng(layerPoint);
3875 layerPoint: layerPoint,
3876 containerPoint: containerPoint,
3880 if (e.type === 'contextmenu') {
3881 L.DomEvent.preventDefault(e);
3883 L.DomEvent.stopPropagation(e);
3888 _initPathRoot: function () {
3889 if (!this._pathRoot) {
3890 this._pathRoot = L.Path.prototype._createElement('svg');
3891 this._panes.overlayPane.appendChild(this._pathRoot);
3893 if (this.options.zoomAnimation && L.Browser.any3d) {
3894 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
3897 'zoomanim': this._animatePathZoom,
3898 'zoomend': this._endPathZoom
3901 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
3904 this.on('moveend', this._updateSvgViewport);
3905 this._updateSvgViewport();
3909 _animatePathZoom: function (opt) {
3910 var scale = this.getZoomScale(opt.zoom),
3911 offset = this._getCenterOffset(opt.center).divideBy(1 - 1 / scale),
3912 viewportPos = this.containerPointToLayerPoint(this.getSize().multiplyBy(-L.Path.CLIP_PADDING)),
3913 origin = viewportPos.add(offset).round();
3915 this._pathRoot.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString((origin.multiplyBy(-1).add(L.DomUtil.getPosition(this._pathRoot)).multiplyBy(scale).add(origin))) + ' scale(' + scale + ') ';
3917 this._pathZooming = true;
3920 _endPathZoom: function () {
3921 this._pathZooming = false;
3924 _updateSvgViewport: function () {
3925 if (this._pathZooming) {
3926 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
3927 // When the zoom animation ends we will be updated again anyway
3928 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
3932 this._updatePathViewport();
3934 var vp = this._pathViewport,
3937 width = max.x - min.x,
3938 height = max.y - min.y,
3939 root = this._pathRoot,
3940 pane = this._panes.overlayPane;
3942 // Hack to make flicker on drag end on mobile webkit less irritating
3943 if (L.Browser.mobileWebkit) {
3944 pane.removeChild(root);
3947 L.DomUtil.setPosition(root, min);
3948 root.setAttribute('width', width);
3949 root.setAttribute('height', height);
3950 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
3952 if (L.Browser.mobileWebkit) {
3953 pane.appendChild(root);
3960 * Popup extension to L.Path (polylines, polygons, circles), adding bindPopup method.
3965 bindPopup: function (content, options) {
3967 if (!this._popup || this._popup.options !== options) {
3968 this._popup = new L.Popup(options, this);
3971 this._popup.setContent(content);
3973 if (!this._popupHandlersAdded) {
3975 .on('click', this._openPopup, this)
3976 .on('remove', this._closePopup, this);
3977 this._popupHandlersAdded = true;
3983 unbindPopup: function () {
3987 .off('click', this.openPopup)
3988 .off('remove', this.closePopup);
3993 openPopup: function (latlng) {
3996 latlng = latlng || this._latlng ||
3997 this._latlngs[Math.floor(this._latlngs.length / 2)];
3999 this._openPopup({latlng: latlng});
4005 _openPopup: function (e) {
4006 this._popup.setLatLng(e.latlng);
4007 this._map.openPopup(this._popup);
4010 _closePopup: function () {
4011 this._popup._close();
4017 * Vector rendering for IE6-8 through VML.
4018 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4021 L.Browser.vml = !L.Browser.svg && (function () {
4023 var div = document.createElement('div');
4024 div.innerHTML = '<v:shape adj="1"/>';
4026 var shape = div.firstChild;
4027 shape.style.behavior = 'url(#default#VML)';
4029 return shape && (typeof shape.adj === 'object');
4035 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4041 _createElement: (function () {
4043 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4044 return function (name) {
4045 return document.createElement('<lvml:' + name + ' class="lvml">');
4048 return function (name) {
4049 return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4054 _initPath: function () {
4055 var container = this._container = this._createElement('shape');
4056 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4057 if (this.options.clickable) {
4058 L.DomUtil.addClass(container, 'leaflet-clickable');
4060 container.coordsize = '1 1';
4062 this._path = this._createElement('path');
4063 container.appendChild(this._path);
4065 this._map._pathRoot.appendChild(container);
4068 _initStyle: function () {
4069 this._updateStyle();
4072 _updateStyle: function () {
4073 var stroke = this._stroke,
4075 options = this.options,
4076 container = this._container;
4078 container.stroked = options.stroke;
4079 container.filled = options.fill;
4081 if (options.stroke) {
4083 stroke = this._stroke = this._createElement('stroke');
4084 stroke.endcap = 'round';
4085 container.appendChild(stroke);
4087 stroke.weight = options.weight + 'px';
4088 stroke.color = options.color;
4089 stroke.opacity = options.opacity;
4090 if (options.dashArray) {
4091 stroke.dashStyle = options.dashArray.replace(/ *, */g, ' ');
4093 stroke.dashStyle = '';
4095 } else if (stroke) {
4096 container.removeChild(stroke);
4097 this._stroke = null;
4102 fill = this._fill = this._createElement('fill');
4103 container.appendChild(fill);
4105 fill.color = options.fillColor || options.color;
4106 fill.opacity = options.fillOpacity;
4108 container.removeChild(fill);
4113 _updatePath: function () {
4114 var style = this._container.style;
4116 style.display = 'none';
4117 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4122 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4123 _initPathRoot: function () {
4124 if (this._pathRoot) { return; }
4126 var root = this._pathRoot = document.createElement('div');
4127 root.className = 'leaflet-vml-container';
4128 this._panes.overlayPane.appendChild(root);
4130 this.on('moveend', this._updatePathViewport);
4131 this._updatePathViewport();
4137 * Vector rendering for all browsers that support canvas.
4140 L.Browser.canvas = (function () {
4141 return !!document.createElement('canvas').getContext;
4144 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4146 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4151 redraw: function () {
4153 this.projectLatlngs();
4154 this._requestUpdate();
4159 setStyle: function (style) {
4160 L.Util.setOptions(this, style);
4163 this._updateStyle();
4164 this._requestUpdate();
4169 onRemove: function (map) {
4171 .off('viewreset', this.projectLatlngs, this)
4172 .off('moveend', this._updatePath, this);
4174 this._requestUpdate();
4179 _requestUpdate: function () {
4180 if (this._map && !L.Path._updateRequest) {
4181 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4185 _fireMapMoveEnd: function () {
4186 L.Path._updateRequest = null;
4187 this.fire('moveend');
4190 _initElements: function () {
4191 this._map._initPathRoot();
4192 this._ctx = this._map._canvasCtx;
4195 _updateStyle: function () {
4196 var options = this.options;
4198 if (options.stroke) {
4199 this._ctx.lineWidth = options.weight;
4200 this._ctx.strokeStyle = options.color;
4203 this._ctx.fillStyle = options.fillColor || options.color;
4207 _drawPath: function () {
4208 var i, j, len, len2, point, drawMethod;
4210 this._ctx.beginPath();
4212 for (i = 0, len = this._parts.length; i < len; i++) {
4213 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4214 point = this._parts[i][j];
4215 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4217 this._ctx[drawMethod](point.x, point.y);
4219 // TODO refactor ugly hack
4220 if (this instanceof L.Polygon) {
4221 this._ctx.closePath();
4226 _checkIfEmpty: function () {
4227 return !this._parts.length;
4230 _updatePath: function () {
4231 if (this._checkIfEmpty()) { return; }
4233 var ctx = this._ctx,
4234 options = this.options;
4238 this._updateStyle();
4241 if (options.fillOpacity < 1) {
4242 ctx.globalAlpha = options.fillOpacity;
4247 if (options.stroke) {
4248 if (options.opacity < 1) {
4249 ctx.globalAlpha = options.opacity;
4256 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
4259 _initEvents: function () {
4260 if (this.options.clickable) {
4262 // TODO mouseover, mouseout, dblclick
4263 this._map.on('click', this._onClick, this);
4267 _onClick: function (e) {
4268 if (this._containsPoint(e.layerPoint)) {
4269 this.fire('click', e);
4274 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
4275 _initPathRoot: function () {
4276 var root = this._pathRoot,
4280 root = this._pathRoot = document.createElement("canvas");
4281 root.style.position = 'absolute';
4282 ctx = this._canvasCtx = root.getContext('2d');
4284 ctx.lineCap = "round";
4285 ctx.lineJoin = "round";
4287 this._panes.overlayPane.appendChild(root);
4289 if (this.options.zoomAnimation) {
4290 this._pathRoot.className = 'leaflet-zoom-animated';
4291 this.on('zoomanim', this._animatePathZoom);
4292 this.on('zoomend', this._endPathZoom);
4294 this.on('moveend', this._updateCanvasViewport);
4295 this._updateCanvasViewport();
4299 _updateCanvasViewport: function () {
4300 if (this._pathZooming) {
4301 //Don't redraw while zooming. See _updateSvgViewport for more details
4304 this._updatePathViewport();
4306 var vp = this._pathViewport,
4308 size = vp.max.subtract(min),
4309 root = this._pathRoot;
4311 //TODO check if this works properly on mobile webkit
4312 L.DomUtil.setPosition(root, min);
4313 root.width = size.x;
4314 root.height = size.y;
4315 root.getContext('2d').translate(-min.x, -min.y);
4321 * L.LineUtil contains different utility functions for line segments
4322 * and polylines (clipping, simplification, distances, etc.)
4327 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
4328 // Improves rendering performance dramatically by lessening the number of points to draw.
4330 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
4331 if (!tolerance || !points.length) {
4332 return points.slice();
4335 var sqTolerance = tolerance * tolerance;
4337 // stage 1: vertex reduction
4338 points = this._reducePoints(points, sqTolerance);
4340 // stage 2: Douglas-Peucker simplification
4341 points = this._simplifyDP(points, sqTolerance);
4346 // distance from a point to a segment between two points
4347 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
4348 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
4351 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
4352 return this._sqClosestPointOnSegment(p, p1, p2);
4355 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
4356 _simplifyDP: function (points, sqTolerance) {
4358 var len = points.length,
4359 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
4360 markers = new ArrayConstructor(len);
4362 markers[0] = markers[len - 1] = 1;
4364 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
4369 for (i = 0; i < len; i++) {
4371 newPoints.push(points[i]);
4378 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
4383 for (i = first + 1; i <= last - 1; i++) {
4384 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
4386 if (sqDist > maxSqDist) {
4392 if (maxSqDist > sqTolerance) {
4395 this._simplifyDPStep(points, markers, sqTolerance, first, index);
4396 this._simplifyDPStep(points, markers, sqTolerance, index, last);
4400 // reduce points that are too close to each other to a single point
4401 _reducePoints: function (points, sqTolerance) {
4402 var reducedPoints = [points[0]];
4404 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
4405 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
4406 reducedPoints.push(points[i]);
4410 if (prev < len - 1) {
4411 reducedPoints.push(points[len - 1]);
4413 return reducedPoints;
4416 /*jshint bitwise:false */ // temporarily allow bitwise oprations
4418 // Cohen-Sutherland line clipping algorithm.
4419 // Used to avoid rendering parts of a polyline that are not currently visible.
4421 clipSegment: function (a, b, bounds, useLastCode) {
4422 var min = bounds.min,
4425 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
4426 codeB = this._getBitCode(b, bounds);
4428 // save 2nd code to avoid calculating it on the next segment
4429 this._lastCode = codeB;
4432 // if a,b is inside the clip window (trivial accept)
4433 if (!(codeA | codeB)) {
4435 // if a,b is outside the clip window (trivial reject)
4436 } else if (codeA & codeB) {
4440 var codeOut = codeA || codeB,
4441 p = this._getEdgeIntersection(a, b, codeOut, bounds),
4442 newCode = this._getBitCode(p, bounds);
4444 if (codeOut === codeA) {
4455 _getEdgeIntersection: function (a, b, code, bounds) {
4461 if (code & 8) { // top
4462 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
4463 } else if (code & 4) { // bottom
4464 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
4465 } else if (code & 2) { // right
4466 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
4467 } else if (code & 1) { // left
4468 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
4472 _getBitCode: function (/*Point*/ p, bounds) {
4475 if (p.x < bounds.min.x) { // left
4477 } else if (p.x > bounds.max.x) { // right
4480 if (p.y < bounds.min.y) { // bottom
4482 } else if (p.y > bounds.max.y) { // top
4489 /*jshint bitwise:true */
4491 // square distance (to avoid unnecessary Math.sqrt calls)
4492 _sqDist: function (p1, p2) {
4493 var dx = p2.x - p1.x,
4495 return dx * dx + dy * dy;
4498 // return closest point on segment or distance to that point
4499 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
4504 dot = dx * dx + dy * dy,
4508 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
4522 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
4527 L.Polyline = L.Path.extend({
4528 initialize: function (latlngs, options) {
4529 L.Path.prototype.initialize.call(this, options);
4531 this._latlngs = this._convertLatLngs(latlngs);
4533 // TODO refactor: move to Polyline.Edit.js
4534 if (L.Handler.PolyEdit) {
4535 this.editing = new L.Handler.PolyEdit(this);
4537 if (this.options.editable) {
4538 this.editing.enable();
4544 // how much to simplify the polyline on each zoom level
4545 // more = better performance and smoother look, less = more accurate
4550 projectLatlngs: function () {
4551 this._originalPoints = [];
4553 for (var i = 0, len = this._latlngs.length; i < len; i++) {
4554 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
4558 getPathString: function () {
4559 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
4560 str += this._getPathPartStr(this._parts[i]);
4565 getLatLngs: function () {
4566 return this._latlngs;
4569 setLatLngs: function (latlngs) {
4570 this._latlngs = this._convertLatLngs(latlngs);
4571 return this.redraw();
4574 addLatLng: function (latlng) {
4575 this._latlngs.push(L.latLng(latlng));
4576 return this.redraw();
4579 spliceLatLngs: function (index, howMany) {
4580 var removed = [].splice.apply(this._latlngs, arguments);
4581 this._convertLatLngs(this._latlngs);
4586 closestLayerPoint: function (p) {
4587 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
4589 for (var j = 0, jLen = parts.length; j < jLen; j++) {
4590 var points = parts[j];
4591 for (var i = 1, len = points.length; i < len; i++) {
4594 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
4595 if (sqDist < minDistance) {
4596 minDistance = sqDist;
4597 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
4602 minPoint.distance = Math.sqrt(minDistance);
4607 getBounds: function () {
4608 var b = new L.LatLngBounds();
4609 var latLngs = this.getLatLngs();
4610 for (var i = 0, len = latLngs.length; i < len; i++) {
4611 b.extend(latLngs[i]);
4616 // TODO refactor: move to Polyline.Edit.js
4617 onAdd: function (map) {
4618 L.Path.prototype.onAdd.call(this, map);
4620 if (this.editing && this.editing.enabled()) {
4621 this.editing.addHooks();
4625 onRemove: function (map) {
4626 if (this.editing && this.editing.enabled()) {
4627 this.editing.removeHooks();
4630 L.Path.prototype.onRemove.call(this, map);
4633 _convertLatLngs: function (latlngs) {
4635 for (i = 0, len = latlngs.length; i < len; i++) {
4636 if (latlngs[i] instanceof Array && typeof latlngs[i][0] !== 'number') {
4639 latlngs[i] = L.latLng(latlngs[i]);
4644 _initEvents: function () {
4645 L.Path.prototype._initEvents.call(this);
4648 _getPathPartStr: function (points) {
4649 var round = L.Path.VML;
4651 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
4656 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
4661 _clipPoints: function () {
4662 var points = this._originalPoints,
4663 len = points.length,
4666 if (this.options.noClip) {
4667 this._parts = [points];
4673 var parts = this._parts,
4674 vp = this._map._pathViewport,
4677 for (i = 0, k = 0; i < len - 1; i++) {
4678 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
4683 parts[k] = parts[k] || [];
4684 parts[k].push(segment[0]);
4686 // if segment goes out of screen, or it's the last one, it's the end of the line part
4687 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
4688 parts[k].push(segment[1]);
4694 // simplify each clipped part of the polyline
4695 _simplifyPoints: function () {
4696 var parts = this._parts,
4699 for (var i = 0, len = parts.length; i < len; i++) {
4700 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
4704 _updatePath: function () {
4705 if (!this._map) { return; }
4708 this._simplifyPoints();
4710 L.Path.prototype._updatePath.call(this);
4714 L.polyline = function (latlngs, options) {
4715 return new L.Polyline(latlngs, options);
4720 * L.PolyUtil contains utilify functions for polygons (clipping, etc.).
4723 /*jshint bitwise:false */ // allow bitwise oprations here
4728 * Sutherland-Hodgeman polygon clipping algorithm.
4729 * Used to avoid rendering parts of a polygon that are not currently visible.
4731 L.PolyUtil.clipPolygon = function (points, bounds) {
4732 var min = bounds.min,
4735 edges = [1, 4, 2, 8],
4741 for (i = 0, len = points.length; i < len; i++) {
4742 points[i]._code = lu._getBitCode(points[i], bounds);
4745 // for each edge (left, bottom, right, top)
4746 for (k = 0; k < 4; k++) {
4750 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
4754 // if a is inside the clip window
4755 if (!(a._code & edge)) {
4756 // if b is outside the clip window (a->b goes out of screen)
4757 if (b._code & edge) {
4758 p = lu._getEdgeIntersection(b, a, edge, bounds);
4759 p._code = lu._getBitCode(p, bounds);
4760 clippedPoints.push(p);
4762 clippedPoints.push(a);
4764 // else if b is inside the clip window (a->b enters the screen)
4765 } else if (!(b._code & edge)) {
4766 p = lu._getEdgeIntersection(b, a, edge, bounds);
4767 p._code = lu._getBitCode(p, bounds);
4768 clippedPoints.push(p);
4771 points = clippedPoints;
4777 /*jshint bitwise:true */
4781 * L.Polygon is used to display polygons on a map.
4784 L.Polygon = L.Polyline.extend({
4789 initialize: function (latlngs, options) {
4790 L.Polyline.prototype.initialize.call(this, latlngs, options);
4792 if (latlngs && (latlngs[0] instanceof Array) && (typeof latlngs[0][0] !== 'number')) {
4793 this._latlngs = this._convertLatLngs(latlngs[0]);
4794 this._holes = latlngs.slice(1);
4798 projectLatlngs: function () {
4799 L.Polyline.prototype.projectLatlngs.call(this);
4801 // project polygon holes points
4802 // TODO move this logic to Polyline to get rid of duplication
4803 this._holePoints = [];
4809 for (var i = 0, len = this._holes.length, hole; i < len; i++) {
4810 this._holePoints[i] = [];
4812 for (var j = 0, len2 = this._holes[i].length; j < len2; j++) {
4813 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
4818 _clipPoints: function () {
4819 var points = this._originalPoints,
4822 this._parts = [points].concat(this._holePoints);
4824 if (this.options.noClip) {
4828 for (var i = 0, len = this._parts.length; i < len; i++) {
4829 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
4830 if (!clipped.length) {
4833 newParts.push(clipped);
4836 this._parts = newParts;
4839 _getPathPartStr: function (points) {
4840 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
4841 return str + (L.Browser.svg ? 'z' : 'x');
4845 L.polygon = function (latlngs, options) {
4846 return new L.Polygon(latlngs, options);
4851 * Contains L.MultiPolyline and L.MultiPolygon layers.
4855 function createMulti(Klass) {
4856 return L.FeatureGroup.extend({
4857 initialize: function (latlngs, options) {
4859 this._options = options;
4860 this.setLatLngs(latlngs);
4863 setLatLngs: function (latlngs) {
4864 var i = 0, len = latlngs.length;
4866 this.eachLayer(function (layer) {
4868 layer.setLatLngs(latlngs[i++]);
4870 this.removeLayer(layer);
4875 this.addLayer(new Klass(latlngs[i++], this._options));
4883 L.MultiPolyline = createMulti(L.Polyline);
4884 L.MultiPolygon = createMulti(L.Polygon);
4886 L.multiPolyline = function (latlngs, options) {
4887 return new L.MultiPolyline(latlngs, options);
4890 L.multiPolygon = function (latlngs, options) {
4891 return new L.MultiPolygon(latlngs, options);
4897 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds
4900 L.Rectangle = L.Polygon.extend({
4901 initialize: function (latLngBounds, options) {
4902 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
4905 setBounds: function (latLngBounds) {
4906 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
4909 _boundsToLatLngs: function (latLngBounds) {
4910 latLngBounds = L.latLngBounds(latLngBounds);
4912 latLngBounds.getSouthWest(),
4913 latLngBounds.getNorthWest(),
4914 latLngBounds.getNorthEast(),
4915 latLngBounds.getSouthEast(),
4916 latLngBounds.getSouthWest()
4921 L.rectangle = function (latLngBounds, options) {
4922 return new L.Rectangle(latLngBounds, options);
4927 * L.Circle is a circle overlay (with a certain radius in meters).
4930 L.Circle = L.Path.extend({
4931 initialize: function (latlng, radius, options) {
4932 L.Path.prototype.initialize.call(this, options);
4934 this._latlng = L.latLng(latlng);
4935 this._mRadius = radius;
4942 setLatLng: function (latlng) {
4943 this._latlng = L.latLng(latlng);
4944 return this.redraw();
4947 setRadius: function (radius) {
4948 this._mRadius = radius;
4949 return this.redraw();
4952 projectLatlngs: function () {
4953 var lngRadius = this._getLngRadius(),
4954 latlng2 = new L.LatLng(this._latlng.lat, this._latlng.lng - lngRadius, true),
4955 point2 = this._map.latLngToLayerPoint(latlng2);
4957 this._point = this._map.latLngToLayerPoint(this._latlng);
4958 this._radius = Math.max(Math.round(this._point.x - point2.x), 1);
4961 getBounds: function () {
4962 var lngRadius = this._getLngRadius(),
4963 latRadius = (this._mRadius / 40075017) * 360,
4964 latlng = this._latlng,
4965 sw = new L.LatLng(latlng.lat - latRadius, latlng.lng - lngRadius),
4966 ne = new L.LatLng(latlng.lat + latRadius, latlng.lng + lngRadius);
4968 return new L.LatLngBounds(sw, ne);
4971 getLatLng: function () {
4972 return this._latlng;
4975 getPathString: function () {
4976 var p = this._point,
4979 if (this._checkIfEmpty()) {
4983 if (L.Browser.svg) {
4984 return "M" + p.x + "," + (p.y - r) +
4985 "A" + r + "," + r + ",0,1,1," +
4986 (p.x - 0.1) + "," + (p.y - r) + " z";
4990 return "AL " + p.x + "," + p.y + " " + r + "," + r + " 0," + (65535 * 360);
4994 getRadius: function () {
4995 return this._mRadius;
4998 // TODO Earth hardcoded, move into projection code!
5000 _getLatRadius: function () {
5001 return (this._mRadius / 40075017) * 360;
5004 _getLngRadius: function () {
5005 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5008 _checkIfEmpty: function () {
5012 var vp = this._map._pathViewport,
5016 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5017 p.x + r < vp.min.x || p.y + r < vp.min.y;
5021 L.circle = function (latlng, radius, options) {
5022 return new L.Circle(latlng, radius, options);
5027 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5030 L.CircleMarker = L.Circle.extend({
5036 initialize: function (latlng, options) {
5037 L.Circle.prototype.initialize.call(this, latlng, null, options);
5038 this._radius = this.options.radius;
5041 projectLatlngs: function () {
5042 this._point = this._map.latLngToLayerPoint(this._latlng);
5045 setRadius: function (radius) {
5046 this._radius = radius;
5047 return this.redraw();
5051 L.circleMarker = function (latlng, options) {
5052 return new L.CircleMarker(latlng, options);
5057 L.Polyline.include(!L.Path.CANVAS ? {} : {
5058 _containsPoint: function (p, closed) {
5059 var i, j, k, len, len2, dist, part,
5060 w = this.options.weight / 2;
5062 if (L.Browser.touch) {
5063 w += 10; // polyline click tolerance on touch devices
5066 for (i = 0, len = this._parts.length; i < len; i++) {
5067 part = this._parts[i];
5068 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5069 if (!closed && (j === 0)) {
5073 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5086 L.Polygon.include(!L.Path.CANVAS ? {} : {
5087 _containsPoint: function (p) {
5093 // TODO optimization: check if within bounds first
5095 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5096 // click on polygon border
5100 // ray casting algorithm for detecting if point is in polygon
5102 for (i = 0, len = this._parts.length; i < len; i++) {
5103 part = this._parts[i];
5105 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5109 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5110 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5122 * Circle canvas specific drawing parts.
5125 L.Circle.include(!L.Path.CANVAS ? {} : {
5126 _drawPath: function () {
5127 var p = this._point;
5128 this._ctx.beginPath();
5129 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5132 _containsPoint: function (p) {
5133 var center = this._point,
5134 w2 = this.options.stroke ? this.options.weight / 2 : 0;
5136 return (p.distanceTo(center) <= this._radius + w2);
5141 L.GeoJSON = L.FeatureGroup.extend({
5142 initialize: function (geojson, options) {
5143 L.Util.setOptions(this, options);
5148 this.addData(geojson);
5152 addData: function (geojson) {
5153 var features = geojson instanceof Array ? geojson : geojson.features,
5157 for (i = 0, len = features.length; i < len; i++) {
5158 this.addData(features[i]);
5163 var options = this.options;
5165 if (options.filter && !options.filter(geojson)) { return; }
5167 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer);
5168 layer.feature = geojson;
5170 this.resetStyle(layer);
5172 if (options.onEachFeature) {
5173 options.onEachFeature(geojson, layer);
5176 return this.addLayer(layer);
5179 resetStyle: function (layer) {
5180 var style = this.options.style;
5182 this._setLayerStyle(layer, style);
5186 setStyle: function (style) {
5187 this.eachLayer(function (layer) {
5188 this._setLayerStyle(layer, style);
5192 _setLayerStyle: function (layer, style) {
5193 if (typeof style === 'function') {
5194 style = style(layer.feature);
5196 if (layer.setStyle) {
5197 layer.setStyle(style);
5202 L.Util.extend(L.GeoJSON, {
5203 geometryToLayer: function (geojson, pointToLayer) {
5204 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
5205 coords = geometry.coordinates,
5207 latlng, latlngs, i, len, layer;
5209 switch (geometry.type) {
5211 latlng = this.coordsToLatLng(coords);
5212 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
5215 for (i = 0, len = coords.length; i < len; i++) {
5216 latlng = this.coordsToLatLng(coords[i]);
5217 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
5220 return new L.FeatureGroup(layers);
5223 latlngs = this.coordsToLatLngs(coords);
5224 return new L.Polyline(latlngs);
5227 latlngs = this.coordsToLatLngs(coords, 1);
5228 return new L.Polygon(latlngs);
5230 case 'MultiLineString':
5231 latlngs = this.coordsToLatLngs(coords, 1);
5232 return new L.MultiPolyline(latlngs);
5234 case "MultiPolygon":
5235 latlngs = this.coordsToLatLngs(coords, 2);
5236 return new L.MultiPolygon(latlngs);
5238 case "GeometryCollection":
5239 for (i = 0, len = geometry.geometries.length; i < len; i++) {
5240 layer = this.geometryToLayer(geometry.geometries[i], pointToLayer);
5243 return new L.FeatureGroup(layers);
5246 throw new Error('Invalid GeoJSON object.');
5250 coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng
5251 var lat = parseFloat(coords[reverse ? 0 : 1]),
5252 lng = parseFloat(coords[reverse ? 1 : 0]);
5254 return new L.LatLng(lat, lng, true);
5257 coordsToLatLngs: function (coords, levelsDeep, reverse) { // (Array, Number, Boolean) -> Array
5262 for (i = 0, len = coords.length; i < len; i++) {
5263 latlng = levelsDeep ?
5264 this.coordsToLatLngs(coords[i], levelsDeep - 1, reverse) :
5265 this.coordsToLatLng(coords[i], reverse);
5267 latlngs.push(latlng);
5274 L.geoJson = function (geojson, options) {
5275 return new L.GeoJSON(geojson, options);
5280 * L.DomEvent contains functions for working with DOM events.
5284 /* inpired by John Resig, Dean Edwards and YUI addEvent implementations */
5285 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
5287 var id = L.Util.stamp(fn),
5288 key = '_leaflet_' + type + id,
5289 handler, originalHandler, newType;
5291 if (obj[key]) { return this; }
5293 handler = function (e) {
5294 return fn.call(context || obj, e || L.DomEvent._getEvent());
5297 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
5298 return this.addDoubleTapListener(obj, handler, id);
5300 } else if ('addEventListener' in obj) {
5302 if (type === 'mousewheel') {
5303 obj.addEventListener('DOMMouseScroll', handler, false);
5304 obj.addEventListener(type, handler, false);
5306 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
5308 originalHandler = handler;
5309 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
5311 handler = function (e) {
5312 if (!L.DomEvent._checkMouse(obj, e)) { return; }
5313 return originalHandler(e);
5316 obj.addEventListener(newType, handler, false);
5319 obj.addEventListener(type, handler, false);
5322 } else if ('attachEvent' in obj) {
5323 obj.attachEvent("on" + type, handler);
5331 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
5333 var id = L.Util.stamp(fn),
5334 key = '_leaflet_' + type + id,
5337 if (!handler) { return; }
5339 if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
5340 this.removeDoubleTapListener(obj, id);
5342 } else if ('removeEventListener' in obj) {
5344 if (type === 'mousewheel') {
5345 obj.removeEventListener('DOMMouseScroll', handler, false);
5346 obj.removeEventListener(type, handler, false);
5348 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
5349 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
5351 obj.removeEventListener(type, handler, false);
5353 } else if ('detachEvent' in obj) {
5354 obj.detachEvent("on" + type, handler);
5362 stopPropagation: function (e) {
5364 if (e.stopPropagation) {
5365 e.stopPropagation();
5367 e.cancelBubble = true;
5372 disableClickPropagation: function (el) {
5374 var stop = L.DomEvent.stopPropagation;
5377 .addListener(el, L.Draggable.START, stop)
5378 .addListener(el, 'click', stop)
5379 .addListener(el, 'dblclick', stop);
5382 preventDefault: function (e) {
5384 if (e.preventDefault) {
5387 e.returnValue = false;
5392 stop: function (e) {
5393 return L.DomEvent.preventDefault(e).stopPropagation(e);
5396 getMousePosition: function (e, container) {
5398 var body = document.body,
5399 docEl = document.documentElement,
5400 x = e.pageX ? e.pageX : e.clientX + body.scrollLeft + docEl.scrollLeft,
5401 y = e.pageY ? e.pageY : e.clientY + body.scrollTop + docEl.scrollTop,
5402 pos = new L.Point(x, y);
5404 return (container ? pos._subtract(L.DomUtil.getViewportOffset(container)) : pos);
5407 getWheelDelta: function (e) {
5412 delta = e.wheelDelta / 120;
5415 delta = -e.detail / 3;
5420 // check if element really left/entered the event target (for mouseenter/mouseleave)
5421 _checkMouse: function (el, e) {
5423 var related = e.relatedTarget;
5425 if (!related) { return true; }
5428 while (related && (related !== el)) {
5429 related = related.parentNode;
5434 return (related !== el);
5437 /*jshint noarg:false */
5438 _getEvent: function () { // evil magic for IE
5440 var e = window.event;
5442 var caller = arguments.callee.caller;
5444 e = caller['arguments'][0];
5445 if (e && window.Event === e.constructor) {
5448 caller = caller.caller;
5453 /*jshint noarg:false */
5456 L.DomEvent.on = L.DomEvent.addListener;
5457 L.DomEvent.off = L.DomEvent.removeListener;
5460 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
5463 L.Draggable = L.Class.extend({
5464 includes: L.Mixin.Events,
5467 START: L.Browser.touch ? 'touchstart' : 'mousedown',
5468 END: L.Browser.touch ? 'touchend' : 'mouseup',
5469 MOVE: L.Browser.touch ? 'touchmove' : 'mousemove',
5473 initialize: function (element, dragStartTarget) {
5474 this._element = element;
5475 this._dragStartTarget = dragStartTarget || element;
5478 enable: function () {
5479 if (this._enabled) {
5482 L.DomEvent.on(this._dragStartTarget, L.Draggable.START, this._onDown, this);
5483 this._enabled = true;
5486 disable: function () {
5487 if (!this._enabled) {
5490 L.DomEvent.off(this._dragStartTarget, L.Draggable.START, this._onDown);
5491 this._enabled = false;
5492 this._moved = false;
5495 _onDown: function (e) {
5496 if ((!L.Browser.touch && e.shiftKey) ||
5497 ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
5499 L.DomEvent.preventDefault(e);
5501 if (L.Draggable._disabled) { return; }
5503 this._simulateClick = true;
5505 if (e.touches && e.touches.length > 1) {
5506 this._simulateClick = false;
5510 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
5513 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
5514 L.DomUtil.addClass(el, 'leaflet-active');
5517 this._moved = false;
5522 this._startPoint = new L.Point(first.clientX, first.clientY);
5523 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
5525 L.DomEvent.on(document, L.Draggable.MOVE, this._onMove, this);
5526 L.DomEvent.on(document, L.Draggable.END, this._onUp, this);
5529 _onMove: function (e) {
5530 if (e.touches && e.touches.length > 1) { return; }
5532 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
5533 newPoint = new L.Point(first.clientX, first.clientY),
5534 diffVec = newPoint.subtract(this._startPoint);
5536 if (!diffVec.x && !diffVec.y) { return; }
5538 L.DomEvent.preventDefault(e);
5541 this.fire('dragstart');
5544 this._startPos = L.DomUtil.getPosition(this._element).subtract(diffVec);
5546 if (!L.Browser.touch) {
5547 L.DomUtil.disableTextSelection();
5548 this._setMovingCursor();
5552 this._newPos = this._startPos.add(diffVec);
5553 this._moving = true;
5555 L.Util.cancelAnimFrame(this._animRequest);
5556 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
5559 _updatePosition: function () {
5560 this.fire('predrag');
5561 L.DomUtil.setPosition(this._element, this._newPos);
5565 _onUp: function (e) {
5566 if (this._simulateClick && e.changedTouches) {
5567 var first = e.changedTouches[0],
5569 dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;
5571 if (el.tagName.toLowerCase() === 'a') {
5572 L.DomUtil.removeClass(el, 'leaflet-active');
5575 if (dist < L.Draggable.TAP_TOLERANCE) {
5576 this._simulateEvent('click', first);
5580 if (!L.Browser.touch) {
5581 L.DomUtil.enableTextSelection();
5582 this._restoreCursor();
5585 L.DomEvent.off(document, L.Draggable.MOVE, this._onMove);
5586 L.DomEvent.off(document, L.Draggable.END, this._onUp);
5589 // ensure drag is not fired after dragend
5590 L.Util.cancelAnimFrame(this._animRequest);
5592 this.fire('dragend');
5594 this._moving = false;
5597 _setMovingCursor: function () {
5598 L.DomUtil.addClass(document.body, 'leaflet-dragging');
5601 _restoreCursor: function () {
5602 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
5605 _simulateEvent: function (type, e) {
5606 var simulatedEvent = document.createEvent('MouseEvents');
5608 simulatedEvent.initMouseEvent(
5609 type, true, true, window, 1,
5610 e.screenX, e.screenY,
5611 e.clientX, e.clientY,
5612 false, false, false, false, 0, null);
5614 e.target.dispatchEvent(simulatedEvent);
5620 * L.Handler classes are used internally to inject interaction features to classes like Map and Marker.
5623 L.Handler = L.Class.extend({
5624 initialize: function (map) {
5628 enable: function () {
5629 if (this._enabled) { return; }
5631 this._enabled = true;
5635 disable: function () {
5636 if (!this._enabled) { return; }
5638 this._enabled = false;
5642 enabled: function () {
5643 return !!this._enabled;
5649 * L.Handler.MapDrag is used internally by L.Map to make the map draggable.
5652 L.Map.mergeOptions({
5655 inertia: !L.Browser.android23,
5656 inertiaDeceleration: 3400, // px/s^2
5657 inertiaMaxSpeed: 6000, // px/s
5658 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
5660 // TODO refactor, move to CRS
5664 L.Map.Drag = L.Handler.extend({
5665 addHooks: function () {
5666 if (!this._draggable) {
5667 this._draggable = new L.Draggable(this._map._mapPane, this._map._container);
5669 this._draggable.on({
5670 'dragstart': this._onDragStart,
5671 'drag': this._onDrag,
5672 'dragend': this._onDragEnd
5675 var options = this._map.options;
5677 if (options.worldCopyJump) {
5678 this._draggable.on('predrag', this._onPreDrag, this);
5679 this._map.on('viewreset', this._onViewReset, this);
5682 this._draggable.enable();
5685 removeHooks: function () {
5686 this._draggable.disable();
5689 moved: function () {
5690 return this._draggable && this._draggable._moved;
5693 _onDragStart: function () {
5694 var map = this._map;
5697 map._panAnim.stop();
5704 if (map.options.inertia) {
5705 this._positions = [];
5710 _onDrag: function () {
5711 if (this._map.options.inertia) {
5712 var time = this._lastTime = +new Date(),
5713 pos = this._lastPos = this._draggable._newPos;
5715 this._positions.push(pos);
5716 this._times.push(time);
5718 if (time - this._times[0] > 200) {
5719 this._positions.shift();
5720 this._times.shift();
5729 _onViewReset: function () {
5730 var pxCenter = this._map.getSize()._divideBy(2),
5731 pxWorldCenter = this._map.latLngToLayerPoint(new L.LatLng(0, 0));
5733 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
5734 this._worldWidth = this._map.project(new L.LatLng(0, 180)).x;
5737 _onPreDrag: function () {
5738 // TODO refactor to be able to adjust map pane position after zoom
5739 var map = this._map,
5740 worldWidth = this._worldWidth,
5741 halfWidth = Math.round(worldWidth / 2),
5742 dx = this._initialWorldOffset,
5743 x = this._draggable._newPos.x,
5744 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
5745 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
5746 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
5748 this._draggable._newPos.x = newX;
5751 _onDragEnd: function () {
5752 var map = this._map,
5753 options = map.options,
5754 delay = +new Date() - this._lastTime,
5756 noInertia = !options.inertia ||
5757 delay > options.inertiaThreshold ||
5758 this._positions[0] === undefined;
5761 map.fire('moveend');
5765 var direction = this._lastPos.subtract(this._positions[0]),
5766 duration = (this._lastTime + delay - this._times[0]) / 1000,
5768 speedVector = direction.multiplyBy(0.58 / duration),
5769 speed = speedVector.distanceTo(new L.Point(0, 0)),
5771 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
5772 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
5774 decelerationDuration = limitedSpeed / options.inertiaDeceleration,
5775 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
5777 L.Util.requestAnimFrame(L.Util.bind(function () {
5778 this._map.panBy(offset, decelerationDuration);
5782 map.fire('dragend');
5784 if (options.maxBounds) {
5785 // TODO predrag validation instead of animation
5786 L.Util.requestAnimFrame(this._panInsideMaxBounds, map, true, map._container);
5790 _panInsideMaxBounds: function () {
5791 this.panInsideBounds(this.options.maxBounds);
5795 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
5799 * L.Handler.DoubleClickZoom is used internally by L.Map to add double-click zooming.
5802 L.Map.mergeOptions({
5803 doubleClickZoom: true
5806 L.Map.DoubleClickZoom = L.Handler.extend({
5807 addHooks: function () {
5808 this._map.on('dblclick', this._onDoubleClick);
5811 removeHooks: function () {
5812 this._map.off('dblclick', this._onDoubleClick);
5815 _onDoubleClick: function (e) {
5816 this.setView(e.latlng, this._zoom + 1);
5820 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
5823 * L.Handler.ScrollWheelZoom is used internally by L.Map to enable mouse scroll wheel zooming on the map.
5826 L.Map.mergeOptions({
5827 scrollWheelZoom: !L.Browser.touch
5830 L.Map.ScrollWheelZoom = L.Handler.extend({
5831 addHooks: function () {
5832 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
5836 removeHooks: function () {
5837 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
5840 _onWheelScroll: function (e) {
5841 var delta = L.DomEvent.getWheelDelta(e);
5843 this._delta += delta;
5844 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
5846 if (!this._startTime) {
5847 this._startTime = +new Date();
5850 var left = Math.max(40 - (+new Date() - this._startTime), 0);
5852 clearTimeout(this._timer);
5853 this._timer = setTimeout(L.Util.bind(this._performZoom, this), left);
5855 L.DomEvent.preventDefault(e);
5856 L.DomEvent.stopPropagation(e);
5859 _performZoom: function () {
5860 var map = this._map,
5861 delta = Math.round(this._delta),
5862 zoom = map.getZoom();
5864 delta = Math.max(Math.min(delta, 4), -4);
5865 delta = map._limitZoom(zoom + delta) - zoom;
5869 this._startTime = null;
5871 if (!delta) { return; }
5873 var newZoom = zoom + delta,
5874 newCenter = this._getCenterForScrollWheelZoom(newZoom);
5876 map.setView(newCenter, newZoom);
5879 _getCenterForScrollWheelZoom: function (newZoom) {
5880 var map = this._map,
5881 scale = map.getZoomScale(newZoom),
5882 viewHalf = map.getSize()._divideBy(2),
5883 centerOffset = this._lastMousePos._subtract(viewHalf)._multiplyBy(1 - 1 / scale),
5884 newCenterPoint = map._getTopLeftPoint()._add(viewHalf)._add(centerOffset);
5886 return map.unproject(newCenterPoint);
5890 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
5893 L.Util.extend(L.DomEvent, {
5894 // inspired by Zepto touch code by Thomas Fuchs
5895 addDoubleTapListener: function (obj, handler, id) {
5901 touchstart = 'touchstart',
5902 touchend = 'touchend';
5904 function onTouchStart(e) {
5905 if (e.touches.length !== 1) {
5909 var now = Date.now(),
5910 delta = now - (last || now);
5912 touch = e.touches[0];
5913 doubleTap = (delta > 0 && delta <= delay);
5916 function onTouchEnd(e) {
5918 touch.type = 'dblclick';
5923 obj[pre + touchstart + id] = onTouchStart;
5924 obj[pre + touchend + id] = onTouchEnd;
5926 obj.addEventListener(touchstart, onTouchStart, false);
5927 obj.addEventListener(touchend, onTouchEnd, false);
5931 removeDoubleTapListener: function (obj, id) {
5932 var pre = '_leaflet_';
5933 obj.removeEventListener(obj, obj[pre + 'touchstart' + id], false);
5934 obj.removeEventListener(obj, obj[pre + 'touchend' + id], false);
5941 * L.Handler.TouchZoom is used internally by L.Map to add touch-zooming on Webkit-powered mobile browsers.
5944 L.Map.mergeOptions({
5945 touchZoom: L.Browser.touch && !L.Browser.android23
5948 L.Map.TouchZoom = L.Handler.extend({
5949 addHooks: function () {
5950 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
5953 removeHooks: function () {
5954 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
5957 _onTouchStart: function (e) {
5958 var map = this._map;
5960 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
5962 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
5963 p2 = map.mouseEventToLayerPoint(e.touches[1]),
5964 viewCenter = map._getCenterLayerPoint();
5966 this._startCenter = p1.add(p2)._divideBy(2);
5967 this._startDist = p1.distanceTo(p2);
5969 this._moved = false;
5970 this._zooming = true;
5972 this._centerOffset = viewCenter.subtract(this._startCenter);
5975 map._panAnim.stop();
5979 .on(document, 'touchmove', this._onTouchMove, this)
5980 .on(document, 'touchend', this._onTouchEnd, this);
5982 L.DomEvent.preventDefault(e);
5985 _onTouchMove: function (e) {
5986 if (!e.touches || e.touches.length !== 2) { return; }
5988 var map = this._map;
5990 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
5991 p2 = map.mouseEventToLayerPoint(e.touches[1]);
5993 this._scale = p1.distanceTo(p2) / this._startDist;
5994 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
5996 if (this._scale === 1) { return; }
5999 L.DomUtil.addClass(map._mapPane, 'leaflet-zoom-anim leaflet-touching');
6009 L.Util.cancelAnimFrame(this._animRequest);
6010 this._animRequest = L.Util.requestAnimFrame(this._updateOnMove, this, true, this._map._container);
6012 L.DomEvent.preventDefault(e);
6015 _updateOnMove: function () {
6016 var map = this._map,
6017 origin = this._getScaleOrigin(),
6018 center = map.layerPointToLatLng(origin);
6020 map.fire('zoomanim', {
6022 zoom: map.getScaleZoom(this._scale)
6025 // Used 2 translates instead of transform-origin because of a very strange bug -
6026 // it didn't count the origin on the first touch-zoom but worked correctly afterwards
6028 map._tileBg.style[L.DomUtil.TRANSFORM] =
6029 L.DomUtil.getTranslateString(this._delta) + ' ' +
6030 L.DomUtil.getScaleString(this._scale, this._startCenter);
6033 _onTouchEnd: function (e) {
6034 if (!this._moved || !this._zooming) { return; }
6036 var map = this._map;
6038 this._zooming = false;
6039 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
6042 .off(document, 'touchmove', this._onTouchMove)
6043 .off(document, 'touchend', this._onTouchEnd);
6045 var origin = this._getScaleOrigin(),
6046 center = map.layerPointToLatLng(origin),
6048 oldZoom = map.getZoom(),
6049 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
6050 roundZoomDelta = (floatZoomDelta > 0 ? Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
6051 zoom = map._limitZoom(oldZoom + roundZoomDelta);
6053 map.fire('zoomanim', {
6058 map._runAnimation(center, zoom, map.getZoomScale(zoom) / this._scale, origin, true);
6061 _getScaleOrigin: function () {
6062 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
6063 return this._startCenter.add(centerOffset);
6067 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
6071 * L.Handler.ShiftDragZoom is used internally by L.Map to add shift-drag zoom (zoom to a selected bounding box).
6074 L.Map.mergeOptions({
6078 L.Map.BoxZoom = L.Handler.extend({
6079 initialize: function (map) {
6081 this._container = map._container;
6082 this._pane = map._panes.overlayPane;
6085 addHooks: function () {
6086 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
6089 removeHooks: function () {
6090 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
6093 _onMouseDown: function (e) {
6094 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
6096 L.DomUtil.disableTextSelection();
6098 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
6100 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
6101 L.DomUtil.setPosition(this._box, this._startLayerPoint);
6103 //TODO refactor: move cursor to styles
6104 this._container.style.cursor = 'crosshair';
6107 .on(document, 'mousemove', this._onMouseMove, this)
6108 .on(document, 'mouseup', this._onMouseUp, this)
6111 this._map.fire("boxzoomstart");
6114 _onMouseMove: function (e) {
6115 var startPoint = this._startLayerPoint,
6118 layerPoint = this._map.mouseEventToLayerPoint(e),
6119 offset = layerPoint.subtract(startPoint),
6121 newPos = new L.Point(
6122 Math.min(layerPoint.x, startPoint.x),
6123 Math.min(layerPoint.y, startPoint.y));
6125 L.DomUtil.setPosition(box, newPos);
6127 // TODO refactor: remove hardcoded 4 pixels
6128 box.style.width = (Math.abs(offset.x) - 4) + 'px';
6129 box.style.height = (Math.abs(offset.y) - 4) + 'px';
6132 _onMouseUp: function (e) {
6133 this._pane.removeChild(this._box);
6134 this._container.style.cursor = '';
6136 L.DomUtil.enableTextSelection();
6139 .off(document, 'mousemove', this._onMouseMove)
6140 .off(document, 'mouseup', this._onMouseUp);
6142 var map = this._map,
6143 layerPoint = map.mouseEventToLayerPoint(e);
6145 var bounds = new L.LatLngBounds(
6146 map.layerPointToLatLng(this._startLayerPoint),
6147 map.layerPointToLatLng(layerPoint));
6149 map.fitBounds(bounds);
6151 map.fire("boxzoomend", {
6152 boxZoomBounds: bounds
6157 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
6160 L.Map.mergeOptions({
6162 keyboardPanOffset: 80,
6163 keyboardZoomOffset: 1
6166 L.Map.Keyboard = L.Handler.extend({
6168 // list of e.keyCode values for particular actions
6174 zoomIn: [187, 107, 61],
6178 initialize: function (map) {
6181 this._setPanOffset(map.options.keyboardPanOffset);
6182 this._setZoomOffset(map.options.keyboardZoomOffset);
6185 addHooks: function () {
6186 var container = this._map._container;
6188 // make the container focusable by tabbing
6189 if (container.tabIndex === -1) {
6190 container.tabIndex = "0";
6194 .addListener(container, 'focus', this._onFocus, this)
6195 .addListener(container, 'blur', this._onBlur, this)
6196 .addListener(container, 'mousedown', this._onMouseDown, this);
6199 .on('focus', this._addHooks, this)
6200 .on('blur', this._removeHooks, this);
6203 removeHooks: function () {
6204 this._removeHooks();
6206 var container = this._map._container;
6208 .removeListener(container, 'focus', this._onFocus, this)
6209 .removeListener(container, 'blur', this._onBlur, this)
6210 .removeListener(container, 'mousedown', this._onMouseDown, this);
6213 .off('focus', this._addHooks, this)
6214 .off('blur', this._removeHooks, this);
6217 _onMouseDown: function () {
6218 if (!this._focused) {
6219 this._map._container.focus();
6223 _onFocus: function () {
6224 this._focused = true;
6225 this._map.fire('focus');
6228 _onBlur: function () {
6229 this._focused = false;
6230 this._map.fire('blur');
6233 _setPanOffset: function (pan) {
6234 var keys = this._panKeys = {},
6235 codes = this.keyCodes,
6238 for (i = 0, len = codes.left.length; i < len; i++) {
6239 keys[codes.left[i]] = [-1 * pan, 0];
6241 for (i = 0, len = codes.right.length; i < len; i++) {
6242 keys[codes.right[i]] = [pan, 0];
6244 for (i = 0, len = codes.down.length; i < len; i++) {
6245 keys[codes.down[i]] = [0, pan];
6247 for (i = 0, len = codes.up.length; i < len; i++) {
6248 keys[codes.up[i]] = [0, -1 * pan];
6252 _setZoomOffset: function (zoom) {
6253 var keys = this._zoomKeys = {},
6254 codes = this.keyCodes,
6257 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
6258 keys[codes.zoomIn[i]] = zoom;
6260 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
6261 keys[codes.zoomOut[i]] = -zoom;
6265 _addHooks: function () {
6266 L.DomEvent.addListener(document, 'keydown', this._onKeyDown, this);
6269 _removeHooks: function () {
6270 L.DomEvent.removeListener(document, 'keydown', this._onKeyDown, this);
6273 _onKeyDown: function (e) {
6274 var key = e.keyCode;
6276 if (this._panKeys.hasOwnProperty(key)) {
6277 this._map.panBy(this._panKeys[key]);
6279 } else if (this._zoomKeys.hasOwnProperty(key)) {
6280 this._map.setZoom(this._map.getZoom() + this._zoomKeys[key]);
6290 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
6294 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
6297 L.Handler.MarkerDrag = L.Handler.extend({
6298 initialize: function (marker) {
6299 this._marker = marker;
6302 addHooks: function () {
6303 var icon = this._marker._icon;
6304 if (!this._draggable) {
6305 this._draggable = new L.Draggable(icon, icon)
6306 .on('dragstart', this._onDragStart, this)
6307 .on('drag', this._onDrag, this)
6308 .on('dragend', this._onDragEnd, this);
6310 this._draggable.enable();
6313 removeHooks: function () {
6314 this._draggable.disable();
6317 moved: function () {
6318 return this._draggable && this._draggable._moved;
6321 _onDragStart: function (e) {
6328 _onDrag: function (e) {
6329 var marker = this._marker,
6330 shadow = marker._shadow,
6331 iconPos = L.DomUtil.getPosition(marker._icon),
6332 latlng = marker._map.layerPointToLatLng(iconPos);
6334 // update shadow position
6336 L.DomUtil.setPosition(shadow, iconPos);
6339 marker._latlng = latlng;
6342 .fire('move', { latlng: latlng })
6346 _onDragEnd: function () {
6354 L.Handler.PolyEdit = L.Handler.extend({
6356 icon: new L.DivIcon({
6357 iconSize: new L.Point(8, 8),
6358 className: 'leaflet-div-icon leaflet-editing-icon'
6362 initialize: function (poly, options) {
6364 L.Util.setOptions(this, options);
6367 addHooks: function () {
6368 if (this._poly._map) {
6369 if (!this._markerGroup) {
6370 this._initMarkers();
6372 this._poly._map.addLayer(this._markerGroup);
6376 removeHooks: function () {
6377 if (this._poly._map) {
6378 this._poly._map.removeLayer(this._markerGroup);
6379 delete this._markerGroup;
6380 delete this._markers;
6384 updateMarkers: function () {
6385 this._markerGroup.clearLayers();
6386 this._initMarkers();
6389 _initMarkers: function () {
6390 if (!this._markerGroup) {
6391 this._markerGroup = new L.LayerGroup();
6395 var latlngs = this._poly._latlngs,
6398 // TODO refactor holes implementation in Polygon to support it here
6400 for (i = 0, len = latlngs.length; i < len; i++) {
6402 marker = this._createMarker(latlngs[i], i);
6403 marker.on('click', this._onMarkerClick, this);
6404 this._markers.push(marker);
6407 var markerLeft, markerRight;
6409 for (i = 0, j = len - 1; i < len; j = i++) {
6410 if (i === 0 && !(L.Polygon && (this._poly instanceof L.Polygon))) {
6414 markerLeft = this._markers[j];
6415 markerRight = this._markers[i];
6417 this._createMiddleMarker(markerLeft, markerRight);
6418 this._updatePrevNext(markerLeft, markerRight);
6422 _createMarker: function (latlng, index) {
6423 var marker = new L.Marker(latlng, {
6425 icon: this.options.icon
6428 marker._origLatLng = latlng;
6429 marker._index = index;
6431 marker.on('drag', this._onMarkerDrag, this);
6432 marker.on('dragend', this._fireEdit, this);
6434 this._markerGroup.addLayer(marker);
6439 _fireEdit: function () {
6440 this._poly.fire('edit');
6443 _onMarkerDrag: function (e) {
6444 var marker = e.target;
6446 L.Util.extend(marker._origLatLng, marker._latlng);
6448 if (marker._middleLeft) {
6449 marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
6451 if (marker._middleRight) {
6452 marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
6455 this._poly.redraw();
6458 _onMarkerClick: function (e) {
6459 // Default action on marker click is to remove that marker, but if we remove the marker when latlng count < 3, we don't have a valid polyline anymore
6460 if (this._poly._latlngs.length < 3) {
6464 var marker = e.target,
6467 // Check existence of previous and next markers since they wouldn't exist for edge points on the polyline
6468 if (marker._prev && marker._next) {
6469 this._createMiddleMarker(marker._prev, marker._next);
6470 } else if (!marker._prev) {
6471 marker._next._middleLeft = null;
6472 } else if (!marker._next) {
6473 marker._prev._middleRight = null;
6475 this._updatePrevNext(marker._prev, marker._next);
6477 // The marker itself is guaranteed to exist and present in the layer, since we managed to click on it
6478 this._markerGroup.removeLayer(marker);
6479 // Check for the existence of middle left or middle right
6480 if (marker._middleLeft) {
6481 this._markerGroup.removeLayer(marker._middleLeft);
6483 if (marker._middleRight) {
6484 this._markerGroup.removeLayer(marker._middleRight);
6486 this._markers.splice(i, 1);
6487 this._poly.spliceLatLngs(i, 1);
6488 this._updateIndexes(i, -1);
6489 this._poly.fire('edit');
6492 _updateIndexes: function (index, delta) {
6493 this._markerGroup.eachLayer(function (marker) {
6494 if (marker._index > index) {
6495 marker._index += delta;
6500 _createMiddleMarker: function (marker1, marker2) {
6501 var latlng = this._getMiddleLatLng(marker1, marker2),
6502 marker = this._createMarker(latlng),
6507 marker.setOpacity(0.6);
6509 marker1._middleRight = marker2._middleLeft = marker;
6511 onDragStart = function () {
6512 var i = marker2._index;
6517 .off('click', onClick)
6518 .on('click', this._onMarkerClick, this);
6520 latlng.lat = marker.getLatLng().lat;
6521 latlng.lng = marker.getLatLng().lng;
6522 this._poly.spliceLatLngs(i, 0, latlng);
6523 this._markers.splice(i, 0, marker);
6525 marker.setOpacity(1);
6527 this._updateIndexes(i, 1);
6529 this._updatePrevNext(marker1, marker);
6530 this._updatePrevNext(marker, marker2);
6533 onDragEnd = function () {
6534 marker.off('dragstart', onDragStart, this);
6535 marker.off('dragend', onDragEnd, this);
6537 this._createMiddleMarker(marker1, marker);
6538 this._createMiddleMarker(marker, marker2);
6541 onClick = function () {
6542 onDragStart.call(this);
6543 onDragEnd.call(this);
6544 this._poly.fire('edit');
6548 .on('click', onClick, this)
6549 .on('dragstart', onDragStart, this)
6550 .on('dragend', onDragEnd, this);
6552 this._markerGroup.addLayer(marker);
6555 _updatePrevNext: function (marker1, marker2) {
6557 marker1._next = marker2;
6560 marker2._prev = marker1;
6564 _getMiddleLatLng: function (marker1, marker2) {
6565 var map = this._poly._map,
6566 p1 = map.latLngToLayerPoint(marker1.getLatLng()),
6567 p2 = map.latLngToLayerPoint(marker2.getLatLng());
6569 return map.layerPointToLatLng(p1._add(p2)._divideBy(2));
6575 L.Control = L.Class.extend({
6577 position: 'topright'
6580 initialize: function (options) {
6581 L.Util.setOptions(this, options);
6584 getPosition: function () {
6585 return this.options.position;
6588 setPosition: function (position) {
6589 var map = this._map;
6592 map.removeControl(this);
6595 this.options.position = position;
6598 map.addControl(this);
6604 addTo: function (map) {
6607 var container = this._container = this.onAdd(map),
6608 pos = this.getPosition(),
6609 corner = map._controlCorners[pos];
6611 L.DomUtil.addClass(container, 'leaflet-control');
6613 if (pos.indexOf('bottom') !== -1) {
6614 corner.insertBefore(container, corner.firstChild);
6616 corner.appendChild(container);
6622 removeFrom: function (map) {
6623 var pos = this.getPosition(),
6624 corner = map._controlCorners[pos];
6626 corner.removeChild(this._container);
6629 if (this.onRemove) {
6637 L.control = function (options) {
6638 return new L.Control(options);
6643 addControl: function (control) {
6644 control.addTo(this);
6648 removeControl: function (control) {
6649 control.removeFrom(this);
6653 _initControlPos: function () {
6654 var corners = this._controlCorners = {},
6656 container = this._controlContainer =
6657 L.DomUtil.create('div', l + 'control-container', this._container);
6659 function createCorner(vSide, hSide) {
6660 var className = l + vSide + ' ' + l + hSide;
6662 corners[vSide + hSide] =
6663 L.DomUtil.create('div', className, container);
6666 createCorner('top', 'left');
6667 createCorner('top', 'right');
6668 createCorner('bottom', 'left');
6669 createCorner('bottom', 'right');
6674 L.Control.Zoom = L.Control.extend({
6679 onAdd: function (map) {
6680 var className = 'leaflet-control-zoom',
6681 container = L.DomUtil.create('div', className);
6685 this._createButton('Zoom in', className + '-in', container, this._zoomIn, this);
6686 this._createButton('Zoom out', className + '-out', container, this._zoomOut, this);
6691 _zoomIn: function (e) {
6692 this._map.zoomIn(e.shiftKey ? 3 : 1);
6695 _zoomOut: function (e) {
6696 this._map.zoomOut(e.shiftKey ? 3 : 1);
6699 _createButton: function (title, className, container, fn, context) {
6700 var link = L.DomUtil.create('a', className, container);
6705 .on(link, 'click', L.DomEvent.stopPropagation)
6706 .on(link, 'mousedown', L.DomEvent.stopPropagation)
6707 .on(link, 'dblclick', L.DomEvent.stopPropagation)
6708 .on(link, 'click', L.DomEvent.preventDefault)
6709 .on(link, 'click', fn, context);
6715 L.Map.mergeOptions({
6719 L.Map.addInitHook(function () {
6720 if (this.options.zoomControl) {
6721 this.zoomControl = new L.Control.Zoom();
6722 this.addControl(this.zoomControl);
6726 L.control.zoom = function (options) {
6727 return new L.Control.Zoom(options);
6732 L.Control.Attribution = L.Control.extend({
6734 position: 'bottomright',
6735 prefix: 'Powered by <a href="http://leaflet.cloudmade.com">Leaflet</a>'
6738 initialize: function (options) {
6739 L.Util.setOptions(this, options);
6741 this._attributions = {};
6744 onAdd: function (map) {
6745 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
6746 L.DomEvent.disableClickPropagation(this._container);
6749 .on('layeradd', this._onLayerAdd, this)
6750 .on('layerremove', this._onLayerRemove, this);
6754 return this._container;
6757 onRemove: function (map) {
6759 .off('layeradd', this._onLayerAdd)
6760 .off('layerremove', this._onLayerRemove);
6764 setPrefix: function (prefix) {
6765 this.options.prefix = prefix;
6770 addAttribution: function (text) {
6771 if (!text) { return; }
6773 if (!this._attributions[text]) {
6774 this._attributions[text] = 0;
6776 this._attributions[text]++;
6783 removeAttribution: function (text) {
6784 if (!text) { return; }
6786 this._attributions[text]--;
6792 _update: function () {
6793 if (!this._map) { return; }
6797 for (var i in this._attributions) {
6798 if (this._attributions.hasOwnProperty(i) && this._attributions[i]) {
6803 var prefixAndAttribs = [];
6805 if (this.options.prefix) {
6806 prefixAndAttribs.push(this.options.prefix);
6808 if (attribs.length) {
6809 prefixAndAttribs.push(attribs.join(', '));
6812 this._container.innerHTML = prefixAndAttribs.join(' — ');
6815 _onLayerAdd: function (e) {
6816 if (e.layer.getAttribution) {
6817 this.addAttribution(e.layer.getAttribution());
6821 _onLayerRemove: function (e) {
6822 if (e.layer.getAttribution) {
6823 this.removeAttribution(e.layer.getAttribution());
6828 L.Map.mergeOptions({
6829 attributionControl: true
6832 L.Map.addInitHook(function () {
6833 if (this.options.attributionControl) {
6834 this.attributionControl = (new L.Control.Attribution()).addTo(this);
6838 L.control.attribution = function (options) {
6839 return new L.Control.Attribution(options);
6843 L.Control.Scale = L.Control.extend({
6845 position: 'bottomleft',
6849 updateWhenIdle: false
6852 onAdd: function (map) {
6855 var className = 'leaflet-control-scale',
6856 container = L.DomUtil.create('div', className),
6857 options = this.options;
6859 this._addScales(options, className, container);
6861 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
6862 map.whenReady(this._update, this);
6867 onRemove: function (map) {
6868 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
6871 _addScales: function (options, className, container) {
6872 if (options.metric) {
6873 this._mScale = L.DomUtil.create('div', className + '-line', container);
6875 if (options.imperial) {
6876 this._iScale = L.DomUtil.create('div', className + '-line', container);
6880 _update: function () {
6881 var bounds = this._map.getBounds(),
6882 centerLat = bounds.getCenter().lat,
6883 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
6884 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
6886 size = this._map.getSize(),
6887 options = this.options,
6891 maxMeters = dist * (options.maxWidth / size.x);
6894 this._updateScales(options, maxMeters);
6897 _updateScales: function (options, maxMeters) {
6898 if (options.metric && maxMeters) {
6899 this._updateMetric(maxMeters);
6902 if (options.imperial && maxMeters) {
6903 this._updateImperial(maxMeters);
6907 _updateMetric: function (maxMeters) {
6908 var meters = this._getRoundNum(maxMeters);
6910 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
6911 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
6914 _updateImperial: function (maxMeters) {
6915 var maxFeet = maxMeters * 3.2808399,
6916 scale = this._iScale,
6917 maxMiles, miles, feet;
6919 if (maxFeet > 5280) {
6920 maxMiles = maxFeet / 5280;
6921 miles = this._getRoundNum(maxMiles);
6923 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
6924 scale.innerHTML = miles + ' mi';
6927 feet = this._getRoundNum(maxFeet);
6929 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
6930 scale.innerHTML = feet + ' ft';
6934 _getScaleWidth: function (ratio) {
6935 return Math.round(this.options.maxWidth * ratio) - 10;
6938 _getRoundNum: function (num) {
6939 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
6942 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
6948 L.control.scale = function (options) {
6949 return new L.Control.Scale(options);
6953 L.Control.Layers = L.Control.extend({
6956 position: 'topright',
6960 initialize: function (baseLayers, overlays, options) {
6961 L.Util.setOptions(this, options);
6964 this._lastZIndex = 0;
6966 for (var i in baseLayers) {
6967 if (baseLayers.hasOwnProperty(i)) {
6968 this._addLayer(baseLayers[i], i);
6972 for (i in overlays) {
6973 if (overlays.hasOwnProperty(i)) {
6974 this._addLayer(overlays[i], i, true);
6979 onAdd: function (map) {
6983 return this._container;
6986 addBaseLayer: function (layer, name) {
6987 this._addLayer(layer, name);
6992 addOverlay: function (layer, name) {
6993 this._addLayer(layer, name, true);
6998 removeLayer: function (layer) {
6999 var id = L.Util.stamp(layer);
7000 delete this._layers[id];
7005 _initLayout: function () {
7006 var className = 'leaflet-control-layers',
7007 container = this._container = L.DomUtil.create('div', className);
7009 if (!L.Browser.touch) {
7010 L.DomEvent.disableClickPropagation(container);
7012 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
7015 var form = this._form = L.DomUtil.create('form', className + '-list');
7017 if (this.options.collapsed) {
7019 .on(container, 'mouseover', this._expand, this)
7020 .on(container, 'mouseout', this._collapse, this);
7022 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
7024 link.title = 'Layers';
7026 if (L.Browser.touch) {
7028 .on(link, 'click', L.DomEvent.stopPropagation)
7029 .on(link, 'click', L.DomEvent.preventDefault)
7030 .on(link, 'click', this._expand, this);
7033 L.DomEvent.on(link, 'focus', this._expand, this);
7036 this._map.on('movestart', this._collapse, this);
7037 // TODO keyboard accessibility
7042 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
7043 this._separator = L.DomUtil.create('div', className + '-separator', form);
7044 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
7046 container.appendChild(form);
7049 _addLayer: function (layer, name, overlay) {
7050 var id = L.Util.stamp(layer);
7052 this._layers[id] = {
7058 if (this.options.autoZIndex && layer.setZIndex) {
7060 layer.setZIndex(this._lastZIndex);
7064 _update: function () {
7065 if (!this._container) {
7069 this._baseLayersList.innerHTML = '';
7070 this._overlaysList.innerHTML = '';
7072 var baseLayersPresent = false,
7073 overlaysPresent = false;
7075 for (var i in this._layers) {
7076 if (this._layers.hasOwnProperty(i)) {
7077 var obj = this._layers[i];
7079 overlaysPresent = overlaysPresent || obj.overlay;
7080 baseLayersPresent = baseLayersPresent || !obj.overlay;
7084 this._separator.style.display = (overlaysPresent && baseLayersPresent ? '' : 'none');
7087 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
7088 _createRadioElement: function (name, checked) {
7090 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
7092 radioHtml += ' checked="checked"';
7096 var radioFragment = document.createElement('div');
7097 radioFragment.innerHTML = radioHtml;
7099 return radioFragment.firstChild;
7102 _addItem: function (obj) {
7103 var label = document.createElement('label'),
7105 checked = this._map.hasLayer(obj.layer);
7108 input = document.createElement('input');
7109 input.type = 'checkbox';
7110 input.className = 'leaflet-control-layers-selector';
7111 input.defaultChecked = checked;
7113 input = this._createRadioElement('leaflet-base-layers', checked);
7116 input.layerId = L.Util.stamp(obj.layer);
7118 L.DomEvent.on(input, 'click', this._onInputClick, this);
7120 var name = document.createElement('span');
7121 name.innerHTML = ' ' + obj.name;
7123 label.appendChild(input);
7124 label.appendChild(name);
7126 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
7127 container.appendChild(label);
7130 _onInputClick: function () {
7132 inputs = this._form.getElementsByTagName('input'),
7133 inputsLen = inputs.length,
7136 for (i = 0; i < inputsLen; i++) {
7138 obj = this._layers[input.layerId];
7140 if (input.checked && !this._map.hasLayer(obj.layer)) {
7141 this._map.addLayer(obj.layer);
7143 baseLayer = obj.layer;
7145 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
7146 this._map.removeLayer(obj.layer);
7151 this._map.fire('baselayerchange', {layer: baseLayer});
7155 _expand: function () {
7156 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
7159 _collapse: function () {
7160 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
7164 L.control.layers = function (baseLayers, overlays, options) {
7165 return new L.Control.Layers(baseLayers, overlays, options);
7170 * L.PosAnimation is used by Leaflet internally for pan animations.
7173 L.PosAnimation = L.Class.extend({
7174 includes: L.Mixin.Events,
7176 run: function (el, newPos, duration, easing) { // (HTMLElement, Point[, Number, String])
7180 this._inProgress = true;
7184 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) + 's ' + (easing || 'ease-out');
7186 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7187 L.DomUtil.setPosition(el, newPos);
7189 // toggle reflow, Chrome flickers for some reason if you don't do this
7190 L.Util.falseFn(el.offsetWidth);
7192 // there's no native way to track value updates of tranisitioned properties, so we imitate this
7193 this._stepTimer = setInterval(L.Util.bind(this.fire, this, 'step'), 50);
7197 if (!this._inProgress) { return; }
7199 // if we just removed the transition property, the element would jump to its final position,
7200 // so we need to make it stay at the current position
7202 L.DomUtil.setPosition(this._el, this._getPos());
7203 this._onTransitionEnd();
7206 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
7207 // we need to parse computed style (in case of transform it returns matrix string)
7209 _transformRe: /(-?[\d\.]+), (-?[\d\.]+)\)/,
7211 _getPos: function () {
7212 var left, top, matches,
7214 style = window.getComputedStyle(el);
7216 if (L.Browser.any3d) {
7217 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
7218 left = parseFloat(matches[1]);
7219 top = parseFloat(matches[2]);
7221 left = parseFloat(style.left);
7222 top = parseFloat(style.top);
7225 return new L.Point(left, top, true);
7228 _onTransitionEnd: function () {
7229 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7231 if (!this._inProgress) { return; }
7232 this._inProgress = false;
7234 this._el.style[L.DomUtil.TRANSITION] = '';
7236 clearInterval(this._stepTimer);
7238 this.fire('step').fire('end');
7247 setView: function (center, zoom, forceReset) {
7248 zoom = this._limitZoom(zoom);
7250 var zoomChanged = (this._zoom !== zoom);
7252 if (this._loaded && !forceReset && this._layers) {
7254 if (this._panAnim) {
7255 this._panAnim.stop();
7258 var done = (zoomChanged ?
7259 this._zoomToIfClose && this._zoomToIfClose(center, zoom) :
7260 this._panByIfClose(center));
7262 // exit if animated pan or zoom started
7264 clearTimeout(this._sizeTimer);
7269 // reset the map view
7270 this._resetView(center, zoom);
7275 panBy: function (offset, duration) {
7276 offset = L.point(offset);
7278 if (!(offset.x || offset.y)) {
7282 if (!this._panAnim) {
7283 this._panAnim = new L.PosAnimation();
7286 'step': this._onPanTransitionStep,
7287 'end': this._onPanTransitionEnd
7291 this.fire('movestart');
7293 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
7295 var newPos = L.DomUtil.getPosition(this._mapPane).subtract(offset);
7296 this._panAnim.run(this._mapPane, newPos, duration || 0.25);
7301 _onPanTransitionStep: function () {
7305 _onPanTransitionEnd: function () {
7306 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
7307 this.fire('moveend');
7310 _panByIfClose: function (center) {
7311 // difference between the new and current centers in pixels
7312 var offset = this._getCenterOffset(center)._floor();
7314 if (this._offsetIsWithinView(offset)) {
7321 _offsetIsWithinView: function (offset, multiplyFactor) {
7322 var m = multiplyFactor || 1,
7323 size = this.getSize();
7325 return (Math.abs(offset.x) <= size.x * m) &&
7326 (Math.abs(offset.y) <= size.y * m);
7332 * L.PosAnimation fallback implementation that powers Leaflet pan animations
7333 * in browsers that don't support CSS3 Transitions.
7336 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
7338 run: function (el, newPos, duration, easing) { // (HTMLElement, Point[, Number, String])
7342 this._inProgress = true;
7343 this._duration = duration || 0.25;
7344 this._ease = this._easings[easing || 'ease-out'];
7346 this._startPos = L.DomUtil.getPosition(el);
7347 this._offset = newPos.subtract(this._startPos);
7348 this._startTime = +new Date();
7356 if (!this._inProgress) { return; }
7362 _animate: function () {
7364 this._animId = L.Util.requestAnimFrame(this._animate, this);
7368 _step: function () {
7369 var elapsed = (+new Date()) - this._startTime,
7370 duration = this._duration * 1000;
7372 if (elapsed < duration) {
7373 this._runFrame(this._ease(elapsed / duration));
7380 _runFrame: function (progress) {
7381 var pos = this._startPos.add(this._offset.multiplyBy(progress));
7382 L.DomUtil.setPosition(this._el, pos);
7387 _complete: function () {
7388 L.Util.cancelAnimFrame(this._animId);
7390 this._inProgress = false;
7394 // easing functions, they map time progress to movement progress
7396 'ease-out': function (t) { return t * (2 - t); },
7397 'linear': function (t) { return t; }
7403 L.Map.mergeOptions({
7404 zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera
7407 if (L.DomUtil.TRANSITION) {
7408 L.Map.addInitHook(function () {
7409 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
7413 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
7415 _zoomToIfClose: function (center, zoom) {
7417 if (this._animatingZoom) { return true; }
7419 if (!this.options.zoomAnimation) { return false; }
7421 var scale = this.getZoomScale(zoom),
7422 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
7424 // if offset does not exceed half of the view
7425 if (!this._offsetIsWithinView(offset, 1)) { return false; }
7427 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
7433 this.fire('zoomanim', {
7438 var origin = this._getCenterLayerPoint().add(offset);
7440 this._prepareTileBg();
7441 this._runAnimation(center, zoom, scale, origin);
7446 _catchTransitionEnd: function (e) {
7447 if (this._animatingZoom) {
7448 this._onZoomTransitionEnd();
7452 _runAnimation: function (center, zoom, scale, origin, backwardsTransform) {
7453 this._animateToCenter = center;
7454 this._animateToZoom = zoom;
7455 this._animatingZoom = true;
7458 L.Draggable._disabled = true;
7461 var transform = L.DomUtil.TRANSFORM,
7462 tileBg = this._tileBg;
7464 clearTimeout(this._clearTileBgTimer);
7466 L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation
7468 var scaleStr = L.DomUtil.getScaleString(scale, origin),
7469 oldTransform = tileBg.style[transform];
7471 tileBg.style[transform] = backwardsTransform ?
7472 oldTransform + ' ' + scaleStr :
7473 scaleStr + ' ' + oldTransform;
7476 _prepareTileBg: function () {
7477 var tilePane = this._tilePane,
7478 tileBg = this._tileBg;
7480 // If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more
7482 this._getLoadedTilesPercentage(tileBg) > 0.5 &&
7483 this._getLoadedTilesPercentage(tilePane) < 0.5) {
7485 tilePane.style.visibility = 'hidden';
7486 tilePane.empty = true;
7487 this._stopLoadingImages(tilePane);
7492 tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane);
7493 tileBg.style.zIndex = 1;
7496 // prepare the background pane to become the main tile pane
7497 tileBg.style[L.DomUtil.TRANSFORM] = '';
7498 tileBg.style.visibility = 'hidden';
7500 // tells tile layers to reinitialize their containers
7501 tileBg.empty = true; //new FG
7502 tilePane.empty = false; //new BG
7504 //Switch out the current layer to be the new bg layer (And vice-versa)
7505 this._tilePane = this._panes.tilePane = tileBg;
7506 var newTileBg = this._tileBg = tilePane;
7508 L.DomUtil.addClass(newTileBg, 'leaflet-zoom-animated');
7510 this._stopLoadingImages(newTileBg);
7513 _getLoadedTilesPercentage: function (container) {
7514 var tiles = container.getElementsByTagName('img'),
7517 for (i = 0, len = tiles.length; i < len; i++) {
7518 if (tiles[i].complete) {
7525 // stops loading all tiles in the background layer
7526 _stopLoadingImages: function (container) {
7527 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
7530 for (i = 0, len = tiles.length; i < len; i++) {
7533 if (!tile.complete) {
7534 tile.onload = L.Util.falseFn;
7535 tile.onerror = L.Util.falseFn;
7536 tile.src = L.Util.emptyImageUrl;
7538 tile.parentNode.removeChild(tile);
7543 _onZoomTransitionEnd: function () {
7544 this._restoreTileFront();
7545 L.Util.falseFn(this._tileBg.offsetWidth); // force reflow
7546 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
7548 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
7549 this._animatingZoom = false;
7552 L.Draggable._disabled = false;
7556 _restoreTileFront: function () {
7557 this._tilePane.innerHTML = '';
7558 this._tilePane.style.visibility = '';
7559 this._tilePane.style.zIndex = 2;
7560 this._tileBg.style.zIndex = 1;
7563 _clearTileBg: function () {
7564 if (!this._animatingZoom && !this.touchZoom._zooming) {
7565 this._tileBg.innerHTML = '';
7572 * Provides L.Map with convenient shortcuts for W3C geolocation.
7576 _defaultLocateOptions: {
7582 enableHighAccuracy: false
7585 locate: function (/*Object*/ options) {
7587 options = this._locationOptions = L.Util.extend(this._defaultLocateOptions, options);
7589 if (!navigator.geolocation) {
7590 this._handleGeolocationError({
7592 message: "Geolocation not supported."
7597 var onResponse = L.Util.bind(this._handleGeolocationResponse, this),
7598 onError = L.Util.bind(this._handleGeolocationError, this);
7600 if (options.watch) {
7601 this._locationWatchId = navigator.geolocation.watchPosition(onResponse, onError, options);
7603 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
7608 stopLocate: function () {
7609 if (navigator.geolocation) {
7610 navigator.geolocation.clearWatch(this._locationWatchId);
7615 _handleGeolocationError: function (error) {
7617 message = error.message ||
7618 (c === 1 ? "permission denied" :
7619 (c === 2 ? "position unavailable" : "timeout"));
7621 if (this._locationOptions.setView && !this._loaded) {
7625 this.fire('locationerror', {
7627 message: "Geolocation error: " + message + "."
7631 _handleGeolocationResponse: function (pos) {
7632 var latAccuracy = 180 * pos.coords.accuracy / 4e7,
7633 lngAccuracy = latAccuracy * 2,
7635 lat = pos.coords.latitude,
7636 lng = pos.coords.longitude,
7637 latlng = new L.LatLng(lat, lng),
7639 sw = new L.LatLng(lat - latAccuracy, lng - lngAccuracy),
7640 ne = new L.LatLng(lat + latAccuracy, lng + lngAccuracy),
7641 bounds = new L.LatLngBounds(sw, ne),
7643 options = this._locationOptions;
7645 if (options.setView) {
7646 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
7647 this.setView(latlng, zoom);
7650 this.fire('locationfound', {
7653 accuracy: pos.coords.accuracy