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;
350 var ie = !!window.ActiveXObject,
351 // http://tanalin.com/en/articles/ie-version-js/
352 ie6 = ie && !window.XMLHttpRequest,
353 ie7 = ie && !document.querySelector,
355 // terrible browser detection to work around Safari / iOS / Android browser bugs
356 // see TileLayer._addTile and debug/hacks/jitter.html
358 ua = navigator.userAgent.toLowerCase(),
359 webkit = ua.indexOf("webkit") !== -1,
360 chrome = ua.indexOf("chrome") !== -1,
361 android = ua.indexOf("android") !== -1,
362 android23 = ua.search("android [23]") !== -1,
364 mobile = typeof orientation !== undefined + '',
365 msTouch = (window.navigator && window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints),
366 retina = (('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
367 ('matchMedia' in window && window.matchMedia("(min-resolution:144dpi)").matches)),
369 doc = document.documentElement,
370 ie3d = ie && ('transition' in doc.style),
371 webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
372 gecko3d = 'MozPerspective' in doc.style,
373 opera3d = 'OTransition' in doc.style,
374 any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d);
377 var touch = !window.L_NO_TOUCH && (function () {
379 var startName = 'ontouchstart';
381 // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.MsTouch) or WebKit, etc.
382 if (msTouch || (startName in doc)) {
387 var div = document.createElement('div'),
390 if (!div.setAttribute) {
393 div.setAttribute(startName, 'return;');
395 if (typeof div[startName] === 'function') {
399 div.removeAttribute(startName);
412 android23: android23,
423 mobileWebkit: mobile && webkit,
424 mobileWebkit3d: mobile && webkit3d,
425 mobileOpera: mobile && window.opera,
437 * L.Point represents a point with x and y coordinates.
440 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
441 this.x = (round ? Math.round(x) : x);
442 this.y = (round ? Math.round(y) : y);
445 L.Point.prototype = {
448 return new L.Point(this.x, this.y);
451 // non-destructive, returns a new point
452 add: function (point) {
453 return this.clone()._add(L.point(point));
456 // destructive, used directly for performance in situations where it's safe to modify existing point
457 _add: function (point) {
463 subtract: function (point) {
464 return this.clone()._subtract(L.point(point));
467 _subtract: function (point) {
473 divideBy: function (num) {
474 return this.clone()._divideBy(num);
477 _divideBy: function (num) {
483 multiplyBy: function (num) {
484 return this.clone()._multiplyBy(num);
487 _multiplyBy: function (num) {
494 return this.clone()._round();
497 _round: function () {
498 this.x = Math.round(this.x);
499 this.y = Math.round(this.y);
504 return this.clone()._floor();
507 _floor: function () {
508 this.x = Math.floor(this.x);
509 this.y = Math.floor(this.y);
513 distanceTo: function (point) {
514 point = L.point(point);
516 var x = point.x - this.x,
517 y = point.y - this.y;
519 return Math.sqrt(x * x + y * y);
522 toString: function () {
524 L.Util.formatNum(this.x) + ', ' +
525 L.Util.formatNum(this.y) + ')';
529 L.point = function (x, y, round) {
530 if (x instanceof L.Point) {
533 if (x instanceof Array) {
534 return new L.Point(x[0], x[1]);
539 return new L.Point(x, y, round);
544 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
547 L.Bounds = L.Class.extend({
549 initialize: function (a, b) { //(Point, Point) or Point[]
552 var points = b ? [a, b] : a;
554 for (var i = 0, len = points.length; i < len; i++) {
555 this.extend(points[i]);
559 // extend the bounds to contain the given point
560 extend: function (point) { // (Point)
561 point = L.point(point);
563 if (!this.min && !this.max) {
564 this.min = point.clone();
565 this.max = point.clone();
567 this.min.x = Math.min(point.x, this.min.x);
568 this.max.x = Math.max(point.x, this.max.x);
569 this.min.y = Math.min(point.y, this.min.y);
570 this.max.y = Math.max(point.y, this.max.y);
575 getCenter: function (round) { // (Boolean) -> Point
577 (this.min.x + this.max.x) / 2,
578 (this.min.y + this.max.y) / 2, round);
581 getBottomLeft: function () { // -> Point
582 return new L.Point(this.min.x, this.max.y);
585 getTopRight: function () { // -> Point
586 return new L.Point(this.max.x, this.min.y);
589 contains: function (obj) { // (Bounds) or (Point) -> Boolean
592 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
598 if (obj instanceof L.Bounds) {
605 return (min.x >= this.min.x) &&
606 (max.x <= this.max.x) &&
607 (min.y >= this.min.y) &&
608 (max.y <= this.max.y);
611 intersects: function (bounds) { // (Bounds) -> Boolean
612 bounds = L.bounds(bounds);
619 var xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
620 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
622 return xIntersects && yIntersects;
625 isValid: function () {
626 return !!(this.min && this.max);
630 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
631 if (!a || a instanceof L.Bounds) {
634 return new L.Bounds(a, b);
639 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
642 L.Transformation = L.Class.extend({
643 initialize: function (/*Number*/ a, /*Number*/ b, /*Number*/ c, /*Number*/ d) {
650 transform: function (point, scale) {
651 return this._transform(point.clone(), scale);
654 // destructive transform (faster)
655 _transform: function (/*Point*/ point, /*Number*/ scale) /*-> Point*/ {
657 point.x = scale * (this._a * point.x + this._b);
658 point.y = scale * (this._c * point.y + this._d);
662 untransform: function (/*Point*/ point, /*Number*/ scale) /*-> Point*/ {
665 (point.x / scale - this._b) / this._a,
666 (point.y / scale - this._d) / this._c);
672 * L.DomUtil contains various utility functions for working with DOM.
677 return (typeof id === 'string' ? document.getElementById(id) : id);
680 getStyle: function (el, style) {
682 var value = el.style[style];
684 if (!value && el.currentStyle) {
685 value = el.currentStyle[style];
688 if ((!value || value === 'auto') && document.defaultView) {
689 var css = document.defaultView.getComputedStyle(el, null);
690 value = css ? css[style] : null;
693 return value === 'auto' ? null : value;
696 getViewportOffset: function (element) {
701 docBody = document.body,
706 top += el.offsetTop || 0;
707 left += el.offsetLeft || 0;
708 pos = L.DomUtil.getStyle(el, 'position');
710 if (el.offsetParent === docBody && pos === 'absolute') { break; }
712 if (pos === 'fixed') {
713 top += docBody.scrollTop || 0;
714 left += docBody.scrollLeft || 0;
717 el = el.offsetParent;
724 if (el === docBody) { break; }
726 top -= el.scrollTop || 0;
727 left -= el.scrollLeft || 0;
729 //Webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
730 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
731 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
732 left += el.scrollWidth - el.clientWidth;
734 //ie7 shows the scrollbar by default and provides clientWidth counting it, so we need to add it back in if it is visible
735 // Scrollbar is on the left as we are RTL
736 if (ie7 && L.DomUtil.getStyle(el, 'overflow-y') !== 'hidden' && L.DomUtil.getStyle(el, 'overflow') !== 'hidden') {
744 return new L.Point(left, top);
747 documentIsLtr: function () {
748 if (!L.DomUtil._docIsLtrCached) {
749 L.DomUtil._docIsLtrCached = true;
750 L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === "ltr";
752 return L.DomUtil._docIsLtr;
755 create: function (tagName, className, container) {
757 var el = document.createElement(tagName);
758 el.className = className;
761 container.appendChild(el);
767 disableTextSelection: function () {
768 if (document.selection && document.selection.empty) {
769 document.selection.empty();
771 if (!this._onselectstart) {
772 this._onselectstart = document.onselectstart;
773 document.onselectstart = L.Util.falseFn;
777 enableTextSelection: function () {
778 if (document.onselectstart === L.Util.falseFn) {
779 document.onselectstart = this._onselectstart;
780 this._onselectstart = null;
784 hasClass: function (el, name) {
785 return (el.className.length > 0) &&
786 new RegExp("(^|\\s)" + name + "(\\s|$)").test(el.className);
789 addClass: function (el, name) {
790 if (!L.DomUtil.hasClass(el, name)) {
791 el.className += (el.className ? ' ' : '') + name;
795 removeClass: function (el, name) {
797 function replaceFn(w, match) {
798 if (match === name) { return ''; }
802 el.className = el.className
803 .replace(/(\S+)\s*/g, replaceFn)
804 .replace(/(^\s+|\s+$)/, '');
807 setOpacity: function (el, value) {
809 if ('opacity' in el.style) {
810 el.style.opacity = value;
812 } else if ('filter' in el.style) {
815 filterName = 'DXImageTransform.Microsoft.Alpha';
817 // filters collection throws an error if we try to retrieve a filter that doesn't exist
818 try { filter = el.filters.item(filterName); } catch (e) {}
820 value = Math.round(value * 100);
823 filter.Enabled = (value !== 100);
824 filter.Opacity = value;
826 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
831 testProp: function (props) {
833 var style = document.documentElement.style;
835 for (var i = 0; i < props.length; i++) {
836 if (props[i] in style) {
843 getTranslateString: function (point) {
844 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
845 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
846 // (same speed either way), Opera 12 doesn't support translate3d
848 var is3d = L.Browser.webkit3d,
849 open = 'translate' + (is3d ? '3d' : '') + '(',
850 close = (is3d ? ',0' : '') + ')';
852 return open + point.x + 'px,' + point.y + 'px' + close;
855 getScaleString: function (scale, origin) {
857 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
858 scaleStr = ' scale(' + scale + ') ';
860 return preTranslateStr + scaleStr;
863 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
865 el._leaflet_pos = point;
867 if (!disable3D && L.Browser.any3d) {
868 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
870 // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
871 if (L.Browser.mobileWebkit3d) {
872 el.style.WebkitBackfaceVisibility = 'hidden';
875 el.style.left = point.x + 'px';
876 el.style.top = point.y + 'px';
880 getPosition: function (el) {
881 // this method is only used for elements previously positioned using setPosition,
882 // so it's safe to cache the position for performance
883 return el._leaflet_pos;
888 // prefix style property names
890 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
891 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
893 L.DomUtil.TRANSITION = L.DomUtil.testProp(
894 ['transition', 'webkitTransition', 'OTransition', 'MozTransition', 'msTransition']);
896 L.DomUtil.TRANSITION_END =
897 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
898 L.DomUtil.TRANSITION + 'End' : 'transitionend';
902 CM.LatLng represents a geographical point with latitude and longtitude coordinates.
905 L.LatLng = function (rawLat, rawLng, noWrap) { // (Number, Number[, Boolean])
906 var lat = parseFloat(rawLat),
907 lng = parseFloat(rawLng);
909 if (isNaN(lat) || isNaN(lng)) {
910 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
913 if (noWrap !== true) {
914 lat = Math.max(Math.min(lat, 90), -90); // clamp latitude into -90..90
915 lng = (lng + 180) % 360 + ((lng < -180 || lng === 180) ? 180 : -180); // wrap longtitude into -180..180
922 L.Util.extend(L.LatLng, {
923 DEG_TO_RAD: Math.PI / 180,
924 RAD_TO_DEG: 180 / Math.PI,
925 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
928 L.LatLng.prototype = {
929 equals: function (obj) { // (LatLng) -> Boolean
930 if (!obj) { return false; }
934 var margin = Math.max(Math.abs(this.lat - obj.lat), Math.abs(this.lng - obj.lng));
935 return margin <= L.LatLng.MAX_MARGIN;
938 toString: function (precision) { // -> String
940 L.Util.formatNum(this.lat, precision) + ', ' +
941 L.Util.formatNum(this.lng, precision) + ')';
944 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
945 distanceTo: function (other) { // (LatLng) -> Number
946 other = L.latLng(other);
948 var R = 6378137, // earth radius in meters
949 d2r = L.LatLng.DEG_TO_RAD,
950 dLat = (other.lat - this.lat) * d2r,
951 dLon = (other.lng - this.lng) * d2r,
952 lat1 = this.lat * d2r,
953 lat2 = other.lat * d2r,
954 sin1 = Math.sin(dLat / 2),
955 sin2 = Math.sin(dLon / 2);
957 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
959 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
963 L.latLng = function (a, b, c) { // (LatLng) or ([Number, Number]) or (Number, Number, Boolean)
964 if (a instanceof L.LatLng) {
967 if (a instanceof Array) {
968 return new L.LatLng(a[0], a[1]);
973 return new L.LatLng(a, b, c);
979 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
982 L.LatLngBounds = L.Class.extend({
983 initialize: function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
984 if (!southWest) { return; }
986 var latlngs = northEast ? [southWest, northEast] : southWest;
988 for (var i = 0, len = latlngs.length; i < len; i++) {
989 this.extend(latlngs[i]);
993 // extend the bounds to contain the given point or bounds
994 extend: function (obj) { // (LatLng) or (LatLngBounds)
995 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
998 obj = L.latLngBounds(obj);
1001 if (obj instanceof L.LatLng) {
1002 if (!this._southWest && !this._northEast) {
1003 this._southWest = new L.LatLng(obj.lat, obj.lng, true);
1004 this._northEast = new L.LatLng(obj.lat, obj.lng, true);
1006 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1007 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1009 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1010 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1012 } else if (obj instanceof L.LatLngBounds) {
1013 this.extend(obj._southWest);
1014 this.extend(obj._northEast);
1019 // extend the bounds by a percentage
1020 pad: function (bufferRatio) { // (Number) -> LatLngBounds
1021 var sw = this._southWest,
1022 ne = this._northEast,
1023 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1024 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1026 return new L.LatLngBounds(
1027 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1028 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1031 getCenter: function () { // -> LatLng
1032 return new L.LatLng(
1033 (this._southWest.lat + this._northEast.lat) / 2,
1034 (this._southWest.lng + this._northEast.lng) / 2);
1037 getSouthWest: function () {
1038 return this._southWest;
1041 getNorthEast: function () {
1042 return this._northEast;
1045 getNorthWest: function () {
1046 return new L.LatLng(this._northEast.lat, this._southWest.lng, true);
1049 getSouthEast: function () {
1050 return new L.LatLng(this._southWest.lat, this._northEast.lng, true);
1053 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1054 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1055 obj = L.latLng(obj);
1057 obj = L.latLngBounds(obj);
1060 var sw = this._southWest,
1061 ne = this._northEast,
1064 if (obj instanceof L.LatLngBounds) {
1065 sw2 = obj.getSouthWest();
1066 ne2 = obj.getNorthEast();
1071 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1072 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1075 intersects: function (bounds) { // (LatLngBounds)
1076 bounds = L.latLngBounds(bounds);
1078 var sw = this._southWest,
1079 ne = this._northEast,
1080 sw2 = bounds.getSouthWest(),
1081 ne2 = bounds.getNorthEast();
1083 var latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1084 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1086 return latIntersects && lngIntersects;
1089 toBBoxString: function () {
1090 var sw = this._southWest,
1091 ne = this._northEast;
1092 return [sw.lng, sw.lat, ne.lng, ne.lat].join(',');
1095 equals: function (bounds) { // (LatLngBounds)
1096 if (!bounds) { return false; }
1098 bounds = L.latLngBounds(bounds);
1100 return this._southWest.equals(bounds.getSouthWest()) &&
1101 this._northEast.equals(bounds.getNorthEast());
1104 isValid: function () {
1105 return !!(this._southWest && this._northEast);
1109 //TODO International date line?
1111 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1112 if (!a || a instanceof L.LatLngBounds) {
1115 return new L.LatLngBounds(a, b);
1120 * L.Projection contains various geographical projections used by CRS classes.
1127 L.Projection.SphericalMercator = {
1128 MAX_LATITUDE: 85.0511287798,
1130 project: function (latlng) { // (LatLng) -> Point
1131 var d = L.LatLng.DEG_TO_RAD,
1132 max = this.MAX_LATITUDE,
1133 lat = Math.max(Math.min(max, latlng.lat), -max),
1136 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1138 return new L.Point(x, y);
1141 unproject: function (point) { // (Point, Boolean) -> LatLng
1142 var d = L.LatLng.RAD_TO_DEG,
1144 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1146 // TODO refactor LatLng wrapping
1147 return new L.LatLng(lat, lng, true);
1153 L.Projection.LonLat = {
1154 project: function (latlng) {
1155 return new L.Point(latlng.lng, latlng.lat);
1158 unproject: function (point) {
1159 return new L.LatLng(point.y, point.x, true);
1166 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1167 var projectedPoint = this.projection.project(latlng),
1168 scale = this.scale(zoom);
1170 return this.transformation._transform(projectedPoint, scale);
1173 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1174 var scale = this.scale(zoom),
1175 untransformedPoint = this.transformation.untransform(point, scale);
1177 return this.projection.unproject(untransformedPoint);
1180 project: function (latlng) {
1181 return this.projection.project(latlng);
1184 scale: function (zoom) {
1185 return 256 * Math.pow(2, zoom);
1191 L.CRS.Simple = L.Util.extend({}, L.CRS, {
1192 projection: L.Projection.LonLat,
1193 transformation: new L.Transformation(1, 0, 1, 0)
1198 L.CRS.EPSG3857 = L.Util.extend({}, L.CRS, {
1201 projection: L.Projection.SphericalMercator,
1202 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1204 project: function (latlng) { // (LatLng) -> Point
1205 var projectedPoint = this.projection.project(latlng),
1206 earthRadius = 6378137;
1207 return projectedPoint.multiplyBy(earthRadius);
1211 L.CRS.EPSG900913 = L.Util.extend({}, L.CRS.EPSG3857, {
1217 L.CRS.EPSG4326 = L.Util.extend({}, L.CRS, {
1220 projection: L.Projection.LonLat,
1221 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1226 * L.Map is the central class of the API - it is used to create a map.
1229 L.Map = L.Class.extend({
1231 includes: L.Mixin.Events,
1234 crs: L.CRS.EPSG3857,
1242 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1244 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1247 initialize: function (id, options) { // (HTMLElement or String, Object)
1248 options = L.Util.setOptions(this, options);
1250 this._initContainer(id);
1255 if (options.maxBounds) {
1256 this.setMaxBounds(options.maxBounds);
1259 if (options.center && options.zoom !== undefined) {
1260 this.setView(L.latLng(options.center), options.zoom, true);
1263 this._initLayers(options.layers);
1267 // public methods that modify map state
1269 // replaced by animation-powered implementation in Map.PanAnimation.js
1270 setView: function (center, zoom) {
1271 this._resetView(L.latLng(center), this._limitZoom(zoom));
1275 setZoom: function (zoom) { // (Number)
1276 return this.setView(this.getCenter(), zoom);
1279 zoomIn: function (delta) {
1280 return this.setZoom(this._zoom + (delta || 1));
1283 zoomOut: function (delta) {
1284 return this.setZoom(this._zoom - (delta || 1));
1287 fitBounds: function (bounds) { // (LatLngBounds)
1288 var zoom = this.getBoundsZoom(bounds);
1289 return this.setView(L.latLngBounds(bounds).getCenter(), zoom);
1292 fitWorld: function () {
1293 var sw = new L.LatLng(-60, -170),
1294 ne = new L.LatLng(85, 179);
1296 return this.fitBounds(new L.LatLngBounds(sw, ne));
1299 panTo: function (center) { // (LatLng)
1300 return this.setView(center, this._zoom);
1303 panBy: function (offset) { // (Point)
1304 // replaced with animated panBy in Map.Animation.js
1305 this.fire('movestart');
1307 this._rawPanBy(L.point(offset));
1310 return this.fire('moveend');
1313 setMaxBounds: function (bounds) {
1314 bounds = L.latLngBounds(bounds);
1316 this.options.maxBounds = bounds;
1319 this._boundsMinZoom = null;
1323 var minZoom = this.getBoundsZoom(bounds, true);
1325 this._boundsMinZoom = minZoom;
1328 if (this._zoom < minZoom) {
1329 this.setView(bounds.getCenter(), minZoom);
1331 this.panInsideBounds(bounds);
1338 panInsideBounds: function (bounds) {
1339 bounds = L.latLngBounds(bounds);
1341 var viewBounds = this.getBounds(),
1342 viewSw = this.project(viewBounds.getSouthWest()),
1343 viewNe = this.project(viewBounds.getNorthEast()),
1344 sw = this.project(bounds.getSouthWest()),
1345 ne = this.project(bounds.getNorthEast()),
1349 if (viewNe.y < ne.y) { // north
1350 dy = ne.y - viewNe.y;
1352 if (viewNe.x > ne.x) { // east
1353 dx = ne.x - viewNe.x;
1355 if (viewSw.y > sw.y) { // south
1356 dy = sw.y - viewSw.y;
1358 if (viewSw.x < sw.x) { // west
1359 dx = sw.x - viewSw.x;
1362 return this.panBy(new L.Point(dx, dy, true));
1365 addLayer: function (layer) {
1366 // TODO method is too big, refactor
1368 var id = L.Util.stamp(layer);
1370 if (this._layers[id]) { return this; }
1372 this._layers[id] = layer;
1374 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1375 if (layer.options && !isNaN(layer.options.maxZoom)) {
1376 this._layersMaxZoom = Math.max(this._layersMaxZoom || 0, layer.options.maxZoom);
1378 if (layer.options && !isNaN(layer.options.minZoom)) {
1379 this._layersMinZoom = Math.min(this._layersMinZoom || Infinity, layer.options.minZoom);
1382 // TODO looks ugly, refactor!!!
1383 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1384 this._tileLayersNum++;
1385 this._tileLayersToLoad++;
1386 layer.on('load', this._onTileLayerLoad, this);
1389 this.whenReady(function () {
1391 this.fire('layeradd', {layer: layer});
1397 removeLayer: function (layer) {
1398 var id = L.Util.stamp(layer);
1400 if (!this._layers[id]) { return; }
1402 layer.onRemove(this);
1404 delete this._layers[id];
1406 // TODO looks ugly, refactor
1407 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1408 this._tileLayersNum--;
1409 this._tileLayersToLoad--;
1410 layer.off('load', this._onTileLayerLoad, this);
1413 return this.fire('layerremove', {layer: layer});
1416 hasLayer: function (layer) {
1417 var id = L.Util.stamp(layer);
1418 return this._layers.hasOwnProperty(id);
1421 invalidateSize: function (animate) {
1422 var oldSize = this.getSize();
1424 this._sizeChanged = true;
1426 if (this.options.maxBounds) {
1427 this.setMaxBounds(this.options.maxBounds);
1430 if (!this._loaded) { return this; }
1432 var offset = oldSize._subtract(this.getSize())._divideBy(2)._round();
1434 if (animate === true) {
1437 this._rawPanBy(offset);
1441 clearTimeout(this._sizeTimer);
1442 this._sizeTimer = setTimeout(L.Util.bind(this.fire, this, 'moveend'), 200);
1447 // TODO handler.addTo
1448 addHandler: function (name, HandlerClass) {
1449 if (!HandlerClass) { return; }
1451 this[name] = new HandlerClass(this);
1453 if (this.options[name]) {
1454 this[name].enable();
1461 // public methods for getting map state
1463 getCenter: function () { // (Boolean) -> LatLng
1464 return this.layerPointToLatLng(this._getCenterLayerPoint());
1467 getZoom: function () {
1471 getBounds: function () {
1472 var bounds = this.getPixelBounds(),
1473 sw = this.unproject(bounds.getBottomLeft()),
1474 ne = this.unproject(bounds.getTopRight());
1476 return new L.LatLngBounds(sw, ne);
1479 getMinZoom: function () {
1480 var z1 = this.options.minZoom || 0,
1481 z2 = this._layersMinZoom || 0,
1482 z3 = this._boundsMinZoom || 0;
1484 return Math.max(z1, z2, z3);
1487 getMaxZoom: function () {
1488 var z1 = this.options.maxZoom === undefined ? Infinity : this.options.maxZoom,
1489 z2 = this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom;
1491 return Math.min(z1, z2);
1494 getBoundsZoom: function (bounds, inside) { // (LatLngBounds, Boolean) -> Number
1495 bounds = L.latLngBounds(bounds);
1497 var size = this.getSize(),
1498 zoom = this.options.minZoom || 0,
1499 maxZoom = this.getMaxZoom(),
1500 ne = bounds.getNorthEast(),
1501 sw = bounds.getSouthWest(),
1505 zoomNotFound = true;
1513 nePoint = this.project(ne, zoom);
1514 swPoint = this.project(sw, zoom);
1515 boundsSize = new L.Point(Math.abs(nePoint.x - swPoint.x), Math.abs(swPoint.y - nePoint.y));
1518 zoomNotFound = boundsSize.x <= size.x && boundsSize.y <= size.y;
1520 zoomNotFound = boundsSize.x < size.x || boundsSize.y < size.y;
1522 } while (zoomNotFound && zoom <= maxZoom);
1524 if (zoomNotFound && inside) {
1528 return inside ? zoom : zoom - 1;
1531 getSize: function () {
1532 if (!this._size || this._sizeChanged) {
1533 this._size = new L.Point(
1534 this._container.clientWidth,
1535 this._container.clientHeight);
1537 this._sizeChanged = false;
1539 return this._size.clone();
1542 getPixelBounds: function () {
1543 var topLeftPoint = this._getTopLeftPoint();
1544 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1547 getPixelOrigin: function () {
1548 return this._initialTopLeftPoint;
1551 getPanes: function () {
1555 getContainer: function () {
1556 return this._container;
1560 // TODO replace with universal implementation after refactoring projections
1562 getZoomScale: function (toZoom) {
1563 var crs = this.options.crs;
1564 return crs.scale(toZoom) / crs.scale(this._zoom);
1567 getScaleZoom: function (scale) {
1568 return this._zoom + (Math.log(scale) / Math.LN2);
1572 // conversion methods
1574 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1575 zoom = zoom === undefined ? this._zoom : zoom;
1576 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1579 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1580 zoom = zoom === undefined ? this._zoom : zoom;
1581 return this.options.crs.pointToLatLng(L.point(point), zoom);
1584 layerPointToLatLng: function (point) { // (Point)
1585 var projectedPoint = L.point(point).add(this._initialTopLeftPoint);
1586 return this.unproject(projectedPoint);
1589 latLngToLayerPoint: function (latlng) { // (LatLng)
1590 var projectedPoint = this.project(L.latLng(latlng))._round();
1591 return projectedPoint._subtract(this._initialTopLeftPoint);
1594 containerPointToLayerPoint: function (point) { // (Point)
1595 return L.point(point).subtract(this._getMapPanePos());
1598 layerPointToContainerPoint: function (point) { // (Point)
1599 return L.point(point).add(this._getMapPanePos());
1602 containerPointToLatLng: function (point) {
1603 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1604 return this.layerPointToLatLng(layerPoint);
1607 latLngToContainerPoint: function (latlng) {
1608 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1611 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1612 return L.DomEvent.getMousePosition(e, this._container);
1615 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1616 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1619 mouseEventToLatLng: function (e) { // (MouseEvent)
1620 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1624 // map initialization methods
1626 _initContainer: function (id) {
1627 var container = this._container = L.DomUtil.get(id);
1629 if (container._leaflet) {
1630 throw new Error("Map container is already initialized.");
1633 container._leaflet = true;
1636 _initLayout: function () {
1637 var container = this._container;
1639 container.innerHTML = '';
1640 L.DomUtil.addClass(container, 'leaflet-container');
1642 if (L.Browser.touch) {
1643 L.DomUtil.addClass(container, 'leaflet-touch');
1646 if (this.options.fadeAnimation) {
1647 L.DomUtil.addClass(container, 'leaflet-fade-anim');
1650 var position = L.DomUtil.getStyle(container, 'position');
1652 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
1653 container.style.position = 'relative';
1658 if (this._initControlPos) {
1659 this._initControlPos();
1663 _initPanes: function () {
1664 var panes = this._panes = {};
1666 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
1668 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
1669 this._objectsPane = panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
1671 panes.shadowPane = this._createPane('leaflet-shadow-pane');
1672 panes.overlayPane = this._createPane('leaflet-overlay-pane');
1673 panes.markerPane = this._createPane('leaflet-marker-pane');
1674 panes.popupPane = this._createPane('leaflet-popup-pane');
1676 var zoomHide = ' leaflet-zoom-hide';
1678 if (!this.options.markerZoomAnimation) {
1679 L.DomUtil.addClass(panes.markerPane, zoomHide);
1680 L.DomUtil.addClass(panes.shadowPane, zoomHide);
1681 L.DomUtil.addClass(panes.popupPane, zoomHide);
1685 _createPane: function (className, container) {
1686 return L.DomUtil.create('div', className, container || this._objectsPane);
1691 _initHooks: function () {
1693 for (i = 0, len = this._initializers.length; i < len; i++) {
1694 this._initializers[i].call(this);
1698 _initLayers: function (layers) {
1699 layers = layers ? (layers instanceof Array ? layers : [layers]) : [];
1702 this._tileLayersNum = 0;
1706 for (i = 0, len = layers.length; i < len; i++) {
1707 this.addLayer(layers[i]);
1712 // private methods that modify map state
1714 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
1716 var zoomChanged = (this._zoom !== zoom);
1718 if (!afterZoomAnim) {
1719 this.fire('movestart');
1722 this.fire('zoomstart');
1728 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
1730 if (!preserveMapOffset) {
1731 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
1733 this._initialTopLeftPoint._add(this._getMapPanePos());
1736 this._tileLayersToLoad = this._tileLayersNum;
1738 var loading = !this._loaded;
1739 this._loaded = true;
1741 this.fire('viewreset', {hard: !preserveMapOffset});
1745 if (zoomChanged || afterZoomAnim) {
1746 this.fire('zoomend');
1749 this.fire('moveend', {hard: !preserveMapOffset});
1756 _rawPanBy: function (offset) {
1757 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
1763 _initEvents: function () {
1764 if (!L.DomEvent) { return; }
1766 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
1768 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter', 'mouseleave', 'mousemove', 'contextmenu'],
1771 for (i = 0, len = events.length; i < len; i++) {
1772 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
1775 if (this.options.trackResize) {
1776 L.DomEvent.on(window, 'resize', this._onResize, this);
1780 _onResize: function () {
1781 L.Util.cancelAnimFrame(this._resizeRequest);
1782 this._resizeRequest = L.Util.requestAnimFrame(this.invalidateSize, this, false, this._container);
1785 _onMouseClick: function (e) {
1786 if (!this._loaded || (this.dragging && this.dragging.moved())) { return; }
1788 this.fire('preclick');
1789 this._fireMouseEvent(e);
1792 _fireMouseEvent: function (e) {
1793 if (!this._loaded) { return; }
1797 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
1799 if (!this.hasEventListeners(type)) { return; }
1801 if (type === 'contextmenu') {
1802 L.DomEvent.preventDefault(e);
1805 var containerPoint = this.mouseEventToContainerPoint(e),
1806 layerPoint = this.containerPointToLayerPoint(containerPoint),
1807 latlng = this.layerPointToLatLng(layerPoint);
1811 layerPoint: layerPoint,
1812 containerPoint: containerPoint,
1817 _onTileLayerLoad: function () {
1818 // TODO super-ugly, refactor!!!
1819 // clear scaled tiles after all new tiles are loaded (for performance)
1820 this._tileLayersToLoad--;
1821 if (this._tileLayersNum && !this._tileLayersToLoad && this._tileBg) {
1822 clearTimeout(this._clearTileBgTimer);
1823 this._clearTileBgTimer = setTimeout(L.Util.bind(this._clearTileBg, this), 500);
1827 whenReady: function (callback, context) {
1829 callback.call(context || this, this);
1831 this.on('load', callback, context);
1837 // private methods for getting map state
1839 _getMapPanePos: function () {
1840 return L.DomUtil.getPosition(this._mapPane);
1843 _getTopLeftPoint: function () {
1844 if (!this._loaded) {
1845 throw new Error('Set map center and zoom first.');
1848 return this._initialTopLeftPoint.subtract(this._getMapPanePos());
1851 _getNewTopLeftPoint: function (center, zoom) {
1852 var viewHalf = this.getSize()._divideBy(2);
1853 // TODO round on display, not calculation to increase precision?
1854 return this.project(center, zoom)._subtract(viewHalf)._round();
1857 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
1858 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
1859 return this.project(latlng, newZoom)._subtract(topLeft);
1862 _getCenterLayerPoint: function () {
1863 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
1866 _getCenterOffset: function (center) {
1867 return this.latLngToLayerPoint(center).subtract(this._getCenterLayerPoint());
1870 _limitZoom: function (zoom) {
1871 var min = this.getMinZoom(),
1872 max = this.getMaxZoom();
1874 return Math.max(min, Math.min(max, zoom));
1878 L.Map.addInitHook = function (fn) {
1879 var args = Array.prototype.slice.call(arguments, 1);
1881 var init = typeof fn === 'function' ? fn : function () {
1882 this[fn].apply(this, args);
1885 this.prototype._initializers.push(init);
1888 L.map = function (id, options) {
1889 return new L.Map(id, options);
1894 L.Projection.Mercator = {
1895 MAX_LATITUDE: 85.0840591556,
1897 R_MINOR: 6356752.3142,
1900 project: function (latlng) { // (LatLng) -> Point
1901 var d = L.LatLng.DEG_TO_RAD,
1902 max = this.MAX_LATITUDE,
1903 lat = Math.max(Math.min(max, latlng.lat), -max),
1906 x = latlng.lng * d * r,
1909 eccent = Math.sqrt(1.0 - tmp * tmp),
1910 con = eccent * Math.sin(y);
1912 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
1914 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
1915 y = -r2 * Math.log(ts);
1917 return new L.Point(x, y);
1920 unproject: function (point) { // (Point, Boolean) -> LatLng
1921 var d = L.LatLng.RAD_TO_DEG,
1924 lng = point.x * d / r,
1926 eccent = Math.sqrt(1 - (tmp * tmp)),
1927 ts = Math.exp(- point.y / r2),
1928 phi = (Math.PI / 2) - 2 * Math.atan(ts),
1935 while ((Math.abs(dphi) > tol) && (--i > 0)) {
1936 con = eccent * Math.sin(phi);
1937 dphi = (Math.PI / 2) - 2 * Math.atan(ts * Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
1941 return new L.LatLng(phi * d, lng, true);
1947 L.CRS.EPSG3395 = L.Util.extend({}, L.CRS, {
1950 projection: L.Projection.Mercator,
1952 transformation: (function () {
1953 var m = L.Projection.Mercator,
1957 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
1963 * L.TileLayer is used for standard xyz-numbered tile layers.
1966 L.TileLayer = L.Class.extend({
1967 includes: L.Mixin.Events,
1978 /* (undefined works too)
1981 continuousWorld: false,
1984 detectRetina: false,
1987 unloadInvisibleTiles: L.Browser.mobile,
1988 updateWhenIdle: L.Browser.mobile
1991 initialize: function (url, options) {
1992 options = L.Util.setOptions(this, options);
1994 // detecting retina displays, adjusting tileSize and zoom levels
1995 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
1997 options.tileSize = Math.floor(options.tileSize / 2);
1998 options.zoomOffset++;
2000 if (options.minZoom > 0) {
2003 this.options.maxZoom--;
2008 var subdomains = this.options.subdomains;
2010 if (typeof subdomains === 'string') {
2011 this.options.subdomains = subdomains.split('');
2015 onAdd: function (map) {
2018 // create a container div for tiles
2019 this._initContainer();
2021 // create an image to clone for tiles
2022 this._createTileProto();
2026 'viewreset': this._resetCallback,
2027 'moveend': this._update
2030 if (!this.options.updateWhenIdle) {
2031 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2032 map.on('move', this._limitedUpdate, this);
2039 addTo: function (map) {
2044 onRemove: function (map) {
2045 map._panes.tilePane.removeChild(this._container);
2048 'viewreset': this._resetCallback,
2049 'moveend': this._update
2052 if (!this.options.updateWhenIdle) {
2053 map.off('move', this._limitedUpdate, this);
2056 this._container = null;
2060 bringToFront: function () {
2061 var pane = this._map._panes.tilePane;
2063 if (this._container) {
2064 pane.appendChild(this._container);
2065 this._setAutoZIndex(pane, Math.max);
2071 bringToBack: function () {
2072 var pane = this._map._panes.tilePane;
2074 if (this._container) {
2075 pane.insertBefore(this._container, pane.firstChild);
2076 this._setAutoZIndex(pane, Math.min);
2082 getAttribution: function () {
2083 return this.options.attribution;
2086 setOpacity: function (opacity) {
2087 this.options.opacity = opacity;
2090 this._updateOpacity();
2096 setZIndex: function (zIndex) {
2097 this.options.zIndex = zIndex;
2098 this._updateZIndex();
2103 setUrl: function (url, noRedraw) {
2113 redraw: function () {
2115 this._map._panes.tilePane.empty = false;
2122 _updateZIndex: function () {
2123 if (this._container && this.options.zIndex !== undefined) {
2124 this._container.style.zIndex = this.options.zIndex;
2128 _setAutoZIndex: function (pane, compare) {
2130 var layers = pane.getElementsByClassName('leaflet-layer'),
2131 edgeZIndex = -compare(Infinity, -Infinity), // -Ifinity for max, Infinity for min
2134 for (var i = 0, len = layers.length; i < len; i++) {
2136 if (layers[i] !== this._container) {
2137 zIndex = parseInt(layers[i].style.zIndex, 10);
2139 if (!isNaN(zIndex)) {
2140 edgeZIndex = compare(edgeZIndex, zIndex);
2145 this.options.zIndex = this._container.style.zIndex = (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2148 _updateOpacity: function () {
2149 L.DomUtil.setOpacity(this._container, this.options.opacity);
2151 // stupid webkit hack to force redrawing of tiles
2153 tiles = this._tiles;
2155 if (L.Browser.webkit) {
2157 if (tiles.hasOwnProperty(i)) {
2158 tiles[i].style.webkitTransform += ' translate(0,0)';
2164 _initContainer: function () {
2165 var tilePane = this._map._panes.tilePane;
2167 if (!this._container || tilePane.empty) {
2168 this._container = L.DomUtil.create('div', 'leaflet-layer');
2170 this._updateZIndex();
2172 tilePane.appendChild(this._container);
2174 if (this.options.opacity < 1) {
2175 this._updateOpacity();
2180 _resetCallback: function (e) {
2181 this._reset(e.hard);
2184 _reset: function (clearOldContainer) {
2186 tiles = this._tiles;
2188 for (key in tiles) {
2189 if (tiles.hasOwnProperty(key)) {
2190 this.fire('tileunload', {tile: tiles[key]});
2195 this._tilesToLoad = 0;
2197 if (this.options.reuseTiles) {
2198 this._unusedTiles = [];
2201 if (clearOldContainer && this._container) {
2202 this._container.innerHTML = "";
2205 this._initContainer();
2208 _update: function (e) {
2210 if (!this._map) { return; }
2212 var bounds = this._map.getPixelBounds(),
2213 zoom = this._map.getZoom(),
2214 tileSize = this.options.tileSize;
2216 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2220 var nwTilePoint = new L.Point(
2221 Math.floor(bounds.min.x / tileSize),
2222 Math.floor(bounds.min.y / tileSize)),
2223 seTilePoint = new L.Point(
2224 Math.floor(bounds.max.x / tileSize),
2225 Math.floor(bounds.max.y / tileSize)),
2226 tileBounds = new L.Bounds(nwTilePoint, seTilePoint);
2228 this._addTilesFromCenterOut(tileBounds);
2230 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2231 this._removeOtherTiles(tileBounds);
2235 _addTilesFromCenterOut: function (bounds) {
2237 center = bounds.getCenter();
2241 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2242 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2243 point = new L.Point(i, j);
2245 if (this._tileShouldBeLoaded(point)) {
2251 var tilesToLoad = queue.length;
2253 if (tilesToLoad === 0) { return; }
2255 // load tiles in order of their distance to center
2256 queue.sort(function (a, b) {
2257 return a.distanceTo(center) - b.distanceTo(center);
2260 var fragment = document.createDocumentFragment();
2262 // if its the first batch of tiles to load
2263 if (!this._tilesToLoad) {
2264 this.fire('loading');
2267 this._tilesToLoad += tilesToLoad;
2269 for (i = 0; i < tilesToLoad; i++) {
2270 this._addTile(queue[i], fragment);
2273 this._container.appendChild(fragment);
2276 _tileShouldBeLoaded: function (tilePoint) {
2277 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2278 return false; // already loaded
2281 if (!this.options.continuousWorld) {
2282 var limit = this._getWrapTileNum();
2284 if (this.options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit) ||
2285 tilePoint.y < 0 || tilePoint.y >= limit) {
2286 return false; // exceeds world bounds
2293 _removeOtherTiles: function (bounds) {
2294 var kArr, x, y, key;
2296 for (key in this._tiles) {
2297 if (this._tiles.hasOwnProperty(key)) {
2298 kArr = key.split(':');
2299 x = parseInt(kArr[0], 10);
2300 y = parseInt(kArr[1], 10);
2302 // remove tile if it's out of bounds
2303 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2304 this._removeTile(key);
2310 _removeTile: function (key) {
2311 var tile = this._tiles[key];
2313 this.fire("tileunload", {tile: tile, url: tile.src});
2315 if (this.options.reuseTiles) {
2316 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2317 this._unusedTiles.push(tile);
2318 } else if (tile.parentNode === this._container) {
2319 this._container.removeChild(tile);
2322 if (!L.Browser.android) { //For https://github.com/CloudMade/Leaflet/issues/137
2323 tile.src = L.Util.emptyImageUrl;
2326 delete this._tiles[key];
2329 _addTile: function (tilePoint, container) {
2330 var tilePos = this._getTilePos(tilePoint);
2332 // get unused tile - or create a new tile
2333 var tile = this._getTile();
2335 // Chrome 20 layouts much faster with top/left (Verify with timeline, frames)
2336 // android 4 browser has display issues with top/left and requires transform instead
2337 // android 3 browser not tested
2338 // android 2 browser requires top/left or tiles disappear on load or first drag (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2339 // (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2340 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2342 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2344 this._loadTile(tile, tilePoint);
2346 if (tile.parentNode !== this._container) {
2347 container.appendChild(tile);
2351 _getZoomForUrl: function () {
2353 var options = this.options,
2354 zoom = this._map.getZoom();
2356 if (options.zoomReverse) {
2357 zoom = options.maxZoom - zoom;
2360 return zoom + options.zoomOffset;
2363 _getTilePos: function (tilePoint) {
2364 var origin = this._map.getPixelOrigin(),
2365 tileSize = this.options.tileSize;
2367 return tilePoint.multiplyBy(tileSize).subtract(origin);
2370 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2372 getTileUrl: function (tilePoint) {
2373 this._adjustTilePoint(tilePoint);
2375 return L.Util.template(this._url, L.Util.extend({
2376 s: this._getSubdomain(tilePoint),
2377 z: this._getZoomForUrl(),
2383 _getWrapTileNum: function () {
2384 // TODO refactor, limit is not valid for non-standard projections
2385 return Math.pow(2, this._getZoomForUrl());
2388 _adjustTilePoint: function (tilePoint) {
2390 var limit = this._getWrapTileNum();
2392 // wrap tile coordinates
2393 if (!this.options.continuousWorld && !this.options.noWrap) {
2394 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2397 if (this.options.tms) {
2398 tilePoint.y = limit - tilePoint.y - 1;
2402 _getSubdomain: function (tilePoint) {
2403 var index = (tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2404 return this.options.subdomains[index];
2407 _createTileProto: function () {
2408 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2409 img.galleryimg = 'no';
2411 var tileSize = this.options.tileSize;
2412 img.style.width = tileSize + 'px';
2413 img.style.height = tileSize + 'px';
2416 _getTile: function () {
2417 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2418 var tile = this._unusedTiles.pop();
2419 this._resetTile(tile);
2422 return this._createTile();
2425 _resetTile: function (tile) {
2426 // Override if data stored on a tile needs to be cleaned up before reuse
2429 _createTile: function () {
2430 var tile = this._tileImg.cloneNode(false);
2431 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2435 _loadTile: function (tile, tilePoint) {
2437 tile.onload = this._tileOnLoad;
2438 tile.onerror = this._tileOnError;
2440 tile.src = this.getTileUrl(tilePoint);
2443 _tileLoaded: function () {
2444 this._tilesToLoad--;
2445 if (!this._tilesToLoad) {
2450 _tileOnLoad: function (e) {
2451 var layer = this._layer;
2453 //Only if we are loading an actual image
2454 if (this.src !== L.Util.emptyImageUrl) {
2455 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2457 layer.fire('tileload', {
2463 layer._tileLoaded();
2466 _tileOnError: function (e) {
2467 var layer = this._layer;
2469 layer.fire('tileerror', {
2474 var newUrl = layer.options.errorTileUrl;
2479 layer._tileLoaded();
2483 L.tileLayer = function (url, options) {
2484 return new L.TileLayer(url, options);
2488 L.TileLayer.WMS = L.TileLayer.extend({
2496 format: 'image/jpeg',
2500 initialize: function (url, options) { // (String, Object)
2504 var wmsParams = L.Util.extend({}, this.defaultWmsParams);
2506 if (options.detectRetina && L.Browser.retina) {
2507 wmsParams.width = wmsParams.height = this.options.tileSize * 2;
2509 wmsParams.width = wmsParams.height = this.options.tileSize;
2512 for (var i in options) {
2513 // all keys that are not TileLayer options go to WMS params
2514 if (!this.options.hasOwnProperty(i)) {
2515 wmsParams[i] = options[i];
2519 this.wmsParams = wmsParams;
2521 L.Util.setOptions(this, options);
2524 onAdd: function (map) {
2526 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2527 this.wmsParams[projectionKey] = map.options.crs.code;
2529 L.TileLayer.prototype.onAdd.call(this, map);
2532 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
2534 var map = this._map,
2535 crs = map.options.crs,
2536 tileSize = this.options.tileSize,
2538 nwPoint = tilePoint.multiplyBy(tileSize),
2539 sePoint = nwPoint.add(new L.Point(tileSize, tileSize)),
2541 nw = crs.project(map.unproject(nwPoint, zoom)),
2542 se = crs.project(map.unproject(sePoint, zoom)),
2544 bbox = [nw.x, se.y, se.x, nw.y].join(','),
2546 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
2548 return url + L.Util.getParamString(this.wmsParams) + "&bbox=" + bbox;
2551 setParams: function (params, noRedraw) {
2553 L.Util.extend(this.wmsParams, params);
2563 L.tileLayer.wms = function (url, options) {
2564 return new L.TileLayer.WMS(url, options);
2568 L.TileLayer.Canvas = L.TileLayer.extend({
2573 initialize: function (options) {
2574 L.Util.setOptions(this, options);
2577 redraw: function () {
2579 tiles = this._tiles;
2582 if (tiles.hasOwnProperty(i)) {
2583 this._redrawTile(tiles[i]);
2588 _redrawTile: function (tile) {
2589 this.drawTile(tile, tile._tilePoint, this._map._zoom);
2592 _createTileProto: function () {
2593 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
2595 var tileSize = this.options.tileSize;
2596 proto.width = tileSize;
2597 proto.height = tileSize;
2600 _createTile: function () {
2601 var tile = this._canvasProto.cloneNode(false);
2602 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2606 _loadTile: function (tile, tilePoint) {
2608 tile._tilePoint = tilePoint;
2610 this._redrawTile(tile);
2612 if (!this.options.async) {
2613 this.tileDrawn(tile);
2617 drawTile: function (tile, tilePoint) {
2618 // override with rendering code
2621 tileDrawn: function (tile) {
2622 this._tileOnLoad.call(tile);
2627 L.tileLayer.canvas = function (options) {
2628 return new L.TileLayer.Canvas(options);
2631 L.ImageOverlay = L.Class.extend({
2632 includes: L.Mixin.Events,
2638 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
2640 this._bounds = L.latLngBounds(bounds);
2642 L.Util.setOptions(this, options);
2645 onAdd: function (map) {
2652 map._panes.overlayPane.appendChild(this._image);
2654 map.on('viewreset', this._reset, this);
2656 if (map.options.zoomAnimation && L.Browser.any3d) {
2657 map.on('zoomanim', this._animateZoom, this);
2663 onRemove: function (map) {
2664 map.getPanes().overlayPane.removeChild(this._image);
2666 map.off('viewreset', this._reset, this);
2668 if (map.options.zoomAnimation) {
2669 map.off('zoomanim', this._animateZoom, this);
2673 addTo: function (map) {
2678 setOpacity: function (opacity) {
2679 this.options.opacity = opacity;
2680 this._updateOpacity();
2684 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
2685 bringToFront: function () {
2687 this._map._panes.overlayPane.appendChild(this._image);
2692 bringToBack: function () {
2693 var pane = this._map._panes.overlayPane;
2695 pane.insertBefore(this._image, pane.firstChild);
2700 _initImage: function () {
2701 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
2703 if (this._map.options.zoomAnimation && L.Browser.any3d) {
2704 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
2706 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
2709 this._updateOpacity();
2711 //TODO createImage util method to remove duplication
2712 L.Util.extend(this._image, {
2714 onselectstart: L.Util.falseFn,
2715 onmousemove: L.Util.falseFn,
2716 onload: L.Util.bind(this._onImageLoad, this),
2721 _animateZoom: function (e) {
2722 var map = this._map,
2723 image = this._image,
2724 scale = map.getZoomScale(e.zoom),
2725 nw = this._bounds.getNorthWest(),
2726 se = this._bounds.getSouthEast(),
2728 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
2729 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
2730 currentSize = map.latLngToLayerPoint(se)._subtract(map.latLngToLayerPoint(nw)),
2731 origin = topLeft._add(size._subtract(currentSize)._divideBy(2));
2733 image.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
2736 _reset: function () {
2737 var image = this._image,
2738 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
2739 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
2741 L.DomUtil.setPosition(image, topLeft);
2743 image.style.width = size.x + 'px';
2744 image.style.height = size.y + 'px';
2747 _onImageLoad: function () {
2751 _updateOpacity: function () {
2752 L.DomUtil.setOpacity(this._image, this.options.opacity);
2756 L.imageOverlay = function (url, bounds, options) {
2757 return new L.ImageOverlay(url, bounds, options);
2761 L.Icon = L.Class.extend({
2764 iconUrl: (String) (required)
2765 iconSize: (Point) (can be set through CSS)
2766 iconAnchor: (Point) (centered by default if size is specified, can be set in CSS with negative margins)
2767 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
2768 shadowUrl: (Point) (no shadow by default)
2770 shadowAnchor: (Point)
2775 initialize: function (options) {
2776 L.Util.setOptions(this, options);
2779 createIcon: function () {
2780 return this._createIcon('icon');
2783 createShadow: function () {
2784 return this._createIcon('shadow');
2787 _createIcon: function (name) {
2788 var src = this._getIconUrl(name);
2791 if (name === 'icon') {
2792 throw new Error("iconUrl not set in Icon options (see the docs).");
2797 var img = this._createImg(src);
2798 this._setIconStyles(img, name);
2803 _setIconStyles: function (img, name) {
2804 var options = this.options,
2805 size = L.point(options[name + 'Size']),
2808 if (name === 'shadow') {
2809 anchor = L.point(options.shadowAnchor || options.iconAnchor);
2811 anchor = L.point(options.iconAnchor);
2814 if (!anchor && size) {
2815 anchor = size.divideBy(2, true);
2818 img.className = 'leaflet-marker-' + name + ' ' + options.className;
2821 img.style.marginLeft = (-anchor.x) + 'px';
2822 img.style.marginTop = (-anchor.y) + 'px';
2826 img.style.width = size.x + 'px';
2827 img.style.height = size.y + 'px';
2831 _createImg: function (src) {
2834 if (!L.Browser.ie6) {
2835 el = document.createElement('img');
2838 el = document.createElement('div');
2839 el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
2844 _getIconUrl: function (name) {
2845 return this.options[name + 'Url'];
2849 L.icon = function (options) {
2850 return new L.Icon(options);
2855 L.Icon.Default = L.Icon.extend({
2858 iconSize: new L.Point(25, 41),
2859 iconAnchor: new L.Point(12, 41),
2860 popupAnchor: new L.Point(1, -34),
2862 shadowSize: new L.Point(41, 41)
2865 _getIconUrl: function (name) {
2866 var key = name + 'Url';
2868 if (this.options[key]) {
2869 return this.options[key];
2872 var path = L.Icon.Default.imagePath;
2875 throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");
2878 return path + '/marker-' + name + '.png';
2882 L.Icon.Default.imagePath = (function () {
2883 var scripts = document.getElementsByTagName('script'),
2884 leafletRe = /\/?leaflet[\-\._]?([\w\-\._]*)\.js\??/;
2886 var i, len, src, matches;
2888 for (i = 0, len = scripts.length; i < len; i++) {
2889 src = scripts[i].src;
2890 matches = src.match(leafletRe);
2893 return src.split(leafletRe)[0] + '/images';
2900 * L.Marker is used to display clickable/draggable icons on the map.
2903 L.Marker = L.Class.extend({
2905 includes: L.Mixin.Events,
2908 icon: new L.Icon.Default(),
2918 initialize: function (latlng, options) {
2919 L.Util.setOptions(this, options);
2920 this._latlng = L.latLng(latlng);
2923 onAdd: function (map) {
2926 map.on('viewreset', this.update, this);
2931 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
2932 map.on('zoomanim', this._animateZoom, this);
2936 addTo: function (map) {
2941 onRemove: function (map) {
2944 this.fire('remove');
2947 'viewreset': this.update,
2948 'zoomanim': this._animateZoom
2954 getLatLng: function () {
2955 return this._latlng;
2958 setLatLng: function (latlng) {
2959 this._latlng = L.latLng(latlng);
2963 this.fire('move', { latlng: this._latlng });
2966 setZIndexOffset: function (offset) {
2967 this.options.zIndexOffset = offset;
2971 setIcon: function (icon) {
2976 this.options.icon = icon;
2984 update: function () {
2985 if (!this._icon) { return; }
2987 var pos = this._map.latLngToLayerPoint(this._latlng).round();
2991 _initIcon: function () {
2992 var options = this.options,
2994 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
2995 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide',
2996 needOpacityUpdate = false;
2999 this._icon = options.icon.createIcon();
3001 if (options.title) {
3002 this._icon.title = options.title;
3005 this._initInteraction();
3006 needOpacityUpdate = (this.options.opacity < 1);
3008 L.DomUtil.addClass(this._icon, classToAdd);
3010 if (options.riseOnHover) {
3012 .on(this._icon, 'mouseover', this._bringToFront, this)
3013 .on(this._icon, 'mouseout', this._resetZIndex, this);
3017 if (!this._shadow) {
3018 this._shadow = options.icon.createShadow();
3021 L.DomUtil.addClass(this._shadow, classToAdd);
3022 needOpacityUpdate = (this.options.opacity < 1);
3026 if (needOpacityUpdate) {
3027 this._updateOpacity();
3030 var panes = this._map._panes;
3032 panes.markerPane.appendChild(this._icon);
3035 panes.shadowPane.appendChild(this._shadow);
3039 _removeIcon: function () {
3040 var panes = this._map._panes;
3042 if (this.options.riseOnHover) {
3044 .off(this._icon, 'mouseover', this._bringToFront)
3045 .off(this._icon, 'mouseout', this._resetZIndex);
3048 panes.markerPane.removeChild(this._icon);
3051 panes.shadowPane.removeChild(this._shadow);
3054 this._icon = this._shadow = null;
3057 _setPos: function (pos) {
3058 L.DomUtil.setPosition(this._icon, pos);
3061 L.DomUtil.setPosition(this._shadow, pos);
3064 this._zIndex = pos.y + this.options.zIndexOffset;
3066 this._resetZIndex();
3069 _updateZIndex: function (offset) {
3070 this._icon.style.zIndex = this._zIndex + offset;
3073 _animateZoom: function (opt) {
3074 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3079 _initInteraction: function () {
3080 if (!this.options.clickable) {
3084 var icon = this._icon,
3085 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout'];
3087 L.DomUtil.addClass(icon, 'leaflet-clickable');
3088 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3090 for (var i = 0; i < events.length; i++) {
3091 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3094 if (L.Handler.MarkerDrag) {
3095 this.dragging = new L.Handler.MarkerDrag(this);
3097 if (this.options.draggable) {
3098 this.dragging.enable();
3103 _onMouseClick: function (e) {
3104 if (this.hasEventListeners(e.type)) {
3105 L.DomEvent.stopPropagation(e);
3107 if (this.dragging && this.dragging.moved()) { return; }
3108 if (this._map.dragging && this._map.dragging.moved()) { return; }
3114 _fireMouseEvent: function (e) {
3118 if (e.type !== 'mousedown') {
3119 L.DomEvent.stopPropagation(e);
3123 setOpacity: function (opacity) {
3124 this.options.opacity = opacity;
3126 this._updateOpacity();
3130 _updateOpacity: function () {
3131 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3133 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3137 _bringToFront: function () {
3138 this._updateZIndex(this.options.riseOffset);
3141 _resetZIndex: function () {
3142 this._updateZIndex(0);
3146 L.marker = function (latlng, options) {
3147 return new L.Marker(latlng, options);
3151 L.DivIcon = L.Icon.extend({
3153 iconSize: new L.Point(12, 12), // also can be set through CSS
3156 popupAnchor: (Point)
3160 className: 'leaflet-div-icon'
3163 createIcon: function () {
3164 var div = document.createElement('div'),
3165 options = this.options;
3168 div.innerHTML = options.html;
3171 if (options.bgPos) {
3172 div.style.backgroundPosition =
3173 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3176 this._setIconStyles(div, 'icon');
3180 createShadow: function () {
3185 L.divIcon = function (options) {
3186 return new L.DivIcon(options);
3191 L.Map.mergeOptions({
3192 closePopupOnClick: true
3195 L.Popup = L.Class.extend({
3196 includes: L.Mixin.Events,
3204 offset: new L.Point(0, 6),
3205 autoPanPadding: new L.Point(5, 5),
3209 initialize: function (options, source) {
3210 L.Util.setOptions(this, options);
3212 this._source = source;
3215 onAdd: function (map) {
3218 if (!this._container) {
3221 this._updateContent();
3223 var animFade = map.options.fadeAnimation;
3226 L.DomUtil.setOpacity(this._container, 0);
3228 map._panes.popupPane.appendChild(this._container);
3230 map.on('viewreset', this._updatePosition, this);
3232 if (L.Browser.any3d) {
3233 map.on('zoomanim', this._zoomAnimation, this);
3236 if (map.options.closePopupOnClick) {
3237 map.on('preclick', this._close, this);
3243 L.DomUtil.setOpacity(this._container, 1);
3247 addTo: function (map) {
3252 openOn: function (map) {
3253 map.openPopup(this);
3257 onRemove: function (map) {
3258 map._panes.popupPane.removeChild(this._container);
3260 L.Util.falseFn(this._container.offsetWidth); // force reflow
3263 viewreset: this._updatePosition,
3264 preclick: this._close,
3265 zoomanim: this._zoomAnimation
3268 if (map.options.fadeAnimation) {
3269 L.DomUtil.setOpacity(this._container, 0);
3275 setLatLng: function (latlng) {
3276 this._latlng = L.latLng(latlng);
3281 setContent: function (content) {
3282 this._content = content;
3287 _close: function () {
3288 var map = this._map;
3295 .fire('popupclose', {popup: this});
3299 _initLayout: function () {
3300 var prefix = 'leaflet-popup',
3301 container = this._container = L.DomUtil.create('div', prefix + ' ' + this.options.className + ' leaflet-zoom-animated'),
3304 if (this.options.closeButton) {
3305 closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
3306 closeButton.href = '#close';
3307 closeButton.innerHTML = '×';
3309 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3312 var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
3313 L.DomEvent.disableClickPropagation(wrapper);
3315 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3316 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
3318 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3319 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3322 _update: function () {
3323 if (!this._map) { return; }
3325 this._container.style.visibility = 'hidden';
3327 this._updateContent();
3328 this._updateLayout();
3329 this._updatePosition();
3331 this._container.style.visibility = '';
3336 _updateContent: function () {
3337 if (!this._content) { return; }
3339 if (typeof this._content === 'string') {
3340 this._contentNode.innerHTML = this._content;
3342 while (this._contentNode.hasChildNodes()) {
3343 this._contentNode.removeChild(this._contentNode.firstChild);
3345 this._contentNode.appendChild(this._content);
3347 this.fire('contentupdate');
3350 _updateLayout: function () {
3351 var container = this._contentNode,
3352 style = container.style;
3355 style.whiteSpace = 'nowrap';
3357 var width = container.offsetWidth;
3358 width = Math.min(width, this.options.maxWidth);
3359 width = Math.max(width, this.options.minWidth);
3361 style.width = (width + 1) + 'px';
3362 style.whiteSpace = '';
3366 var height = container.offsetHeight,
3367 maxHeight = this.options.maxHeight,
3368 scrolledClass = 'leaflet-popup-scrolled';
3370 if (maxHeight && height > maxHeight) {
3371 style.height = maxHeight + 'px';
3372 L.DomUtil.addClass(container, scrolledClass);
3374 L.DomUtil.removeClass(container, scrolledClass);
3377 this._containerWidth = this._container.offsetWidth;
3380 _updatePosition: function () {
3381 if (!this._map) { return; }
3383 var pos = this._map.latLngToLayerPoint(this._latlng),
3384 is3d = L.Browser.any3d,
3385 offset = this.options.offset;
3388 L.DomUtil.setPosition(this._container, pos);
3391 this._containerBottom = -offset.y - (is3d ? 0 : pos.y);
3392 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (is3d ? 0 : pos.x);
3394 //Bottom position the popup in case the height of the popup changes (images loading etc)
3395 this._container.style.bottom = this._containerBottom + 'px';
3396 this._container.style.left = this._containerLeft + 'px';
3399 _zoomAnimation: function (opt) {
3400 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3402 L.DomUtil.setPosition(this._container, pos);
3405 _adjustPan: function () {
3406 if (!this.options.autoPan) { return; }
3408 var map = this._map,
3409 containerHeight = this._container.offsetHeight,
3410 containerWidth = this._containerWidth,
3412 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
3414 if (L.Browser.any3d) {
3415 layerPos._add(L.DomUtil.getPosition(this._container));
3418 var containerPos = map.layerPointToContainerPoint(layerPos),
3419 padding = this.options.autoPanPadding,
3420 size = map.getSize(),
3424 if (containerPos.x < 0) {
3425 dx = containerPos.x - padding.x;
3427 if (containerPos.x + containerWidth > size.x) {
3428 dx = containerPos.x + containerWidth - size.x + padding.x;
3430 if (containerPos.y < 0) {
3431 dy = containerPos.y - padding.y;
3433 if (containerPos.y + containerHeight > size.y) {
3434 dy = containerPos.y + containerHeight - size.y + padding.y;
3438 map.panBy(new L.Point(dx, dy));
3442 _onCloseButtonClick: function (e) {
3448 L.popup = function (options, source) {
3449 return new L.Popup(options, source);
3454 * Popup extension to L.Marker, adding openPopup & bindPopup methods.
3458 openPopup: function () {
3459 if (this._popup && this._map) {
3460 this._popup.setLatLng(this._latlng);
3461 this._map.openPopup(this._popup);
3467 closePopup: function () {
3469 this._popup._close();
3474 bindPopup: function (content, options) {
3475 var anchor = L.point(this.options.icon.options.popupAnchor) || new L.Point(0, 0);
3477 anchor = anchor.add(L.Popup.prototype.options.offset);
3479 if (options && options.offset) {
3480 anchor = anchor.add(options.offset);
3483 options = L.Util.extend({offset: anchor}, options);
3487 .on('click', this.openPopup, this)
3488 .on('remove', this.closePopup, this)
3489 .on('move', this._movePopup, this);
3492 this._popup = new L.Popup(options, this)
3493 .setContent(content);
3498 unbindPopup: function () {
3502 .off('click', this.openPopup)
3503 .off('remove', this.closePopup)
3504 .off('move', this._movePopup);
3509 _movePopup: function (e) {
3510 this._popup.setLatLng(e.latlng);
3517 openPopup: function (popup) {
3520 this._popup = popup;
3524 .fire('popupopen', {popup: this._popup});
3527 closePopup: function () {
3529 this._popup._close();
3536 * L.LayerGroup is a class to combine several layers so you can manipulate the group (e.g. add/remove it) as one layer.
3539 L.LayerGroup = L.Class.extend({
3540 initialize: function (layers) {
3546 for (i = 0, len = layers.length; i < len; i++) {
3547 this.addLayer(layers[i]);
3552 addLayer: function (layer) {
3553 var id = L.Util.stamp(layer);
3555 this._layers[id] = layer;
3558 this._map.addLayer(layer);
3564 removeLayer: function (layer) {
3565 var id = L.Util.stamp(layer);
3567 delete this._layers[id];
3570 this._map.removeLayer(layer);
3576 clearLayers: function () {
3577 this.eachLayer(this.removeLayer, this);
3581 invoke: function (methodName) {
3582 var args = Array.prototype.slice.call(arguments, 1),
3585 for (i in this._layers) {
3586 if (this._layers.hasOwnProperty(i)) {
3587 layer = this._layers[i];
3589 if (layer[methodName]) {
3590 layer[methodName].apply(layer, args);
3598 onAdd: function (map) {
3600 this.eachLayer(map.addLayer, map);
3603 onRemove: function (map) {
3604 this.eachLayer(map.removeLayer, map);
3608 addTo: function (map) {
3613 eachLayer: function (method, context) {
3614 for (var i in this._layers) {
3615 if (this._layers.hasOwnProperty(i)) {
3616 method.call(context, this._layers[i]);
3622 L.layerGroup = function (layers) {
3623 return new L.LayerGroup(layers);
3628 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and bindPopup method shared between a group of layers.
3631 L.FeatureGroup = L.LayerGroup.extend({
3632 includes: L.Mixin.Events,
3634 addLayer: function (layer) {
3635 if (this._layers[L.Util.stamp(layer)]) {
3639 layer.on('click dblclick mouseover mouseout mousemove contextmenu', this._propagateEvent, this);
3641 L.LayerGroup.prototype.addLayer.call(this, layer);
3643 if (this._popupContent && layer.bindPopup) {
3644 layer.bindPopup(this._popupContent);
3650 removeLayer: function (layer) {
3651 layer.off('click dblclick mouseover mouseout mousemove contextmenu', this._propagateEvent, this);
3653 L.LayerGroup.prototype.removeLayer.call(this, layer);
3655 if (this._popupContent) {
3656 return this.invoke('unbindPopup');
3662 bindPopup: function (content) {
3663 this._popupContent = content;
3664 return this.invoke('bindPopup', content);
3667 setStyle: function (style) {
3668 return this.invoke('setStyle', style);
3671 bringToFront: function () {
3672 return this.invoke('bringToFront');
3675 bringToBack: function () {
3676 return this.invoke('bringToBack');
3679 getBounds: function () {
3680 var bounds = new L.LatLngBounds();
3681 this.eachLayer(function (layer) {
3682 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
3687 _propagateEvent: function (e) {
3691 this.fire(e.type, e);
3695 L.featureGroup = function (layers) {
3696 return new L.FeatureGroup(layers);
3701 * L.Path is a base class for rendering vector paths on a map. It's inherited by Polyline, Circle, etc.
3704 L.Path = L.Class.extend({
3705 includes: [L.Mixin.Events],
3708 // how much to extend the clip area around the map view
3709 // (relative to its size, e.g. 0.5 is half the screen in each direction)
3710 // set in such way that SVG element doesn't exceed 1280px (vector layers flicker on dragend if it is)
3711 CLIP_PADDING: L.Browser.mobile ?
3712 Math.max(0, Math.min(0.5,
3713 (1280 / Math.max(window.innerWidth, window.innerHeight) - 1) / 2))
3725 fillColor: null, //same as color by default
3731 initialize: function (options) {
3732 L.Util.setOptions(this, options);
3735 onAdd: function (map) {
3738 if (!this._container) {
3739 this._initElements();
3743 this.projectLatlngs();
3746 if (this._container) {
3747 this._map._pathRoot.appendChild(this._container);
3751 'viewreset': this.projectLatlngs,
3752 'moveend': this._updatePath
3756 addTo: function (map) {
3761 onRemove: function (map) {
3762 map._pathRoot.removeChild(this._container);
3766 if (L.Browser.vml) {
3767 this._container = null;
3768 this._stroke = null;
3772 this.fire('remove');
3775 'viewreset': this.projectLatlngs,
3776 'moveend': this._updatePath
3780 projectLatlngs: function () {
3781 // do all projection stuff here
3784 setStyle: function (style) {
3785 L.Util.setOptions(this, style);
3787 if (this._container) {
3788 this._updateStyle();
3794 redraw: function () {
3796 this.projectLatlngs();
3804 _updatePathViewport: function () {
3805 var p = L.Path.CLIP_PADDING,
3806 size = this.getSize(),
3807 panePos = L.DomUtil.getPosition(this._mapPane),
3808 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
3809 max = min.add(size.multiplyBy(1 + p * 2)._round());
3811 this._pathViewport = new L.Bounds(min, max);
3816 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
3818 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
3820 L.Path = L.Path.extend({
3825 bringToFront: function () {
3826 var root = this._map._pathRoot,
3827 path = this._container;
3829 if (path && root.lastChild !== path) {
3830 root.appendChild(path);
3835 bringToBack: function () {
3836 var root = this._map._pathRoot,
3837 path = this._container,
3838 first = root.firstChild;
3840 if (path && first !== path) {
3841 root.insertBefore(path, first);
3846 getPathString: function () {
3847 // form path string here
3850 _createElement: function (name) {
3851 return document.createElementNS(L.Path.SVG_NS, name);
3854 _initElements: function () {
3855 this._map._initPathRoot();
3860 _initPath: function () {
3861 this._container = this._createElement('g');
3863 this._path = this._createElement('path');
3864 this._container.appendChild(this._path);
3867 _initStyle: function () {
3868 if (this.options.stroke) {
3869 this._path.setAttribute('stroke-linejoin', 'round');
3870 this._path.setAttribute('stroke-linecap', 'round');
3872 if (this.options.fill) {
3873 this._path.setAttribute('fill-rule', 'evenodd');
3875 this._updateStyle();
3878 _updateStyle: function () {
3879 if (this.options.stroke) {
3880 this._path.setAttribute('stroke', this.options.color);
3881 this._path.setAttribute('stroke-opacity', this.options.opacity);
3882 this._path.setAttribute('stroke-width', this.options.weight);
3883 if (this.options.dashArray) {
3884 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
3886 this._path.removeAttribute('stroke-dasharray');
3889 this._path.setAttribute('stroke', 'none');
3891 if (this.options.fill) {
3892 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
3893 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
3895 this._path.setAttribute('fill', 'none');
3899 _updatePath: function () {
3900 var str = this.getPathString();
3902 // fix webkit empty string parsing bug
3905 this._path.setAttribute('d', str);
3908 // TODO remove duplication with L.Map
3909 _initEvents: function () {
3910 if (this.options.clickable) {
3911 if (L.Browser.svg || !L.Browser.vml) {
3912 this._path.setAttribute('class', 'leaflet-clickable');
3915 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
3917 var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'mousemove', 'contextmenu'];
3918 for (var i = 0; i < events.length; i++) {
3919 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
3924 _onMouseClick: function (e) {
3925 if (this._map.dragging && this._map.dragging.moved()) {
3929 this._fireMouseEvent(e);
3932 _fireMouseEvent: function (e) {
3933 if (!this.hasEventListeners(e.type)) {
3937 var map = this._map,
3938 containerPoint = map.mouseEventToContainerPoint(e),
3939 layerPoint = map.containerPointToLayerPoint(containerPoint),
3940 latlng = map.layerPointToLatLng(layerPoint);
3944 layerPoint: layerPoint,
3945 containerPoint: containerPoint,
3949 if (e.type === 'contextmenu') {
3950 L.DomEvent.preventDefault(e);
3952 L.DomEvent.stopPropagation(e);
3957 _initPathRoot: function () {
3958 if (!this._pathRoot) {
3959 this._pathRoot = L.Path.prototype._createElement('svg');
3960 this._panes.overlayPane.appendChild(this._pathRoot);
3962 if (this.options.zoomAnimation && L.Browser.any3d) {
3963 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
3966 'zoomanim': this._animatePathZoom,
3967 'zoomend': this._endPathZoom
3970 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
3973 this.on('moveend', this._updateSvgViewport);
3974 this._updateSvgViewport();
3978 _animatePathZoom: function (opt) {
3979 var scale = this.getZoomScale(opt.zoom),
3980 offset = this._getCenterOffset(opt.center),
3981 translate = offset.multiplyBy(-scale)._add(this._pathViewport.min);
3983 this._pathRoot.style[L.DomUtil.TRANSFORM] =
3984 L.DomUtil.getTranslateString(translate) + ' scale(' + scale + ') ';
3986 this._pathZooming = true;
3989 _endPathZoom: function () {
3990 this._pathZooming = false;
3993 _updateSvgViewport: function () {
3994 if (this._pathZooming) {
3995 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
3996 // When the zoom animation ends we will be updated again anyway
3997 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4001 this._updatePathViewport();
4003 var vp = this._pathViewport,
4006 width = max.x - min.x,
4007 height = max.y - min.y,
4008 root = this._pathRoot,
4009 pane = this._panes.overlayPane;
4011 // Hack to make flicker on drag end on mobile webkit less irritating
4012 if (L.Browser.mobileWebkit) {
4013 pane.removeChild(root);
4016 L.DomUtil.setPosition(root, min);
4017 root.setAttribute('width', width);
4018 root.setAttribute('height', height);
4019 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4021 if (L.Browser.mobileWebkit) {
4022 pane.appendChild(root);
4029 * Popup extension to L.Path (polylines, polygons, circles), adding bindPopup method.
4034 bindPopup: function (content, options) {
4036 if (!this._popup || this._popup.options !== options) {
4037 this._popup = new L.Popup(options, this);
4040 this._popup.setContent(content);
4042 if (!this._popupHandlersAdded) {
4044 .on('click', this._openPopup, this)
4045 .on('remove', this._closePopup, this);
4046 this._popupHandlersAdded = true;
4052 unbindPopup: function () {
4056 .off('click', this.openPopup)
4057 .off('remove', this.closePopup);
4062 openPopup: function (latlng) {
4065 latlng = latlng || this._latlng ||
4066 this._latlngs[Math.floor(this._latlngs.length / 2)];
4068 this._openPopup({latlng: latlng});
4074 _openPopup: function (e) {
4075 this._popup.setLatLng(e.latlng);
4076 this._map.openPopup(this._popup);
4079 _closePopup: function () {
4080 this._popup._close();
4086 * Vector rendering for IE6-8 through VML.
4087 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4090 L.Browser.vml = !L.Browser.svg && (function () {
4092 var div = document.createElement('div');
4093 div.innerHTML = '<v:shape adj="1"/>';
4095 var shape = div.firstChild;
4096 shape.style.behavior = 'url(#default#VML)';
4098 return shape && (typeof shape.adj === 'object');
4104 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4110 _createElement: (function () {
4112 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4113 return function (name) {
4114 return document.createElement('<lvml:' + name + ' class="lvml">');
4117 return function (name) {
4118 return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4123 _initPath: function () {
4124 var container = this._container = this._createElement('shape');
4125 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4126 if (this.options.clickable) {
4127 L.DomUtil.addClass(container, 'leaflet-clickable');
4129 container.coordsize = '1 1';
4131 this._path = this._createElement('path');
4132 container.appendChild(this._path);
4134 this._map._pathRoot.appendChild(container);
4137 _initStyle: function () {
4138 this._updateStyle();
4141 _updateStyle: function () {
4142 var stroke = this._stroke,
4144 options = this.options,
4145 container = this._container;
4147 container.stroked = options.stroke;
4148 container.filled = options.fill;
4150 if (options.stroke) {
4152 stroke = this._stroke = this._createElement('stroke');
4153 stroke.endcap = 'round';
4154 container.appendChild(stroke);
4156 stroke.weight = options.weight + 'px';
4157 stroke.color = options.color;
4158 stroke.opacity = options.opacity;
4159 if (options.dashArray) {
4160 stroke.dashStyle = options.dashArray.replace(/ *, */g, ' ');
4162 stroke.dashStyle = '';
4164 } else if (stroke) {
4165 container.removeChild(stroke);
4166 this._stroke = null;
4171 fill = this._fill = this._createElement('fill');
4172 container.appendChild(fill);
4174 fill.color = options.fillColor || options.color;
4175 fill.opacity = options.fillOpacity;
4177 container.removeChild(fill);
4182 _updatePath: function () {
4183 var style = this._container.style;
4185 style.display = 'none';
4186 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4191 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4192 _initPathRoot: function () {
4193 if (this._pathRoot) { return; }
4195 var root = this._pathRoot = document.createElement('div');
4196 root.className = 'leaflet-vml-container';
4197 this._panes.overlayPane.appendChild(root);
4199 this.on('moveend', this._updatePathViewport);
4200 this._updatePathViewport();
4206 * Vector rendering for all browsers that support canvas.
4209 L.Browser.canvas = (function () {
4210 return !!document.createElement('canvas').getContext;
4213 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4215 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4220 redraw: function () {
4222 this.projectLatlngs();
4223 this._requestUpdate();
4228 setStyle: function (style) {
4229 L.Util.setOptions(this, style);
4232 this._updateStyle();
4233 this._requestUpdate();
4238 onRemove: function (map) {
4240 .off('viewreset', this.projectLatlngs, this)
4241 .off('moveend', this._updatePath, this);
4243 this._requestUpdate();
4248 _requestUpdate: function () {
4249 if (this._map && !L.Path._updateRequest) {
4250 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4254 _fireMapMoveEnd: function () {
4255 L.Path._updateRequest = null;
4256 this.fire('moveend');
4259 _initElements: function () {
4260 this._map._initPathRoot();
4261 this._ctx = this._map._canvasCtx;
4264 _updateStyle: function () {
4265 var options = this.options;
4267 if (options.stroke) {
4268 this._ctx.lineWidth = options.weight;
4269 this._ctx.strokeStyle = options.color;
4272 this._ctx.fillStyle = options.fillColor || options.color;
4276 _drawPath: function () {
4277 var i, j, len, len2, point, drawMethod;
4279 this._ctx.beginPath();
4281 for (i = 0, len = this._parts.length; i < len; i++) {
4282 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4283 point = this._parts[i][j];
4284 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4286 this._ctx[drawMethod](point.x, point.y);
4288 // TODO refactor ugly hack
4289 if (this instanceof L.Polygon) {
4290 this._ctx.closePath();
4295 _checkIfEmpty: function () {
4296 return !this._parts.length;
4299 _updatePath: function () {
4300 if (this._checkIfEmpty()) { return; }
4302 var ctx = this._ctx,
4303 options = this.options;
4307 this._updateStyle();
4310 if (options.fillOpacity < 1) {
4311 ctx.globalAlpha = options.fillOpacity;
4316 if (options.stroke) {
4317 if (options.opacity < 1) {
4318 ctx.globalAlpha = options.opacity;
4325 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
4328 _initEvents: function () {
4329 if (this.options.clickable) {
4331 // TODO mouseover, mouseout, dblclick
4332 this._map.on('click', this._onClick, this);
4336 _onClick: function (e) {
4337 if (this._containsPoint(e.layerPoint)) {
4338 this.fire('click', e);
4343 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
4344 _initPathRoot: function () {
4345 var root = this._pathRoot,
4349 root = this._pathRoot = document.createElement("canvas");
4350 root.style.position = 'absolute';
4351 ctx = this._canvasCtx = root.getContext('2d');
4353 ctx.lineCap = "round";
4354 ctx.lineJoin = "round";
4356 this._panes.overlayPane.appendChild(root);
4358 if (this.options.zoomAnimation) {
4359 this._pathRoot.className = 'leaflet-zoom-animated';
4360 this.on('zoomanim', this._animatePathZoom);
4361 this.on('zoomend', this._endPathZoom);
4363 this.on('moveend', this._updateCanvasViewport);
4364 this._updateCanvasViewport();
4368 _updateCanvasViewport: function () {
4369 if (this._pathZooming) {
4370 //Don't redraw while zooming. See _updateSvgViewport for more details
4373 this._updatePathViewport();
4375 var vp = this._pathViewport,
4377 size = vp.max.subtract(min),
4378 root = this._pathRoot;
4380 //TODO check if this works properly on mobile webkit
4381 L.DomUtil.setPosition(root, min);
4382 root.width = size.x;
4383 root.height = size.y;
4384 root.getContext('2d').translate(-min.x, -min.y);
4390 * L.LineUtil contains different utility functions for line segments
4391 * and polylines (clipping, simplification, distances, etc.)
4396 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
4397 // Improves rendering performance dramatically by lessening the number of points to draw.
4399 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
4400 if (!tolerance || !points.length) {
4401 return points.slice();
4404 var sqTolerance = tolerance * tolerance;
4406 // stage 1: vertex reduction
4407 points = this._reducePoints(points, sqTolerance);
4409 // stage 2: Douglas-Peucker simplification
4410 points = this._simplifyDP(points, sqTolerance);
4415 // distance from a point to a segment between two points
4416 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
4417 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
4420 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
4421 return this._sqClosestPointOnSegment(p, p1, p2);
4424 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
4425 _simplifyDP: function (points, sqTolerance) {
4427 var len = points.length,
4428 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
4429 markers = new ArrayConstructor(len);
4431 markers[0] = markers[len - 1] = 1;
4433 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
4438 for (i = 0; i < len; i++) {
4440 newPoints.push(points[i]);
4447 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
4452 for (i = first + 1; i <= last - 1; i++) {
4453 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
4455 if (sqDist > maxSqDist) {
4461 if (maxSqDist > sqTolerance) {
4464 this._simplifyDPStep(points, markers, sqTolerance, first, index);
4465 this._simplifyDPStep(points, markers, sqTolerance, index, last);
4469 // reduce points that are too close to each other to a single point
4470 _reducePoints: function (points, sqTolerance) {
4471 var reducedPoints = [points[0]];
4473 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
4474 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
4475 reducedPoints.push(points[i]);
4479 if (prev < len - 1) {
4480 reducedPoints.push(points[len - 1]);
4482 return reducedPoints;
4485 /*jshint bitwise:false */ // temporarily allow bitwise oprations
4487 // Cohen-Sutherland line clipping algorithm.
4488 // Used to avoid rendering parts of a polyline that are not currently visible.
4490 clipSegment: function (a, b, bounds, useLastCode) {
4491 var min = bounds.min,
4494 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
4495 codeB = this._getBitCode(b, bounds);
4497 // save 2nd code to avoid calculating it on the next segment
4498 this._lastCode = codeB;
4501 // if a,b is inside the clip window (trivial accept)
4502 if (!(codeA | codeB)) {
4504 // if a,b is outside the clip window (trivial reject)
4505 } else if (codeA & codeB) {
4509 var codeOut = codeA || codeB,
4510 p = this._getEdgeIntersection(a, b, codeOut, bounds),
4511 newCode = this._getBitCode(p, bounds);
4513 if (codeOut === codeA) {
4524 _getEdgeIntersection: function (a, b, code, bounds) {
4530 if (code & 8) { // top
4531 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
4532 } else if (code & 4) { // bottom
4533 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
4534 } else if (code & 2) { // right
4535 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
4536 } else if (code & 1) { // left
4537 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
4541 _getBitCode: function (/*Point*/ p, bounds) {
4544 if (p.x < bounds.min.x) { // left
4546 } else if (p.x > bounds.max.x) { // right
4549 if (p.y < bounds.min.y) { // bottom
4551 } else if (p.y > bounds.max.y) { // top
4558 /*jshint bitwise:true */
4560 // square distance (to avoid unnecessary Math.sqrt calls)
4561 _sqDist: function (p1, p2) {
4562 var dx = p2.x - p1.x,
4564 return dx * dx + dy * dy;
4567 // return closest point on segment or distance to that point
4568 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
4573 dot = dx * dx + dy * dy,
4577 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
4591 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
4596 L.Polyline = L.Path.extend({
4597 initialize: function (latlngs, options) {
4598 L.Path.prototype.initialize.call(this, options);
4600 this._latlngs = this._convertLatLngs(latlngs);
4602 // TODO refactor: move to Polyline.Edit.js
4603 if (L.Handler.PolyEdit) {
4604 this.editing = new L.Handler.PolyEdit(this);
4606 if (this.options.editable) {
4607 this.editing.enable();
4613 // how much to simplify the polyline on each zoom level
4614 // more = better performance and smoother look, less = more accurate
4619 projectLatlngs: function () {
4620 this._originalPoints = [];
4622 for (var i = 0, len = this._latlngs.length; i < len; i++) {
4623 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
4627 getPathString: function () {
4628 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
4629 str += this._getPathPartStr(this._parts[i]);
4634 getLatLngs: function () {
4635 return this._latlngs;
4638 setLatLngs: function (latlngs) {
4639 this._latlngs = this._convertLatLngs(latlngs);
4640 return this.redraw();
4643 addLatLng: function (latlng) {
4644 this._latlngs.push(L.latLng(latlng));
4645 return this.redraw();
4648 spliceLatLngs: function (index, howMany) {
4649 var removed = [].splice.apply(this._latlngs, arguments);
4650 this._convertLatLngs(this._latlngs);
4655 closestLayerPoint: function (p) {
4656 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
4658 for (var j = 0, jLen = parts.length; j < jLen; j++) {
4659 var points = parts[j];
4660 for (var i = 1, len = points.length; i < len; i++) {
4663 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
4664 if (sqDist < minDistance) {
4665 minDistance = sqDist;
4666 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
4671 minPoint.distance = Math.sqrt(minDistance);
4676 getBounds: function () {
4677 var b = new L.LatLngBounds();
4678 var latLngs = this.getLatLngs();
4679 for (var i = 0, len = latLngs.length; i < len; i++) {
4680 b.extend(latLngs[i]);
4685 // TODO refactor: move to Polyline.Edit.js
4686 onAdd: function (map) {
4687 L.Path.prototype.onAdd.call(this, map);
4689 if (this.editing && this.editing.enabled()) {
4690 this.editing.addHooks();
4694 onRemove: function (map) {
4695 if (this.editing && this.editing.enabled()) {
4696 this.editing.removeHooks();
4699 L.Path.prototype.onRemove.call(this, map);
4702 _convertLatLngs: function (latlngs) {
4704 for (i = 0, len = latlngs.length; i < len; i++) {
4705 if (latlngs[i] instanceof Array && typeof latlngs[i][0] !== 'number') {
4708 latlngs[i] = L.latLng(latlngs[i]);
4713 _initEvents: function () {
4714 L.Path.prototype._initEvents.call(this);
4717 _getPathPartStr: function (points) {
4718 var round = L.Path.VML;
4720 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
4725 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
4730 _clipPoints: function () {
4731 var points = this._originalPoints,
4732 len = points.length,
4735 if (this.options.noClip) {
4736 this._parts = [points];
4742 var parts = this._parts,
4743 vp = this._map._pathViewport,
4746 for (i = 0, k = 0; i < len - 1; i++) {
4747 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
4752 parts[k] = parts[k] || [];
4753 parts[k].push(segment[0]);
4755 // if segment goes out of screen, or it's the last one, it's the end of the line part
4756 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
4757 parts[k].push(segment[1]);
4763 // simplify each clipped part of the polyline
4764 _simplifyPoints: function () {
4765 var parts = this._parts,
4768 for (var i = 0, len = parts.length; i < len; i++) {
4769 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
4773 _updatePath: function () {
4774 if (!this._map) { return; }
4777 this._simplifyPoints();
4779 L.Path.prototype._updatePath.call(this);
4783 L.polyline = function (latlngs, options) {
4784 return new L.Polyline(latlngs, options);
4789 * L.PolyUtil contains utilify functions for polygons (clipping, etc.).
4792 /*jshint bitwise:false */ // allow bitwise oprations here
4797 * Sutherland-Hodgeman polygon clipping algorithm.
4798 * Used to avoid rendering parts of a polygon that are not currently visible.
4800 L.PolyUtil.clipPolygon = function (points, bounds) {
4801 var min = bounds.min,
4804 edges = [1, 4, 2, 8],
4810 for (i = 0, len = points.length; i < len; i++) {
4811 points[i]._code = lu._getBitCode(points[i], bounds);
4814 // for each edge (left, bottom, right, top)
4815 for (k = 0; k < 4; k++) {
4819 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
4823 // if a is inside the clip window
4824 if (!(a._code & edge)) {
4825 // if b is outside the clip window (a->b goes out of screen)
4826 if (b._code & edge) {
4827 p = lu._getEdgeIntersection(b, a, edge, bounds);
4828 p._code = lu._getBitCode(p, bounds);
4829 clippedPoints.push(p);
4831 clippedPoints.push(a);
4833 // else if b is inside the clip window (a->b enters the screen)
4834 } else if (!(b._code & edge)) {
4835 p = lu._getEdgeIntersection(b, a, edge, bounds);
4836 p._code = lu._getBitCode(p, bounds);
4837 clippedPoints.push(p);
4840 points = clippedPoints;
4846 /*jshint bitwise:true */
4850 * L.Polygon is used to display polygons on a map.
4853 L.Polygon = L.Polyline.extend({
4858 initialize: function (latlngs, options) {
4859 L.Polyline.prototype.initialize.call(this, latlngs, options);
4861 if (latlngs && (latlngs[0] instanceof Array) && (typeof latlngs[0][0] !== 'number')) {
4862 this._latlngs = this._convertLatLngs(latlngs[0]);
4863 this._holes = latlngs.slice(1);
4867 projectLatlngs: function () {
4868 L.Polyline.prototype.projectLatlngs.call(this);
4870 // project polygon holes points
4871 // TODO move this logic to Polyline to get rid of duplication
4872 this._holePoints = [];
4878 for (var i = 0, len = this._holes.length, hole; i < len; i++) {
4879 this._holePoints[i] = [];
4881 for (var j = 0, len2 = this._holes[i].length; j < len2; j++) {
4882 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
4887 _clipPoints: function () {
4888 var points = this._originalPoints,
4891 this._parts = [points].concat(this._holePoints);
4893 if (this.options.noClip) {
4897 for (var i = 0, len = this._parts.length; i < len; i++) {
4898 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
4899 if (!clipped.length) {
4902 newParts.push(clipped);
4905 this._parts = newParts;
4908 _getPathPartStr: function (points) {
4909 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
4910 return str + (L.Browser.svg ? 'z' : 'x');
4914 L.polygon = function (latlngs, options) {
4915 return new L.Polygon(latlngs, options);
4920 * Contains L.MultiPolyline and L.MultiPolygon layers.
4924 function createMulti(Klass) {
4925 return L.FeatureGroup.extend({
4926 initialize: function (latlngs, options) {
4928 this._options = options;
4929 this.setLatLngs(latlngs);
4932 setLatLngs: function (latlngs) {
4933 var i = 0, len = latlngs.length;
4935 this.eachLayer(function (layer) {
4937 layer.setLatLngs(latlngs[i++]);
4939 this.removeLayer(layer);
4944 this.addLayer(new Klass(latlngs[i++], this._options));
4952 L.MultiPolyline = createMulti(L.Polyline);
4953 L.MultiPolygon = createMulti(L.Polygon);
4955 L.multiPolyline = function (latlngs, options) {
4956 return new L.MultiPolyline(latlngs, options);
4959 L.multiPolygon = function (latlngs, options) {
4960 return new L.MultiPolygon(latlngs, options);
4966 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds
4969 L.Rectangle = L.Polygon.extend({
4970 initialize: function (latLngBounds, options) {
4971 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
4974 setBounds: function (latLngBounds) {
4975 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
4978 _boundsToLatLngs: function (latLngBounds) {
4979 latLngBounds = L.latLngBounds(latLngBounds);
4981 latLngBounds.getSouthWest(),
4982 latLngBounds.getNorthWest(),
4983 latLngBounds.getNorthEast(),
4984 latLngBounds.getSouthEast(),
4985 latLngBounds.getSouthWest()
4990 L.rectangle = function (latLngBounds, options) {
4991 return new L.Rectangle(latLngBounds, options);
4996 * L.Circle is a circle overlay (with a certain radius in meters).
4999 L.Circle = L.Path.extend({
5000 initialize: function (latlng, radius, options) {
5001 L.Path.prototype.initialize.call(this, options);
5003 this._latlng = L.latLng(latlng);
5004 this._mRadius = radius;
5011 setLatLng: function (latlng) {
5012 this._latlng = L.latLng(latlng);
5013 return this.redraw();
5016 setRadius: function (radius) {
5017 this._mRadius = radius;
5018 return this.redraw();
5021 projectLatlngs: function () {
5022 var lngRadius = this._getLngRadius(),
5023 latlng2 = new L.LatLng(this._latlng.lat, this._latlng.lng - lngRadius, true),
5024 point2 = this._map.latLngToLayerPoint(latlng2);
5026 this._point = this._map.latLngToLayerPoint(this._latlng);
5027 this._radius = Math.max(Math.round(this._point.x - point2.x), 1);
5030 getBounds: function () {
5031 var lngRadius = this._getLngRadius(),
5032 latRadius = (this._mRadius / 40075017) * 360,
5033 latlng = this._latlng,
5034 sw = new L.LatLng(latlng.lat - latRadius, latlng.lng - lngRadius),
5035 ne = new L.LatLng(latlng.lat + latRadius, latlng.lng + lngRadius);
5037 return new L.LatLngBounds(sw, ne);
5040 getLatLng: function () {
5041 return this._latlng;
5044 getPathString: function () {
5045 var p = this._point,
5048 if (this._checkIfEmpty()) {
5052 if (L.Browser.svg) {
5053 return "M" + p.x + "," + (p.y - r) +
5054 "A" + r + "," + r + ",0,1,1," +
5055 (p.x - 0.1) + "," + (p.y - r) + " z";
5059 return "AL " + p.x + "," + p.y + " " + r + "," + r + " 0," + (65535 * 360);
5063 getRadius: function () {
5064 return this._mRadius;
5067 // TODO Earth hardcoded, move into projection code!
5069 _getLatRadius: function () {
5070 return (this._mRadius / 40075017) * 360;
5073 _getLngRadius: function () {
5074 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5077 _checkIfEmpty: function () {
5081 var vp = this._map._pathViewport,
5085 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5086 p.x + r < vp.min.x || p.y + r < vp.min.y;
5090 L.circle = function (latlng, radius, options) {
5091 return new L.Circle(latlng, radius, options);
5096 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5099 L.CircleMarker = L.Circle.extend({
5105 initialize: function (latlng, options) {
5106 L.Circle.prototype.initialize.call(this, latlng, null, options);
5107 this._radius = this.options.radius;
5110 projectLatlngs: function () {
5111 this._point = this._map.latLngToLayerPoint(this._latlng);
5114 setRadius: function (radius) {
5115 this._radius = radius;
5116 return this.redraw();
5120 L.circleMarker = function (latlng, options) {
5121 return new L.CircleMarker(latlng, options);
5126 L.Polyline.include(!L.Path.CANVAS ? {} : {
5127 _containsPoint: function (p, closed) {
5128 var i, j, k, len, len2, dist, part,
5129 w = this.options.weight / 2;
5131 if (L.Browser.touch) {
5132 w += 10; // polyline click tolerance on touch devices
5135 for (i = 0, len = this._parts.length; i < len; i++) {
5136 part = this._parts[i];
5137 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5138 if (!closed && (j === 0)) {
5142 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5155 L.Polygon.include(!L.Path.CANVAS ? {} : {
5156 _containsPoint: function (p) {
5162 // TODO optimization: check if within bounds first
5164 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5165 // click on polygon border
5169 // ray casting algorithm for detecting if point is in polygon
5171 for (i = 0, len = this._parts.length; i < len; i++) {
5172 part = this._parts[i];
5174 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5178 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5179 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5191 * Circle canvas specific drawing parts.
5194 L.Circle.include(!L.Path.CANVAS ? {} : {
5195 _drawPath: function () {
5196 var p = this._point;
5197 this._ctx.beginPath();
5198 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5201 _containsPoint: function (p) {
5202 var center = this._point,
5203 w2 = this.options.stroke ? this.options.weight / 2 : 0;
5205 return (p.distanceTo(center) <= this._radius + w2);
5210 L.GeoJSON = L.FeatureGroup.extend({
5211 initialize: function (geojson, options) {
5212 L.Util.setOptions(this, options);
5217 this.addData(geojson);
5221 addData: function (geojson) {
5222 var features = geojson instanceof Array ? geojson : geojson.features,
5226 for (i = 0, len = features.length; i < len; i++) {
5227 this.addData(features[i]);
5232 var options = this.options;
5234 if (options.filter && !options.filter(geojson)) { return; }
5236 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer);
5237 layer.feature = geojson;
5239 this.resetStyle(layer);
5241 if (options.onEachFeature) {
5242 options.onEachFeature(geojson, layer);
5245 return this.addLayer(layer);
5248 resetStyle: function (layer) {
5249 var style = this.options.style;
5251 this._setLayerStyle(layer, style);
5255 setStyle: function (style) {
5256 this.eachLayer(function (layer) {
5257 this._setLayerStyle(layer, style);
5261 _setLayerStyle: function (layer, style) {
5262 if (typeof style === 'function') {
5263 style = style(layer.feature);
5265 if (layer.setStyle) {
5266 layer.setStyle(style);
5271 L.Util.extend(L.GeoJSON, {
5272 geometryToLayer: function (geojson, pointToLayer) {
5273 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
5274 coords = geometry.coordinates,
5276 latlng, latlngs, i, len, layer;
5278 switch (geometry.type) {
5280 latlng = this.coordsToLatLng(coords);
5281 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
5284 for (i = 0, len = coords.length; i < len; i++) {
5285 latlng = this.coordsToLatLng(coords[i]);
5286 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
5289 return new L.FeatureGroup(layers);
5292 latlngs = this.coordsToLatLngs(coords);
5293 return new L.Polyline(latlngs);
5296 latlngs = this.coordsToLatLngs(coords, 1);
5297 return new L.Polygon(latlngs);
5299 case 'MultiLineString':
5300 latlngs = this.coordsToLatLngs(coords, 1);
5301 return new L.MultiPolyline(latlngs);
5303 case "MultiPolygon":
5304 latlngs = this.coordsToLatLngs(coords, 2);
5305 return new L.MultiPolygon(latlngs);
5307 case "GeometryCollection":
5308 for (i = 0, len = geometry.geometries.length; i < len; i++) {
5309 layer = this.geometryToLayer(geometry.geometries[i], pointToLayer);
5312 return new L.FeatureGroup(layers);
5315 throw new Error('Invalid GeoJSON object.');
5319 coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng
5320 var lat = parseFloat(coords[reverse ? 0 : 1]),
5321 lng = parseFloat(coords[reverse ? 1 : 0]);
5323 return new L.LatLng(lat, lng, true);
5326 coordsToLatLngs: function (coords, levelsDeep, reverse) { // (Array, Number, Boolean) -> Array
5331 for (i = 0, len = coords.length; i < len; i++) {
5332 latlng = levelsDeep ?
5333 this.coordsToLatLngs(coords[i], levelsDeep - 1, reverse) :
5334 this.coordsToLatLng(coords[i], reverse);
5336 latlngs.push(latlng);
5343 L.geoJson = function (geojson, options) {
5344 return new L.GeoJSON(geojson, options);
5349 * L.DomEvent contains functions for working with DOM events.
5353 /* inpired by John Resig, Dean Edwards and YUI addEvent implementations */
5354 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
5356 var id = L.Util.stamp(fn),
5357 key = '_leaflet_' + type + id,
5358 handler, originalHandler, newType;
5360 if (obj[key]) { return this; }
5362 handler = function (e) {
5363 return fn.call(context || obj, e || L.DomEvent._getEvent());
5366 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
5367 return this.addMsTouchListener(obj, type, handler, id);
5368 } else if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
5369 return this.addDoubleTapListener(obj, handler, id);
5371 } else if ('addEventListener' in obj) {
5373 if (type === 'mousewheel') {
5374 obj.addEventListener('DOMMouseScroll', handler, false);
5375 obj.addEventListener(type, handler, false);
5377 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
5379 originalHandler = handler;
5380 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
5382 handler = function (e) {
5383 if (!L.DomEvent._checkMouse(obj, e)) { return; }
5384 return originalHandler(e);
5387 obj.addEventListener(newType, handler, false);
5390 obj.addEventListener(type, handler, false);
5393 } else if ('attachEvent' in obj) {
5394 obj.attachEvent("on" + type, handler);
5402 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
5404 var id = L.Util.stamp(fn),
5405 key = '_leaflet_' + type + id,
5408 if (!handler) { return; }
5410 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
5411 this.removeMsTouchListener(obj, type, id);
5412 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
5413 this.removeDoubleTapListener(obj, id);
5415 } else if ('removeEventListener' in obj) {
5417 if (type === 'mousewheel') {
5418 obj.removeEventListener('DOMMouseScroll', handler, false);
5419 obj.removeEventListener(type, handler, false);
5421 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
5422 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
5424 obj.removeEventListener(type, handler, false);
5426 } else if ('detachEvent' in obj) {
5427 obj.detachEvent("on" + type, handler);
5435 stopPropagation: function (e) {
5437 if (e.stopPropagation) {
5438 e.stopPropagation();
5440 e.cancelBubble = true;
5445 disableClickPropagation: function (el) {
5447 var stop = L.DomEvent.stopPropagation;
5450 .addListener(el, L.Draggable.START, stop)
5451 .addListener(el, 'click', stop)
5452 .addListener(el, 'dblclick', stop);
5455 preventDefault: function (e) {
5457 if (e.preventDefault) {
5460 e.returnValue = false;
5465 stop: function (e) {
5466 return L.DomEvent.preventDefault(e).stopPropagation(e);
5469 getMousePosition: function (e, container) {
5471 var body = document.body,
5472 docEl = document.documentElement,
5473 x = e.pageX ? e.pageX : e.clientX + body.scrollLeft + docEl.scrollLeft,
5474 y = e.pageY ? e.pageY : e.clientY + body.scrollTop + docEl.scrollTop,
5475 pos = new L.Point(x, y);
5477 return (container ? pos._subtract(L.DomUtil.getViewportOffset(container)) : pos);
5480 getWheelDelta: function (e) {
5485 delta = e.wheelDelta / 120;
5488 delta = -e.detail / 3;
5493 // check if element really left/entered the event target (for mouseenter/mouseleave)
5494 _checkMouse: function (el, e) {
5496 var related = e.relatedTarget;
5498 if (!related) { return true; }
5501 while (related && (related !== el)) {
5502 related = related.parentNode;
5507 return (related !== el);
5510 /*jshint noarg:false */
5511 _getEvent: function () { // evil magic for IE
5513 var e = window.event;
5515 var caller = arguments.callee.caller;
5517 e = caller['arguments'][0];
5518 if (e && window.Event === e.constructor) {
5521 caller = caller.caller;
5526 /*jshint noarg:false */
5529 L.DomEvent.on = L.DomEvent.addListener;
5530 L.DomEvent.off = L.DomEvent.removeListener;
5533 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
5536 L.Draggable = L.Class.extend({
5537 includes: L.Mixin.Events,
5540 START: L.Browser.touch ? 'touchstart' : 'mousedown',
5541 END: L.Browser.touch ? 'touchend' : 'mouseup',
5542 MOVE: L.Browser.touch ? 'touchmove' : 'mousemove',
5546 initialize: function (element, dragStartTarget) {
5547 this._element = element;
5548 this._dragStartTarget = dragStartTarget || element;
5551 enable: function () {
5552 if (this._enabled) {
5555 L.DomEvent.on(this._dragStartTarget, L.Draggable.START, this._onDown, this);
5556 this._enabled = true;
5559 disable: function () {
5560 if (!this._enabled) {
5563 L.DomEvent.off(this._dragStartTarget, L.Draggable.START, this._onDown);
5564 this._enabled = false;
5565 this._moved = false;
5568 _onDown: function (e) {
5569 if ((!L.Browser.touch && e.shiftKey) ||
5570 ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
5572 L.DomEvent.preventDefault(e);
5574 if (L.Draggable._disabled) { return; }
5576 this._simulateClick = true;
5578 if (e.touches && e.touches.length > 1) {
5579 this._simulateClick = false;
5583 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
5586 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
5587 L.DomUtil.addClass(el, 'leaflet-active');
5590 this._moved = false;
5595 this._startPoint = new L.Point(first.clientX, first.clientY);
5596 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
5598 L.DomEvent.on(document, L.Draggable.MOVE, this._onMove, this);
5599 L.DomEvent.on(document, L.Draggable.END, this._onUp, this);
5602 _onMove: function (e) {
5603 if (e.touches && e.touches.length > 1) { return; }
5605 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
5606 newPoint = new L.Point(first.clientX, first.clientY),
5607 diffVec = newPoint.subtract(this._startPoint);
5609 if (!diffVec.x && !diffVec.y) { return; }
5611 L.DomEvent.preventDefault(e);
5614 this.fire('dragstart');
5617 this._startPos = L.DomUtil.getPosition(this._element).subtract(diffVec);
5619 if (!L.Browser.touch) {
5620 L.DomUtil.disableTextSelection();
5621 this._setMovingCursor();
5625 this._newPos = this._startPos.add(diffVec);
5626 this._moving = true;
5628 L.Util.cancelAnimFrame(this._animRequest);
5629 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
5632 _updatePosition: function () {
5633 this.fire('predrag');
5634 L.DomUtil.setPosition(this._element, this._newPos);
5638 _onUp: function (e) {
5639 var simulateClickTouch;
5640 if (this._simulateClick && e.changedTouches) {
5641 var first = e.changedTouches[0],
5643 dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;
5645 if (el.tagName.toLowerCase() === 'a') {
5646 L.DomUtil.removeClass(el, 'leaflet-active');
5649 if (dist < L.Draggable.TAP_TOLERANCE) {
5650 simulateClickTouch = first;
5654 if (!L.Browser.touch) {
5655 L.DomUtil.enableTextSelection();
5656 this._restoreCursor();
5659 L.DomEvent.off(document, L.Draggable.MOVE, this._onMove);
5660 L.DomEvent.off(document, L.Draggable.END, this._onUp);
5663 // ensure drag is not fired after dragend
5664 L.Util.cancelAnimFrame(this._animRequest);
5666 this.fire('dragend');
5668 this._moving = false;
5670 if (simulateClickTouch) {
5671 this._moved = false;
5672 this._simulateEvent('click', simulateClickTouch);
5676 _setMovingCursor: function () {
5677 L.DomUtil.addClass(document.body, 'leaflet-dragging');
5680 _restoreCursor: function () {
5681 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
5684 _simulateEvent: function (type, e) {
5685 var simulatedEvent = document.createEvent('MouseEvents');
5687 simulatedEvent.initMouseEvent(
5688 type, true, true, window, 1,
5689 e.screenX, e.screenY,
5690 e.clientX, e.clientY,
5691 false, false, false, false, 0, null);
5693 e.target.dispatchEvent(simulatedEvent);
5699 * L.Handler classes are used internally to inject interaction features to classes like Map and Marker.
5702 L.Handler = L.Class.extend({
5703 initialize: function (map) {
5707 enable: function () {
5708 if (this._enabled) { return; }
5710 this._enabled = true;
5714 disable: function () {
5715 if (!this._enabled) { return; }
5717 this._enabled = false;
5721 enabled: function () {
5722 return !!this._enabled;
5728 * L.Handler.MapDrag is used internally by L.Map to make the map draggable.
5731 L.Map.mergeOptions({
5734 inertia: !L.Browser.android23,
5735 inertiaDeceleration: 3400, // px/s^2
5736 inertiaMaxSpeed: 6000, // px/s
5737 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
5739 // TODO refactor, move to CRS
5743 L.Map.Drag = L.Handler.extend({
5744 addHooks: function () {
5745 if (!this._draggable) {
5746 this._draggable = new L.Draggable(this._map._mapPane, this._map._container);
5748 this._draggable.on({
5749 'dragstart': this._onDragStart,
5750 'drag': this._onDrag,
5751 'dragend': this._onDragEnd
5754 var options = this._map.options;
5756 if (options.worldCopyJump) {
5757 this._draggable.on('predrag', this._onPreDrag, this);
5758 this._map.on('viewreset', this._onViewReset, this);
5761 this._draggable.enable();
5764 removeHooks: function () {
5765 this._draggable.disable();
5768 moved: function () {
5769 return this._draggable && this._draggable._moved;
5772 _onDragStart: function () {
5773 var map = this._map;
5776 map._panAnim.stop();
5783 if (map.options.inertia) {
5784 this._positions = [];
5789 _onDrag: function () {
5790 if (this._map.options.inertia) {
5791 var time = this._lastTime = +new Date(),
5792 pos = this._lastPos = this._draggable._newPos;
5794 this._positions.push(pos);
5795 this._times.push(time);
5797 if (time - this._times[0] > 200) {
5798 this._positions.shift();
5799 this._times.shift();
5808 _onViewReset: function () {
5809 var pxCenter = this._map.getSize()._divideBy(2),
5810 pxWorldCenter = this._map.latLngToLayerPoint(new L.LatLng(0, 0));
5812 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
5813 this._worldWidth = this._map.project(new L.LatLng(0, 180)).x;
5816 _onPreDrag: function () {
5817 // TODO refactor to be able to adjust map pane position after zoom
5818 var map = this._map,
5819 worldWidth = this._worldWidth,
5820 halfWidth = Math.round(worldWidth / 2),
5821 dx = this._initialWorldOffset,
5822 x = this._draggable._newPos.x,
5823 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
5824 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
5825 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
5827 this._draggable._newPos.x = newX;
5830 _onDragEnd: function () {
5831 var map = this._map,
5832 options = map.options,
5833 delay = +new Date() - this._lastTime,
5835 noInertia = !options.inertia ||
5836 delay > options.inertiaThreshold ||
5837 this._positions[0] === undefined;
5840 map.fire('moveend');
5844 var direction = this._lastPos.subtract(this._positions[0]),
5845 duration = (this._lastTime + delay - this._times[0]) / 1000,
5847 speedVector = direction.multiplyBy(0.58 / duration),
5848 speed = speedVector.distanceTo(new L.Point(0, 0)),
5850 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
5851 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
5853 decelerationDuration = limitedSpeed / options.inertiaDeceleration,
5854 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
5856 L.Util.requestAnimFrame(L.Util.bind(function () {
5857 this._map.panBy(offset, decelerationDuration);
5861 map.fire('dragend');
5863 if (options.maxBounds) {
5864 // TODO predrag validation instead of animation
5865 L.Util.requestAnimFrame(this._panInsideMaxBounds, map, true, map._container);
5869 _panInsideMaxBounds: function () {
5870 this.panInsideBounds(this.options.maxBounds);
5874 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
5878 * L.Handler.DoubleClickZoom is used internally by L.Map to add double-click zooming.
5881 L.Map.mergeOptions({
5882 doubleClickZoom: true
5885 L.Map.DoubleClickZoom = L.Handler.extend({
5886 addHooks: function () {
5887 this._map.on('dblclick', this._onDoubleClick);
5890 removeHooks: function () {
5891 this._map.off('dblclick', this._onDoubleClick);
5894 _onDoubleClick: function (e) {
5895 this.setView(e.latlng, this._zoom + 1);
5899 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
5902 * L.Handler.ScrollWheelZoom is used internally by L.Map to enable mouse scroll wheel zooming on the map.
5905 L.Map.mergeOptions({
5906 scrollWheelZoom: !L.Browser.touch || L.Browser.msTouch
5909 L.Map.ScrollWheelZoom = L.Handler.extend({
5910 addHooks: function () {
5911 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
5915 removeHooks: function () {
5916 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
5919 _onWheelScroll: function (e) {
5920 var delta = L.DomEvent.getWheelDelta(e);
5922 this._delta += delta;
5923 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
5925 if (!this._startTime) {
5926 this._startTime = +new Date();
5929 var left = Math.max(40 - (+new Date() - this._startTime), 0);
5931 clearTimeout(this._timer);
5932 this._timer = setTimeout(L.Util.bind(this._performZoom, this), left);
5934 L.DomEvent.preventDefault(e);
5935 L.DomEvent.stopPropagation(e);
5938 _performZoom: function () {
5939 var map = this._map,
5940 delta = Math.round(this._delta),
5941 zoom = map.getZoom();
5943 delta = Math.max(Math.min(delta, 4), -4);
5944 delta = map._limitZoom(zoom + delta) - zoom;
5948 this._startTime = null;
5950 if (!delta) { return; }
5952 var newZoom = zoom + delta,
5953 newCenter = this._getCenterForScrollWheelZoom(newZoom);
5955 map.setView(newCenter, newZoom);
5958 _getCenterForScrollWheelZoom: function (newZoom) {
5959 var map = this._map,
5960 scale = map.getZoomScale(newZoom),
5961 viewHalf = map.getSize()._divideBy(2),
5962 centerOffset = this._lastMousePos._subtract(viewHalf)._multiplyBy(1 - 1 / scale),
5963 newCenterPoint = map._getTopLeftPoint()._add(viewHalf)._add(centerOffset);
5965 return map.unproject(newCenterPoint);
5969 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
5972 L.Util.extend(L.DomEvent, {
5974 _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
5975 _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
5977 // inspired by Zepto touch code by Thomas Fuchs
5978 addDoubleTapListener: function (obj, handler, id) {
5984 touchstart = this._touchstart,
5985 touchend = this._touchend,
5986 trackedTouches = [];
5988 function onTouchStart(e) {
5990 if (L.Browser.msTouch) {
5991 trackedTouches.push(e.pointerId);
5992 count = trackedTouches.length;
5994 count = e.touches.length;
6000 var now = Date.now(),
6001 delta = now - (last || now);
6003 touch = e.touches ? e.touches[0] : e;
6004 doubleTap = (delta > 0 && delta <= delay);
6007 function onTouchEnd(e) {
6008 if (L.Browser.msTouch) {
6009 var idx = trackedTouches.indexOf(e.pointerId);
6013 trackedTouches.splice(idx, 1);
6017 if (L.Browser.msTouch) {
6018 //Work around .type being readonly with MSPointer* events
6021 for (var i in touch) {
6022 if (true) { //Make JSHint happy, we want to copy all properties
6024 if (typeof prop === 'function') {
6025 newTouch[i] = prop.bind(touch);
6033 touch.type = 'dblclick';
6038 obj[pre + touchstart + id] = onTouchStart;
6039 obj[pre + touchend + id] = onTouchEnd;
6041 //On msTouch we need to listen on the document otherwise a drag starting on the map and moving off screen will not come through to us
6042 // so we will lose track of how many touches are ongoing
6043 var endElement = L.Browser.msTouch ? document.documentElement : obj;
6045 obj.addEventListener(touchstart, onTouchStart, false);
6046 endElement.addEventListener(touchend, onTouchEnd, false);
6047 if (L.Browser.msTouch) {
6048 endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
6053 removeDoubleTapListener: function (obj, id) {
6054 var pre = '_leaflet_';
6055 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
6056 (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(this._touchend, obj[pre + this._touchend + id], false);
6057 if (L.Browser.msTouch) {
6058 document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
6065 L.Util.extend(L.DomEvent, {
6068 _msDocumentListener: false,
6070 // Provides a touch events wrapper for msPointer events.
6071 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
6073 addMsTouchListener: function (obj, type, handler, id) {
6077 return this.addMsTouchListenerStart(obj, type, handler, id);
6079 return this.addMsTouchListenerEnd(obj, type, handler, id);
6081 return this.addMsTouchListenerMove(obj, type, handler, id);
6083 throw 'Unknown touch event type';
6087 addMsTouchListenerStart: function (obj, type, handler, id) {
6088 var pre = '_leaflet_',
6089 touches = this._msTouches;
6091 var cb = function (e) {
6093 var alreadyInArray = false;
6094 for (var i = 0; i < touches.length; i++) {
6095 if (touches[i].pointerId === e.pointerId) {
6096 alreadyInArray = true;
6100 if (!alreadyInArray) {
6104 e.touches = touches.slice();
6105 e.changedTouches = [e];
6110 obj[pre + 'touchstart' + id] = cb;
6111 obj.addEventListener('MSPointerDown', cb, false);
6113 //Need to also listen for end events to keep the _msTouches list accurate
6114 //this needs to be on the body and never go away
6115 if (!this._msDocumentListener) {
6116 var internalCb = function (e) {
6117 for (var i = 0; i < touches.length; i++) {
6118 if (touches[i].pointerId === e.pointerId) {
6119 touches.splice(i, 1);
6124 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
6125 document.documentElement.addEventListener('MSPointerUp', internalCb, false);
6126 document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
6128 this._msDocumentListener = true;
6134 addMsTouchListenerMove: function (obj, type, handler, id) {
6135 var pre = '_leaflet_';
6137 var touches = this._msTouches;
6138 var cb = function (e) {
6140 //Don't fire touch moves when mouse isn't down
6141 if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) {
6145 for (var i = 0; i < touches.length; i++) {
6146 if (touches[i].pointerId === e.pointerId) {
6152 e.touches = touches.slice();
6153 e.changedTouches = [e];
6158 obj[pre + 'touchmove' + id] = cb;
6159 obj.addEventListener('MSPointerMove', cb, false);
6164 addMsTouchListenerEnd: function (obj, type, handler, id) {
6165 var pre = '_leaflet_',
6166 touches = this._msTouches;
6168 var cb = function (e) {
6169 for (var i = 0; i < touches.length; i++) {
6170 if (touches[i].pointerId === e.pointerId) {
6171 touches.splice(i, 1);
6176 e.touches = touches.slice();
6177 e.changedTouches = [e];
6182 obj[pre + 'touchend' + id] = cb;
6183 obj.addEventListener('MSPointerUp', cb, false);
6184 obj.addEventListener('MSPointerCancel', cb, false);
6189 removeMsTouchListener: function (obj, type, id) {
6190 var pre = '_leaflet_',
6191 cb = obj[pre + type + id];
6195 obj.removeEventListener('MSPointerDown', cb, false);
6198 obj.removeEventListener('MSPointerMove', cb, false);
6201 obj.removeEventListener('MSPointerUp', cb, false);
6202 obj.removeEventListener('MSPointerCancel', cb, false);
6212 * L.Handler.TouchZoom is used internally by L.Map to add touch-zooming on Webkit-powered mobile browsers.
6215 L.Map.mergeOptions({
6216 touchZoom: L.Browser.touch && !L.Browser.android23
6219 L.Map.TouchZoom = L.Handler.extend({
6220 addHooks: function () {
6221 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
6224 removeHooks: function () {
6225 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
6228 _onTouchStart: function (e) {
6229 var map = this._map;
6231 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
6233 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
6234 p2 = map.mouseEventToLayerPoint(e.touches[1]),
6235 viewCenter = map._getCenterLayerPoint();
6237 this._startCenter = p1.add(p2)._divideBy(2);
6238 this._startDist = p1.distanceTo(p2);
6240 this._moved = false;
6241 this._zooming = true;
6243 this._centerOffset = viewCenter.subtract(this._startCenter);
6246 map._panAnim.stop();
6250 .on(document, 'touchmove', this._onTouchMove, this)
6251 .on(document, 'touchend', this._onTouchEnd, this);
6253 L.DomEvent.preventDefault(e);
6256 _onTouchMove: function (e) {
6257 if (!e.touches || e.touches.length !== 2) { return; }
6259 var map = this._map;
6261 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
6262 p2 = map.mouseEventToLayerPoint(e.touches[1]);
6264 this._scale = p1.distanceTo(p2) / this._startDist;
6265 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
6267 if (this._scale === 1) { return; }
6270 L.DomUtil.addClass(map._mapPane, 'leaflet-zoom-anim leaflet-touching');
6280 L.Util.cancelAnimFrame(this._animRequest);
6281 this._animRequest = L.Util.requestAnimFrame(this._updateOnMove, this, true, this._map._container);
6283 L.DomEvent.preventDefault(e);
6286 _updateOnMove: function () {
6287 var map = this._map,
6288 origin = this._getScaleOrigin(),
6289 center = map.layerPointToLatLng(origin);
6291 map.fire('zoomanim', {
6293 zoom: map.getScaleZoom(this._scale)
6296 // Used 2 translates instead of transform-origin because of a very strange bug -
6297 // it didn't count the origin on the first touch-zoom but worked correctly afterwards
6299 map._tileBg.style[L.DomUtil.TRANSFORM] =
6300 L.DomUtil.getTranslateString(this._delta) + ' ' +
6301 L.DomUtil.getScaleString(this._scale, this._startCenter);
6304 _onTouchEnd: function (e) {
6305 if (!this._moved || !this._zooming) { return; }
6307 var map = this._map;
6309 this._zooming = false;
6310 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
6313 .off(document, 'touchmove', this._onTouchMove)
6314 .off(document, 'touchend', this._onTouchEnd);
6316 var origin = this._getScaleOrigin(),
6317 center = map.layerPointToLatLng(origin),
6319 oldZoom = map.getZoom(),
6320 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
6321 roundZoomDelta = (floatZoomDelta > 0 ? Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
6322 zoom = map._limitZoom(oldZoom + roundZoomDelta);
6324 map.fire('zoomanim', {
6329 map._runAnimation(center, zoom, map.getZoomScale(zoom) / this._scale, origin, true);
6332 _getScaleOrigin: function () {
6333 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
6334 return this._startCenter.add(centerOffset);
6338 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
6342 * L.Handler.ShiftDragZoom is used internally by L.Map to add shift-drag zoom (zoom to a selected bounding box).
6345 L.Map.mergeOptions({
6349 L.Map.BoxZoom = L.Handler.extend({
6350 initialize: function (map) {
6352 this._container = map._container;
6353 this._pane = map._panes.overlayPane;
6356 addHooks: function () {
6357 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
6360 removeHooks: function () {
6361 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
6364 _onMouseDown: function (e) {
6365 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
6367 L.DomUtil.disableTextSelection();
6369 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
6371 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
6372 L.DomUtil.setPosition(this._box, this._startLayerPoint);
6374 //TODO refactor: move cursor to styles
6375 this._container.style.cursor = 'crosshair';
6378 .on(document, 'mousemove', this._onMouseMove, this)
6379 .on(document, 'mouseup', this._onMouseUp, this)
6382 this._map.fire("boxzoomstart");
6385 _onMouseMove: function (e) {
6386 var startPoint = this._startLayerPoint,
6389 layerPoint = this._map.mouseEventToLayerPoint(e),
6390 offset = layerPoint.subtract(startPoint),
6392 newPos = new L.Point(
6393 Math.min(layerPoint.x, startPoint.x),
6394 Math.min(layerPoint.y, startPoint.y));
6396 L.DomUtil.setPosition(box, newPos);
6398 // TODO refactor: remove hardcoded 4 pixels
6399 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
6400 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
6403 _onMouseUp: function (e) {
6404 this._pane.removeChild(this._box);
6405 this._container.style.cursor = '';
6407 L.DomUtil.enableTextSelection();
6410 .off(document, 'mousemove', this._onMouseMove)
6411 .off(document, 'mouseup', this._onMouseUp);
6413 var map = this._map,
6414 layerPoint = map.mouseEventToLayerPoint(e);
6416 var bounds = new L.LatLngBounds(
6417 map.layerPointToLatLng(this._startLayerPoint),
6418 map.layerPointToLatLng(layerPoint));
6420 map.fitBounds(bounds);
6422 map.fire("boxzoomend", {
6423 boxZoomBounds: bounds
6428 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
6431 L.Map.mergeOptions({
6433 keyboardPanOffset: 80,
6434 keyboardZoomOffset: 1
6437 L.Map.Keyboard = L.Handler.extend({
6439 // list of e.keyCode values for particular actions
6445 zoomIn: [187, 107, 61],
6449 initialize: function (map) {
6452 this._setPanOffset(map.options.keyboardPanOffset);
6453 this._setZoomOffset(map.options.keyboardZoomOffset);
6456 addHooks: function () {
6457 var container = this._map._container;
6459 // make the container focusable by tabbing
6460 if (container.tabIndex === -1) {
6461 container.tabIndex = "0";
6465 .addListener(container, 'focus', this._onFocus, this)
6466 .addListener(container, 'blur', this._onBlur, this)
6467 .addListener(container, 'mousedown', this._onMouseDown, this);
6470 .on('focus', this._addHooks, this)
6471 .on('blur', this._removeHooks, this);
6474 removeHooks: function () {
6475 this._removeHooks();
6477 var container = this._map._container;
6479 .removeListener(container, 'focus', this._onFocus, this)
6480 .removeListener(container, 'blur', this._onBlur, this)
6481 .removeListener(container, 'mousedown', this._onMouseDown, this);
6484 .off('focus', this._addHooks, this)
6485 .off('blur', this._removeHooks, this);
6488 _onMouseDown: function () {
6489 if (!this._focused) {
6490 this._map._container.focus();
6494 _onFocus: function () {
6495 this._focused = true;
6496 this._map.fire('focus');
6499 _onBlur: function () {
6500 this._focused = false;
6501 this._map.fire('blur');
6504 _setPanOffset: function (pan) {
6505 var keys = this._panKeys = {},
6506 codes = this.keyCodes,
6509 for (i = 0, len = codes.left.length; i < len; i++) {
6510 keys[codes.left[i]] = [-1 * pan, 0];
6512 for (i = 0, len = codes.right.length; i < len; i++) {
6513 keys[codes.right[i]] = [pan, 0];
6515 for (i = 0, len = codes.down.length; i < len; i++) {
6516 keys[codes.down[i]] = [0, pan];
6518 for (i = 0, len = codes.up.length; i < len; i++) {
6519 keys[codes.up[i]] = [0, -1 * pan];
6523 _setZoomOffset: function (zoom) {
6524 var keys = this._zoomKeys = {},
6525 codes = this.keyCodes,
6528 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
6529 keys[codes.zoomIn[i]] = zoom;
6531 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
6532 keys[codes.zoomOut[i]] = -zoom;
6536 _addHooks: function () {
6537 L.DomEvent.addListener(document, 'keydown', this._onKeyDown, this);
6540 _removeHooks: function () {
6541 L.DomEvent.removeListener(document, 'keydown', this._onKeyDown, this);
6544 _onKeyDown: function (e) {
6545 var key = e.keyCode;
6547 if (this._panKeys.hasOwnProperty(key)) {
6548 this._map.panBy(this._panKeys[key]);
6550 } else if (this._zoomKeys.hasOwnProperty(key)) {
6551 this._map.setZoom(this._map.getZoom() + this._zoomKeys[key]);
6561 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
6565 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
6568 L.Handler.MarkerDrag = L.Handler.extend({
6569 initialize: function (marker) {
6570 this._marker = marker;
6573 addHooks: function () {
6574 var icon = this._marker._icon;
6575 if (!this._draggable) {
6576 this._draggable = new L.Draggable(icon, icon)
6577 .on('dragstart', this._onDragStart, this)
6578 .on('drag', this._onDrag, this)
6579 .on('dragend', this._onDragEnd, this);
6581 this._draggable.enable();
6584 removeHooks: function () {
6585 this._draggable.disable();
6588 moved: function () {
6589 return this._draggable && this._draggable._moved;
6592 _onDragStart: function (e) {
6599 _onDrag: function (e) {
6600 var marker = this._marker,
6601 shadow = marker._shadow,
6602 iconPos = L.DomUtil.getPosition(marker._icon),
6603 latlng = marker._map.layerPointToLatLng(iconPos);
6605 // update shadow position
6607 L.DomUtil.setPosition(shadow, iconPos);
6610 marker._latlng = latlng;
6613 .fire('move', { latlng: latlng })
6617 _onDragEnd: function () {
6625 L.Handler.PolyEdit = L.Handler.extend({
6627 icon: new L.DivIcon({
6628 iconSize: new L.Point(8, 8),
6629 className: 'leaflet-div-icon leaflet-editing-icon'
6633 initialize: function (poly, options) {
6635 L.Util.setOptions(this, options);
6638 addHooks: function () {
6639 if (this._poly._map) {
6640 if (!this._markerGroup) {
6641 this._initMarkers();
6643 this._poly._map.addLayer(this._markerGroup);
6647 removeHooks: function () {
6648 if (this._poly._map) {
6649 this._poly._map.removeLayer(this._markerGroup);
6650 delete this._markerGroup;
6651 delete this._markers;
6655 updateMarkers: function () {
6656 this._markerGroup.clearLayers();
6657 this._initMarkers();
6660 _initMarkers: function () {
6661 if (!this._markerGroup) {
6662 this._markerGroup = new L.LayerGroup();
6666 var latlngs = this._poly._latlngs,
6669 // TODO refactor holes implementation in Polygon to support it here
6671 for (i = 0, len = latlngs.length; i < len; i++) {
6673 marker = this._createMarker(latlngs[i], i);
6674 marker.on('click', this._onMarkerClick, this);
6675 this._markers.push(marker);
6678 var markerLeft, markerRight;
6680 for (i = 0, j = len - 1; i < len; j = i++) {
6681 if (i === 0 && !(L.Polygon && (this._poly instanceof L.Polygon))) {
6685 markerLeft = this._markers[j];
6686 markerRight = this._markers[i];
6688 this._createMiddleMarker(markerLeft, markerRight);
6689 this._updatePrevNext(markerLeft, markerRight);
6693 _createMarker: function (latlng, index) {
6694 var marker = new L.Marker(latlng, {
6696 icon: this.options.icon
6699 marker._origLatLng = latlng;
6700 marker._index = index;
6702 marker.on('drag', this._onMarkerDrag, this);
6703 marker.on('dragend', this._fireEdit, this);
6705 this._markerGroup.addLayer(marker);
6710 _fireEdit: function () {
6711 this._poly.fire('edit');
6714 _onMarkerDrag: function (e) {
6715 var marker = e.target;
6717 L.Util.extend(marker._origLatLng, marker._latlng);
6719 if (marker._middleLeft) {
6720 marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
6722 if (marker._middleRight) {
6723 marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
6726 this._poly.redraw();
6729 _onMarkerClick: function (e) {
6730 // 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
6731 if (this._poly._latlngs.length < 3) {
6735 var marker = e.target,
6738 // Check existence of previous and next markers since they wouldn't exist for edge points on the polyline
6739 if (marker._prev && marker._next) {
6740 this._createMiddleMarker(marker._prev, marker._next);
6741 } else if (!marker._prev) {
6742 marker._next._middleLeft = null;
6743 } else if (!marker._next) {
6744 marker._prev._middleRight = null;
6746 this._updatePrevNext(marker._prev, marker._next);
6748 // The marker itself is guaranteed to exist and present in the layer, since we managed to click on it
6749 this._markerGroup.removeLayer(marker);
6750 // Check for the existence of middle left or middle right
6751 if (marker._middleLeft) {
6752 this._markerGroup.removeLayer(marker._middleLeft);
6754 if (marker._middleRight) {
6755 this._markerGroup.removeLayer(marker._middleRight);
6757 this._markers.splice(i, 1);
6758 this._poly.spliceLatLngs(i, 1);
6759 this._updateIndexes(i, -1);
6760 this._poly.fire('edit');
6763 _updateIndexes: function (index, delta) {
6764 this._markerGroup.eachLayer(function (marker) {
6765 if (marker._index > index) {
6766 marker._index += delta;
6771 _createMiddleMarker: function (marker1, marker2) {
6772 var latlng = this._getMiddleLatLng(marker1, marker2),
6773 marker = this._createMarker(latlng),
6778 marker.setOpacity(0.6);
6780 marker1._middleRight = marker2._middleLeft = marker;
6782 onDragStart = function () {
6783 var i = marker2._index;
6788 .off('click', onClick)
6789 .on('click', this._onMarkerClick, this);
6791 latlng.lat = marker.getLatLng().lat;
6792 latlng.lng = marker.getLatLng().lng;
6793 this._poly.spliceLatLngs(i, 0, latlng);
6794 this._markers.splice(i, 0, marker);
6796 marker.setOpacity(1);
6798 this._updateIndexes(i, 1);
6800 this._updatePrevNext(marker1, marker);
6801 this._updatePrevNext(marker, marker2);
6804 onDragEnd = function () {
6805 marker.off('dragstart', onDragStart, this);
6806 marker.off('dragend', onDragEnd, this);
6808 this._createMiddleMarker(marker1, marker);
6809 this._createMiddleMarker(marker, marker2);
6812 onClick = function () {
6813 onDragStart.call(this);
6814 onDragEnd.call(this);
6815 this._poly.fire('edit');
6819 .on('click', onClick, this)
6820 .on('dragstart', onDragStart, this)
6821 .on('dragend', onDragEnd, this);
6823 this._markerGroup.addLayer(marker);
6826 _updatePrevNext: function (marker1, marker2) {
6828 marker1._next = marker2;
6831 marker2._prev = marker1;
6835 _getMiddleLatLng: function (marker1, marker2) {
6836 var map = this._poly._map,
6837 p1 = map.latLngToLayerPoint(marker1.getLatLng()),
6838 p2 = map.latLngToLayerPoint(marker2.getLatLng());
6840 return map.layerPointToLatLng(p1._add(p2)._divideBy(2));
6846 L.Control = L.Class.extend({
6848 position: 'topright'
6851 initialize: function (options) {
6852 L.Util.setOptions(this, options);
6855 getPosition: function () {
6856 return this.options.position;
6859 setPosition: function (position) {
6860 var map = this._map;
6863 map.removeControl(this);
6866 this.options.position = position;
6869 map.addControl(this);
6875 addTo: function (map) {
6878 var container = this._container = this.onAdd(map),
6879 pos = this.getPosition(),
6880 corner = map._controlCorners[pos];
6882 L.DomUtil.addClass(container, 'leaflet-control');
6884 if (pos.indexOf('bottom') !== -1) {
6885 corner.insertBefore(container, corner.firstChild);
6887 corner.appendChild(container);
6893 removeFrom: function (map) {
6894 var pos = this.getPosition(),
6895 corner = map._controlCorners[pos];
6897 corner.removeChild(this._container);
6900 if (this.onRemove) {
6908 L.control = function (options) {
6909 return new L.Control(options);
6914 addControl: function (control) {
6915 control.addTo(this);
6919 removeControl: function (control) {
6920 control.removeFrom(this);
6924 _initControlPos: function () {
6925 var corners = this._controlCorners = {},
6927 container = this._controlContainer =
6928 L.DomUtil.create('div', l + 'control-container', this._container);
6930 function createCorner(vSide, hSide) {
6931 var className = l + vSide + ' ' + l + hSide;
6933 corners[vSide + hSide] =
6934 L.DomUtil.create('div', className, container);
6937 createCorner('top', 'left');
6938 createCorner('top', 'right');
6939 createCorner('bottom', 'left');
6940 createCorner('bottom', 'right');
6945 L.Control.Zoom = L.Control.extend({
6950 onAdd: function (map) {
6951 var className = 'leaflet-control-zoom',
6952 container = L.DomUtil.create('div', className);
6956 this._createButton('Zoom in', className + '-in', container, this._zoomIn, this);
6957 this._createButton('Zoom out', className + '-out', container, this._zoomOut, this);
6962 _zoomIn: function (e) {
6963 this._map.zoomIn(e.shiftKey ? 3 : 1);
6966 _zoomOut: function (e) {
6967 this._map.zoomOut(e.shiftKey ? 3 : 1);
6970 _createButton: function (title, className, container, fn, context) {
6971 var link = L.DomUtil.create('a', className, container);
6976 .on(link, 'click', L.DomEvent.stopPropagation)
6977 .on(link, 'mousedown', L.DomEvent.stopPropagation)
6978 .on(link, 'dblclick', L.DomEvent.stopPropagation)
6979 .on(link, 'click', L.DomEvent.preventDefault)
6980 .on(link, 'click', fn, context);
6986 L.Map.mergeOptions({
6990 L.Map.addInitHook(function () {
6991 if (this.options.zoomControl) {
6992 this.zoomControl = new L.Control.Zoom();
6993 this.addControl(this.zoomControl);
6997 L.control.zoom = function (options) {
6998 return new L.Control.Zoom(options);
7003 L.Control.Attribution = L.Control.extend({
7005 position: 'bottomright',
7006 prefix: 'Powered by <a href="http://leaflet.cloudmade.com">Leaflet</a>'
7009 initialize: function (options) {
7010 L.Util.setOptions(this, options);
7012 this._attributions = {};
7015 onAdd: function (map) {
7016 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
7017 L.DomEvent.disableClickPropagation(this._container);
7020 .on('layeradd', this._onLayerAdd, this)
7021 .on('layerremove', this._onLayerRemove, this);
7025 return this._container;
7028 onRemove: function (map) {
7030 .off('layeradd', this._onLayerAdd)
7031 .off('layerremove', this._onLayerRemove);
7035 setPrefix: function (prefix) {
7036 this.options.prefix = prefix;
7041 addAttribution: function (text) {
7042 if (!text) { return; }
7044 if (!this._attributions[text]) {
7045 this._attributions[text] = 0;
7047 this._attributions[text]++;
7054 removeAttribution: function (text) {
7055 if (!text) { return; }
7057 this._attributions[text]--;
7063 _update: function () {
7064 if (!this._map) { return; }
7068 for (var i in this._attributions) {
7069 if (this._attributions.hasOwnProperty(i) && this._attributions[i]) {
7074 var prefixAndAttribs = [];
7076 if (this.options.prefix) {
7077 prefixAndAttribs.push(this.options.prefix);
7079 if (attribs.length) {
7080 prefixAndAttribs.push(attribs.join(', '));
7083 this._container.innerHTML = prefixAndAttribs.join(' — ');
7086 _onLayerAdd: function (e) {
7087 if (e.layer.getAttribution) {
7088 this.addAttribution(e.layer.getAttribution());
7092 _onLayerRemove: function (e) {
7093 if (e.layer.getAttribution) {
7094 this.removeAttribution(e.layer.getAttribution());
7099 L.Map.mergeOptions({
7100 attributionControl: true
7103 L.Map.addInitHook(function () {
7104 if (this.options.attributionControl) {
7105 this.attributionControl = (new L.Control.Attribution()).addTo(this);
7109 L.control.attribution = function (options) {
7110 return new L.Control.Attribution(options);
7114 L.Control.Scale = L.Control.extend({
7116 position: 'bottomleft',
7120 updateWhenIdle: false
7123 onAdd: function (map) {
7126 var className = 'leaflet-control-scale',
7127 container = L.DomUtil.create('div', className),
7128 options = this.options;
7130 this._addScales(options, className, container);
7132 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
7133 map.whenReady(this._update, this);
7138 onRemove: function (map) {
7139 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
7142 _addScales: function (options, className, container) {
7143 if (options.metric) {
7144 this._mScale = L.DomUtil.create('div', className + '-line', container);
7146 if (options.imperial) {
7147 this._iScale = L.DomUtil.create('div', className + '-line', container);
7151 _update: function () {
7152 var bounds = this._map.getBounds(),
7153 centerLat = bounds.getCenter().lat,
7154 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
7155 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
7157 size = this._map.getSize(),
7158 options = this.options,
7162 maxMeters = dist * (options.maxWidth / size.x);
7165 this._updateScales(options, maxMeters);
7168 _updateScales: function (options, maxMeters) {
7169 if (options.metric && maxMeters) {
7170 this._updateMetric(maxMeters);
7173 if (options.imperial && maxMeters) {
7174 this._updateImperial(maxMeters);
7178 _updateMetric: function (maxMeters) {
7179 var meters = this._getRoundNum(maxMeters);
7181 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
7182 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
7185 _updateImperial: function (maxMeters) {
7186 var maxFeet = maxMeters * 3.2808399,
7187 scale = this._iScale,
7188 maxMiles, miles, feet;
7190 if (maxFeet > 5280) {
7191 maxMiles = maxFeet / 5280;
7192 miles = this._getRoundNum(maxMiles);
7194 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
7195 scale.innerHTML = miles + ' mi';
7198 feet = this._getRoundNum(maxFeet);
7200 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
7201 scale.innerHTML = feet + ' ft';
7205 _getScaleWidth: function (ratio) {
7206 return Math.round(this.options.maxWidth * ratio) - 10;
7209 _getRoundNum: function (num) {
7210 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
7213 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
7219 L.control.scale = function (options) {
7220 return new L.Control.Scale(options);
7224 L.Control.Layers = L.Control.extend({
7227 position: 'topright',
7231 initialize: function (baseLayers, overlays, options) {
7232 L.Util.setOptions(this, options);
7235 this._lastZIndex = 0;
7237 for (var i in baseLayers) {
7238 if (baseLayers.hasOwnProperty(i)) {
7239 this._addLayer(baseLayers[i], i);
7243 for (i in overlays) {
7244 if (overlays.hasOwnProperty(i)) {
7245 this._addLayer(overlays[i], i, true);
7250 onAdd: function (map) {
7254 return this._container;
7257 addBaseLayer: function (layer, name) {
7258 this._addLayer(layer, name);
7263 addOverlay: function (layer, name) {
7264 this._addLayer(layer, name, true);
7269 removeLayer: function (layer) {
7270 var id = L.Util.stamp(layer);
7271 delete this._layers[id];
7276 _initLayout: function () {
7277 var className = 'leaflet-control-layers',
7278 container = this._container = L.DomUtil.create('div', className);
7280 if (!L.Browser.touch) {
7281 L.DomEvent.disableClickPropagation(container);
7283 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
7286 var form = this._form = L.DomUtil.create('form', className + '-list');
7288 if (this.options.collapsed) {
7290 .on(container, 'mouseover', this._expand, this)
7291 .on(container, 'mouseout', this._collapse, this);
7293 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
7295 link.title = 'Layers';
7297 if (L.Browser.touch) {
7299 .on(link, 'click', L.DomEvent.stopPropagation)
7300 .on(link, 'click', L.DomEvent.preventDefault)
7301 .on(link, 'click', this._expand, this);
7304 L.DomEvent.on(link, 'focus', this._expand, this);
7307 this._map.on('movestart', this._collapse, this);
7308 // TODO keyboard accessibility
7313 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
7314 this._separator = L.DomUtil.create('div', className + '-separator', form);
7315 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
7317 container.appendChild(form);
7320 _addLayer: function (layer, name, overlay) {
7321 var id = L.Util.stamp(layer);
7323 this._layers[id] = {
7329 if (this.options.autoZIndex && layer.setZIndex) {
7331 layer.setZIndex(this._lastZIndex);
7335 _update: function () {
7336 if (!this._container) {
7340 this._baseLayersList.innerHTML = '';
7341 this._overlaysList.innerHTML = '';
7343 var baseLayersPresent = false,
7344 overlaysPresent = false;
7346 for (var i in this._layers) {
7347 if (this._layers.hasOwnProperty(i)) {
7348 var obj = this._layers[i];
7350 overlaysPresent = overlaysPresent || obj.overlay;
7351 baseLayersPresent = baseLayersPresent || !obj.overlay;
7355 this._separator.style.display = (overlaysPresent && baseLayersPresent ? '' : 'none');
7358 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
7359 _createRadioElement: function (name, checked) {
7361 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
7363 radioHtml += ' checked="checked"';
7367 var radioFragment = document.createElement('div');
7368 radioFragment.innerHTML = radioHtml;
7370 return radioFragment.firstChild;
7373 _addItem: function (obj) {
7374 var label = document.createElement('label'),
7376 checked = this._map.hasLayer(obj.layer);
7379 input = document.createElement('input');
7380 input.type = 'checkbox';
7381 input.className = 'leaflet-control-layers-selector';
7382 input.defaultChecked = checked;
7384 input = this._createRadioElement('leaflet-base-layers', checked);
7387 input.layerId = L.Util.stamp(obj.layer);
7389 L.DomEvent.on(input, 'click', this._onInputClick, this);
7391 var name = document.createElement('span');
7392 name.innerHTML = ' ' + obj.name;
7394 label.appendChild(input);
7395 label.appendChild(name);
7397 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
7398 container.appendChild(label);
7401 _onInputClick: function () {
7403 inputs = this._form.getElementsByTagName('input'),
7404 inputsLen = inputs.length,
7407 for (i = 0; i < inputsLen; i++) {
7409 obj = this._layers[input.layerId];
7411 if (input.checked && !this._map.hasLayer(obj.layer)) {
7412 this._map.addLayer(obj.layer);
7414 baseLayer = obj.layer;
7416 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
7417 this._map.removeLayer(obj.layer);
7422 this._map.fire('baselayerchange', {layer: baseLayer});
7426 _expand: function () {
7427 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
7430 _collapse: function () {
7431 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
7435 L.control.layers = function (baseLayers, overlays, options) {
7436 return new L.Control.Layers(baseLayers, overlays, options);
7441 * L.PosAnimation is used by Leaflet internally for pan animations.
7444 L.PosAnimation = L.Class.extend({
7445 includes: L.Mixin.Events,
7447 run: function (el, newPos, duration, easing) { // (HTMLElement, Point[, Number, String])
7451 this._inProgress = true;
7455 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) + 's ' + (easing || 'ease-out');
7457 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7458 L.DomUtil.setPosition(el, newPos);
7460 // toggle reflow, Chrome flickers for some reason if you don't do this
7461 L.Util.falseFn(el.offsetWidth);
7463 // there's no native way to track value updates of tranisitioned properties, so we imitate this
7464 this._stepTimer = setInterval(L.Util.bind(this.fire, this, 'step'), 50);
7468 if (!this._inProgress) { return; }
7470 // if we just removed the transition property, the element would jump to its final position,
7471 // so we need to make it stay at the current position
7473 L.DomUtil.setPosition(this._el, this._getPos());
7474 this._onTransitionEnd();
7477 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
7478 // we need to parse computed style (in case of transform it returns matrix string)
7480 _transformRe: /(-?[\d\.]+), (-?[\d\.]+)\)/,
7482 _getPos: function () {
7483 var left, top, matches,
7485 style = window.getComputedStyle(el);
7487 if (L.Browser.any3d) {
7488 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
7489 left = parseFloat(matches[1]);
7490 top = parseFloat(matches[2]);
7492 left = parseFloat(style.left);
7493 top = parseFloat(style.top);
7496 return new L.Point(left, top, true);
7499 _onTransitionEnd: function () {
7500 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7502 if (!this._inProgress) { return; }
7503 this._inProgress = false;
7505 this._el.style[L.DomUtil.TRANSITION] = '';
7507 clearInterval(this._stepTimer);
7509 this.fire('step').fire('end');
7518 setView: function (center, zoom, forceReset) {
7519 zoom = this._limitZoom(zoom);
7521 var zoomChanged = (this._zoom !== zoom);
7523 if (this._loaded && !forceReset && this._layers) {
7525 if (this._panAnim) {
7526 this._panAnim.stop();
7529 var done = (zoomChanged ?
7530 this._zoomToIfClose && this._zoomToIfClose(center, zoom) :
7531 this._panByIfClose(center));
7533 // exit if animated pan or zoom started
7535 clearTimeout(this._sizeTimer);
7540 // reset the map view
7541 this._resetView(center, zoom);
7546 panBy: function (offset, duration) {
7547 offset = L.point(offset);
7549 if (!(offset.x || offset.y)) {
7553 if (!this._panAnim) {
7554 this._panAnim = new L.PosAnimation();
7557 'step': this._onPanTransitionStep,
7558 'end': this._onPanTransitionEnd
7562 this.fire('movestart');
7564 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
7566 var newPos = L.DomUtil.getPosition(this._mapPane).subtract(offset);
7567 this._panAnim.run(this._mapPane, newPos, duration || 0.25);
7572 _onPanTransitionStep: function () {
7576 _onPanTransitionEnd: function () {
7577 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
7578 this.fire('moveend');
7581 _panByIfClose: function (center) {
7582 // difference between the new and current centers in pixels
7583 var offset = this._getCenterOffset(center)._floor();
7585 if (this._offsetIsWithinView(offset)) {
7592 _offsetIsWithinView: function (offset, multiplyFactor) {
7593 var m = multiplyFactor || 1,
7594 size = this.getSize();
7596 return (Math.abs(offset.x) <= size.x * m) &&
7597 (Math.abs(offset.y) <= size.y * m);
7603 * L.PosAnimation fallback implementation that powers Leaflet pan animations
7604 * in browsers that don't support CSS3 Transitions.
7607 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
7609 run: function (el, newPos, duration, easing) { // (HTMLElement, Point[, Number, String])
7613 this._inProgress = true;
7614 this._duration = duration || 0.25;
7615 this._ease = this._easings[easing || 'ease-out'];
7617 this._startPos = L.DomUtil.getPosition(el);
7618 this._offset = newPos.subtract(this._startPos);
7619 this._startTime = +new Date();
7627 if (!this._inProgress) { return; }
7633 _animate: function () {
7635 this._animId = L.Util.requestAnimFrame(this._animate, this);
7639 _step: function () {
7640 var elapsed = (+new Date()) - this._startTime,
7641 duration = this._duration * 1000;
7643 if (elapsed < duration) {
7644 this._runFrame(this._ease(elapsed / duration));
7651 _runFrame: function (progress) {
7652 var pos = this._startPos.add(this._offset.multiplyBy(progress));
7653 L.DomUtil.setPosition(this._el, pos);
7658 _complete: function () {
7659 L.Util.cancelAnimFrame(this._animId);
7661 this._inProgress = false;
7665 // easing functions, they map time progress to movement progress
7667 'ease-out': function (t) { return t * (2 - t); },
7668 'linear': function (t) { return t; }
7674 L.Map.mergeOptions({
7675 zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera
7678 if (L.DomUtil.TRANSITION) {
7679 L.Map.addInitHook(function () {
7680 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
7684 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
7686 _zoomToIfClose: function (center, zoom) {
7688 if (this._animatingZoom) { return true; }
7690 if (!this.options.zoomAnimation) { return false; }
7692 var scale = this.getZoomScale(zoom),
7693 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
7695 // if offset does not exceed half of the view
7696 if (!this._offsetIsWithinView(offset, 1)) { return false; }
7698 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
7704 this.fire('zoomanim', {
7709 var origin = this._getCenterLayerPoint().add(offset);
7711 this._prepareTileBg();
7712 this._runAnimation(center, zoom, scale, origin);
7717 _catchTransitionEnd: function (e) {
7718 if (this._animatingZoom) {
7719 this._onZoomTransitionEnd();
7723 _runAnimation: function (center, zoom, scale, origin, backwardsTransform) {
7724 this._animateToCenter = center;
7725 this._animateToZoom = zoom;
7726 this._animatingZoom = true;
7729 L.Draggable._disabled = true;
7732 var transform = L.DomUtil.TRANSFORM,
7733 tileBg = this._tileBg;
7735 clearTimeout(this._clearTileBgTimer);
7737 L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation
7739 var scaleStr = L.DomUtil.getScaleString(scale, origin),
7740 oldTransform = tileBg.style[transform];
7742 tileBg.style[transform] = backwardsTransform ?
7743 oldTransform + ' ' + scaleStr :
7744 scaleStr + ' ' + oldTransform;
7747 _prepareTileBg: function () {
7748 var tilePane = this._tilePane,
7749 tileBg = this._tileBg;
7751 // If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more
7753 this._getLoadedTilesPercentage(tileBg) > 0.5 &&
7754 this._getLoadedTilesPercentage(tilePane) < 0.5) {
7756 tilePane.style.visibility = 'hidden';
7757 tilePane.empty = true;
7758 this._stopLoadingImages(tilePane);
7763 tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane);
7764 tileBg.style.zIndex = 1;
7767 // prepare the background pane to become the main tile pane
7768 tileBg.style[L.DomUtil.TRANSFORM] = '';
7769 tileBg.style.visibility = 'hidden';
7771 // tells tile layers to reinitialize their containers
7772 tileBg.empty = true; //new FG
7773 tilePane.empty = false; //new BG
7775 //Switch out the current layer to be the new bg layer (And vice-versa)
7776 this._tilePane = this._panes.tilePane = tileBg;
7777 var newTileBg = this._tileBg = tilePane;
7779 L.DomUtil.addClass(newTileBg, 'leaflet-zoom-animated');
7781 this._stopLoadingImages(newTileBg);
7784 _getLoadedTilesPercentage: function (container) {
7785 var tiles = container.getElementsByTagName('img'),
7788 for (i = 0, len = tiles.length; i < len; i++) {
7789 if (tiles[i].complete) {
7796 // stops loading all tiles in the background layer
7797 _stopLoadingImages: function (container) {
7798 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
7801 for (i = 0, len = tiles.length; i < len; i++) {
7804 if (!tile.complete) {
7805 tile.onload = L.Util.falseFn;
7806 tile.onerror = L.Util.falseFn;
7807 tile.src = L.Util.emptyImageUrl;
7809 tile.parentNode.removeChild(tile);
7814 _onZoomTransitionEnd: function () {
7815 this._restoreTileFront();
7816 L.Util.falseFn(this._tileBg.offsetWidth); // force reflow
7817 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
7819 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
7820 this._animatingZoom = false;
7823 L.Draggable._disabled = false;
7827 _restoreTileFront: function () {
7828 this._tilePane.innerHTML = '';
7829 this._tilePane.style.visibility = '';
7830 this._tilePane.style.zIndex = 2;
7831 this._tileBg.style.zIndex = 1;
7834 _clearTileBg: function () {
7835 if (!this._animatingZoom && !this.touchZoom._zooming) {
7836 this._tileBg.innerHTML = '';
7843 * Provides L.Map with convenient shortcuts for W3C geolocation.
7847 _defaultLocateOptions: {
7853 enableHighAccuracy: false
7856 locate: function (/*Object*/ options) {
7858 options = this._locationOptions = L.Util.extend(this._defaultLocateOptions, options);
7860 if (!navigator.geolocation) {
7861 this._handleGeolocationError({
7863 message: "Geolocation not supported."
7868 var onResponse = L.Util.bind(this._handleGeolocationResponse, this),
7869 onError = L.Util.bind(this._handleGeolocationError, this);
7871 if (options.watch) {
7872 this._locationWatchId = navigator.geolocation.watchPosition(onResponse, onError, options);
7874 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
7879 stopLocate: function () {
7880 if (navigator.geolocation) {
7881 navigator.geolocation.clearWatch(this._locationWatchId);
7886 _handleGeolocationError: function (error) {
7888 message = error.message ||
7889 (c === 1 ? "permission denied" :
7890 (c === 2 ? "position unavailable" : "timeout"));
7892 if (this._locationOptions.setView && !this._loaded) {
7896 this.fire('locationerror', {
7898 message: "Geolocation error: " + message + "."
7902 _handleGeolocationResponse: function (pos) {
7903 var latAccuracy = 180 * pos.coords.accuracy / 4e7,
7904 lngAccuracy = latAccuracy * 2,
7906 lat = pos.coords.latitude,
7907 lng = pos.coords.longitude,
7908 latlng = new L.LatLng(lat, lng),
7910 sw = new L.LatLng(lat - latAccuracy, lng - lngAccuracy),
7911 ne = new L.LatLng(lat + latAccuracy, lng + lngAccuracy),
7912 bounds = new L.LatLngBounds(sw, ne),
7914 options = this._locationOptions;
7916 if (options.setView) {
7917 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
7918 this.setView(latlng, zoom);
7921 this.fire('locationfound', {
7924 accuracy: pos.coords.accuracy