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 + '') {
\r
13 originalL = window.L;
\r
16 L.noConflict = function () {
\r
17 window.L = originalL;
\r
24 L.version = '0.4.4';
\r
28 * L.Util is a namespace for various utility functions.
\r
32 extend: function (/*Object*/ dest) /*-> Object*/ { // merge src properties into dest
\r
33 var sources = Array.prototype.slice.call(arguments, 1);
\r
34 for (var j = 0, len = sources.length, src; j < len; j++) {
\r
35 src = sources[j] || {};
\r
36 for (var i in src) {
\r
37 if (src.hasOwnProperty(i)) {
\r
45 bind: function (fn, obj) { // (Function, Object) -> Function
\r
46 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
\r
47 return function () {
\r
48 return fn.apply(obj, args || arguments);
\r
52 stamp: (function () {
\r
53 var lastId = 0, key = '_leaflet_id';
\r
54 return function (/*Object*/ obj) {
\r
55 obj[key] = obj[key] || ++lastId;
\r
60 limitExecByInterval: function (fn, time, context) {
\r
61 var lock, execOnUnlock;
\r
63 return function wrapperFn() {
\r
64 var args = arguments;
\r
67 execOnUnlock = true;
\r
73 setTimeout(function () {
\r
77 wrapperFn.apply(context, args);
\r
78 execOnUnlock = false;
\r
82 fn.apply(context, args);
\r
86 falseFn: function () {
\r
90 formatNum: function (num, digits) {
\r
91 var pow = Math.pow(10, digits || 5);
\r
92 return Math.round(num * pow) / pow;
\r
95 splitWords: function (str) {
\r
96 return str.replace(/^\s+|\s+$/g, '').split(/\s+/);
\r
99 setOptions: function (obj, options) {
\r
100 obj.options = L.Util.extend({}, obj.options, options);
\r
101 return obj.options;
\r
104 getParamString: function (obj) {
\r
106 for (var i in obj) {
\r
107 if (obj.hasOwnProperty(i)) {
\r
108 params.push(i + '=' + obj[i]);
\r
111 return '?' + params.join('&');
\r
114 template: function (str, data) {
\r
115 return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
\r
116 var value = data[key];
\r
117 if (!data.hasOwnProperty(key)) {
\r
118 throw new Error('No value provided for variable ' + str);
\r
124 emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
\r
129 // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
\r
131 function getPrefixed(name) {
\r
133 prefixes = ['webkit', 'moz', 'o', 'ms'];
\r
135 for (i = 0; i < prefixes.length && !fn; i++) {
\r
136 fn = window[prefixes[i] + name];
\r
144 function timeoutDefer(fn) {
\r
145 var time = +new Date(),
\r
146 timeToCall = Math.max(0, 16 - (time - lastTime));
\r
148 lastTime = time + timeToCall;
\r
149 return window.setTimeout(fn, timeToCall);
\r
152 var requestFn = window.requestAnimationFrame ||
\r
153 getPrefixed('RequestAnimationFrame') || timeoutDefer;
\r
155 var cancelFn = window.cancelAnimationFrame ||
\r
156 getPrefixed('CancelAnimationFrame') ||
\r
157 getPrefixed('CancelRequestAnimationFrame') ||
\r
159 window.clearTimeout(id);
\r
163 L.Util.requestAnimFrame = function (fn, context, immediate, element) {
\r
164 fn = L.Util.bind(fn, context);
\r
166 if (immediate && requestFn === timeoutDefer) {
\r
169 return requestFn.call(window, fn, element);
\r
173 L.Util.cancelAnimFrame = function (id) {
\r
175 cancelFn.call(window, id);
\r
183 * Class powers the OOP facilities of the library. Thanks to John Resig and Dean Edwards for inspiration!
\r
186 L.Class = function () {};
\r
188 L.Class.extend = function (/*Object*/ props) /*-> Class*/ {
\r
190 // extended class with the new prototype
\r
191 var NewClass = function () {
\r
192 if (this.initialize) {
\r
193 this.initialize.apply(this, arguments);
\r
197 // instantiate class without calling constructor
\r
198 var F = function () {};
\r
199 F.prototype = this.prototype;
\r
201 var proto = new F();
\r
202 proto.constructor = NewClass;
\r
204 NewClass.prototype = proto;
\r
206 //inherit parent's statics
\r
207 for (var i in this) {
\r
208 if (this.hasOwnProperty(i) && i !== 'prototype') {
\r
209 NewClass[i] = this[i];
\r
213 // mix static properties into the class
\r
214 if (props.statics) {
\r
215 L.Util.extend(NewClass, props.statics);
\r
216 delete props.statics;
\r
219 // mix includes into the prototype
\r
220 if (props.includes) {
\r
221 L.Util.extend.apply(null, [proto].concat(props.includes));
\r
222 delete props.includes;
\r
226 if (props.options && proto.options) {
\r
227 props.options = L.Util.extend({}, proto.options, props.options);
\r
230 // mix given properties into the prototype
\r
231 L.Util.extend(proto, props);
\r
237 // method for adding properties to prototype
\r
238 L.Class.include = function (props) {
\r
239 L.Util.extend(this.prototype, props);
\r
242 L.Class.mergeOptions = function (options) {
\r
243 L.Util.extend(this.prototype.options, options);
\r
247 * L.Mixin.Events adds custom events functionality to Leaflet classes
\r
250 var key = '_leaflet_events';
\r
256 addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
\r
257 var events = this[key] = this[key] || {},
\r
260 // Types can be a map of types/handlers
\r
261 if (typeof types === 'object') {
\r
262 for (type in types) {
\r
263 if (types.hasOwnProperty(type)) {
\r
264 this.addEventListener(type, types[type], fn);
\r
271 types = L.Util.splitWords(types);
\r
273 for (i = 0, len = types.length; i < len; i++) {
\r
274 events[types[i]] = events[types[i]] || [];
\r
275 events[types[i]].push({
\r
277 context: context || this
\r
284 hasEventListeners: function (type) { // (String) -> Boolean
\r
285 return (key in this) && (type in this[key]) && (this[key][type].length > 0);
\r
288 removeEventListener: function (types, fn, context) { // (String[, Function, Object]) or (Object[, Object])
\r
289 var events = this[key],
\r
290 type, i, len, listeners, j;
\r
292 if (typeof types === 'object') {
\r
293 for (type in types) {
\r
294 if (types.hasOwnProperty(type)) {
\r
295 this.removeEventListener(type, types[type], fn);
\r
302 types = L.Util.splitWords(types);
\r
304 for (i = 0, len = types.length; i < len; i++) {
\r
306 if (this.hasEventListeners(types[i])) {
\r
307 listeners = events[types[i]];
\r
309 for (j = listeners.length - 1; j >= 0; j--) {
\r
311 (!fn || listeners[j].action === fn) &&
\r
312 (!context || (listeners[j].context === context))
\r
314 listeners.splice(j, 1);
\r
323 fireEvent: function (type, data) { // (String[, Object])
\r
324 if (!this.hasEventListeners(type)) {
\r
328 var event = L.Util.extend({
\r
333 var listeners = this[key][type].slice();
\r
335 for (var i = 0, len = listeners.length; i < len; i++) {
\r
336 listeners[i].action.call(listeners[i].context || this, event);
\r
343 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
\r
344 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
\r
345 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
\r
349 var ua = navigator.userAgent.toLowerCase(),
\r
350 ie = !!window.ActiveXObject,
\r
351 ie6 = ie && !window.XMLHttpRequest,
\r
352 webkit = ua.indexOf("webkit") !== -1,
\r
353 gecko = ua.indexOf("gecko") !== -1,
\r
354 //Terrible browser detection to work around a safari / iOS / android browser bug. See TileLayer._addTile and debug/hacks/jitter.html
\r
355 chrome = ua.indexOf("chrome") !== -1,
\r
356 opera = window.opera,
\r
357 android = ua.indexOf("android") !== -1,
\r
358 android23 = ua.search("android [23]") !== -1,
\r
359 mobile = typeof orientation !== undefined + '' ? true : false,
\r
360 doc = document.documentElement,
\r
361 ie3d = ie && ('transition' in doc.style),
\r
362 webkit3d = webkit && ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
\r
363 gecko3d = gecko && ('MozPerspective' in doc.style),
\r
364 opera3d = opera && ('OTransition' in doc.style);
\r
366 var touch = !window.L_NO_TOUCH && (function () {
\r
367 var startName = 'ontouchstart';
\r
370 if (startName in doc) {
\r
375 var div = document.createElement('div'),
\r
378 if (!div.setAttribute) {
\r
381 div.setAttribute(startName, 'return;');
\r
383 if (typeof div[startName] === 'function') {
\r
387 div.removeAttribute(startName);
\r
393 var retina = (('devicePixelRatio' in window && window.devicePixelRatio > 1) || ('matchMedia' in window && window.matchMedia("(min-resolution:144dpi)").matches));
\r
403 android23: android23,
\r
408 webkit3d: webkit3d,
\r
411 any3d: !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d),
\r
414 mobileWebkit: mobile && webkit,
\r
415 mobileWebkit3d: mobile && webkit3d,
\r
416 mobileOpera: mobile && opera,
\r
426 * L.Point represents a point with x and y coordinates.
\r
429 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
\r
430 this.x = (round ? Math.round(x) : x);
\r
431 this.y = (round ? Math.round(y) : y);
\r
434 L.Point.prototype = {
\r
436 clone: function () {
\r
437 return new L.Point(this.x, this.y);
\r
440 // non-destructive, returns a new point
\r
441 add: function (point) {
\r
442 return this.clone()._add(L.point(point));
\r
445 // destructive, used directly for performance in situations where it's safe to modify existing point
\r
446 _add: function (point) {
\r
452 subtract: function (point) {
\r
453 return this.clone()._subtract(L.point(point));
\r
456 _subtract: function (point) {
\r
462 divideBy: function (num) {
\r
463 return this.clone()._divideBy(num);
\r
466 _divideBy: function (num) {
\r
472 multiplyBy: function (num) {
\r
473 return this.clone()._multiplyBy(num);
\r
476 _multiplyBy: function (num) {
\r
482 round: function () {
\r
483 return this.clone()._round();
\r
486 _round: function () {
\r
487 this.x = Math.round(this.x);
\r
488 this.y = Math.round(this.y);
\r
492 floor: function () {
\r
493 return this.clone()._floor();
\r
496 _floor: function () {
\r
497 this.x = Math.floor(this.x);
\r
498 this.y = Math.floor(this.y);
\r
502 distanceTo: function (point) {
\r
503 point = L.point(point);
\r
505 var x = point.x - this.x,
\r
506 y = point.y - this.y;
\r
508 return Math.sqrt(x * x + y * y);
\r
511 toString: function () {
\r
513 L.Util.formatNum(this.x) + ', ' +
\r
514 L.Util.formatNum(this.y) + ')';
\r
518 L.point = function (x, y, round) {
\r
519 if (x instanceof L.Point) {
\r
522 if (x instanceof Array) {
\r
523 return new L.Point(x[0], x[1]);
\r
528 return new L.Point(x, y, round);
\r
533 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
\r
536 L.Bounds = L.Class.extend({
\r
538 initialize: function (a, b) { //(Point, Point) or Point[]
\r
539 if (!a) { return; }
\r
541 var points = b ? [a, b] : a;
\r
543 for (var i = 0, len = points.length; i < len; i++) {
\r
544 this.extend(points[i]);
\r
548 // extend the bounds to contain the given point
\r
549 extend: function (point) { // (Point)
\r
550 point = L.point(point);
\r
552 if (!this.min && !this.max) {
\r
553 this.min = point.clone();
\r
554 this.max = point.clone();
\r
556 this.min.x = Math.min(point.x, this.min.x);
\r
557 this.max.x = Math.max(point.x, this.max.x);
\r
558 this.min.y = Math.min(point.y, this.min.y);
\r
559 this.max.y = Math.max(point.y, this.max.y);
\r
564 getCenter: function (round) { // (Boolean) -> Point
\r
565 return new L.Point(
\r
566 (this.min.x + this.max.x) / 2,
\r
567 (this.min.y + this.max.y) / 2, round);
\r
570 getBottomLeft: function () { // -> Point
\r
571 return new L.Point(this.min.x, this.max.y);
\r
574 getTopRight: function () { // -> Point
\r
575 return new L.Point(this.max.x, this.min.y);
\r
578 contains: function (obj) { // (Bounds) or (Point) -> Boolean
\r
581 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
\r
582 obj = L.point(obj);
\r
584 obj = L.bounds(obj);
\r
587 if (obj instanceof L.Bounds) {
\r
594 return (min.x >= this.min.x) &&
\r
595 (max.x <= this.max.x) &&
\r
596 (min.y >= this.min.y) &&
\r
597 (max.y <= this.max.y);
\r
600 intersects: function (bounds) { // (Bounds) -> Boolean
\r
601 bounds = L.bounds(bounds);
\r
603 var min = this.min,
\r
608 var xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
\r
609 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
\r
611 return xIntersects && yIntersects;
\r
614 isValid: function () {
\r
615 return !!(this.min && this.max);
\r
619 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
\r
620 if (!a || a instanceof L.Bounds) {
\r
623 return new L.Bounds(a, b);
\r
628 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
\r
631 L.Transformation = L.Class.extend({
\r
632 initialize: function (/*Number*/ a, /*Number*/ b, /*Number*/ c, /*Number*/ d) {
\r
639 transform: function (point, scale) {
\r
640 return this._transform(point.clone(), scale);
\r
643 // destructive transform (faster)
\r
644 _transform: function (/*Point*/ point, /*Number*/ scale) /*-> Point*/ {
\r
645 scale = scale || 1;
\r
646 point.x = scale * (this._a * point.x + this._b);
\r
647 point.y = scale * (this._c * point.y + this._d);
\r
651 untransform: function (/*Point*/ point, /*Number*/ scale) /*-> Point*/ {
\r
652 scale = scale || 1;
\r
653 return new L.Point(
\r
654 (point.x / scale - this._b) / this._a,
\r
655 (point.y / scale - this._d) / this._c);
\r
661 * L.DomUtil contains various utility functions for working with DOM.
\r
665 get: function (id) {
\r
666 return (typeof id === 'string' ? document.getElementById(id) : id);
\r
669 getStyle: function (el, style) {
\r
671 var value = el.style[style];
\r
673 if (!value && el.currentStyle) {
\r
674 value = el.currentStyle[style];
\r
677 if (!value || value === 'auto') {
\r
678 var css = document.defaultView.getComputedStyle(el, null);
\r
679 value = css ? css[style] : null;
\r
682 return value === 'auto' ? null : value;
\r
685 getViewportOffset: function (element) {
\r
690 docBody = document.body,
\r
694 top += el.offsetTop || 0;
\r
695 left += el.offsetLeft || 0;
\r
696 pos = L.DomUtil.getStyle(el, 'position');
\r
698 if (el.offsetParent === docBody && pos === 'absolute') { break; }
\r
700 if (pos === 'fixed') {
\r
701 top += docBody.scrollTop || 0;
\r
702 left += docBody.scrollLeft || 0;
\r
705 el = el.offsetParent;
\r
712 if (el === docBody) { break; }
\r
714 top -= el.scrollTop || 0;
\r
715 left -= el.scrollLeft || 0;
\r
717 el = el.parentNode;
\r
720 return new L.Point(left, top);
\r
723 create: function (tagName, className, container) {
\r
725 var el = document.createElement(tagName);
\r
726 el.className = className;
\r
729 container.appendChild(el);
\r
735 disableTextSelection: function () {
\r
736 if (document.selection && document.selection.empty) {
\r
737 document.selection.empty();
\r
739 if (!this._onselectstart) {
\r
740 this._onselectstart = document.onselectstart;
\r
741 document.onselectstart = L.Util.falseFn;
\r
745 enableTextSelection: function () {
\r
746 if (document.onselectstart === L.Util.falseFn) {
\r
747 document.onselectstart = this._onselectstart;
\r
748 this._onselectstart = null;
\r
752 hasClass: function (el, name) {
\r
753 return (el.className.length > 0) &&
\r
754 new RegExp("(^|\\s)" + name + "(\\s|$)").test(el.className);
\r
757 addClass: function (el, name) {
\r
758 if (!L.DomUtil.hasClass(el, name)) {
\r
759 el.className += (el.className ? ' ' : '') + name;
\r
763 removeClass: function (el, name) {
\r
765 function replaceFn(w, match) {
\r
766 if (match === name) { return ''; }
\r
770 el.className = el.className
\r
771 .replace(/(\S+)\s*/g, replaceFn)
\r
772 .replace(/(^\s+|\s+$)/, '');
\r
775 setOpacity: function (el, value) {
\r
777 if ('opacity' in el.style) {
\r
778 el.style.opacity = value;
\r
780 } else if (L.Browser.ie) {
\r
782 var filter = false,
\r
783 filterName = 'DXImageTransform.Microsoft.Alpha';
\r
785 // filters collection throws an error if we try to retrieve a filter that doesn't exist
\r
786 try { filter = el.filters.item(filterName); } catch (e) {}
\r
788 value = Math.round(value * 100);
\r
791 filter.Enabled = (value !== 100);
\r
792 filter.Opacity = value;
\r
794 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
\r
799 testProp: function (props) {
\r
801 var style = document.documentElement.style;
\r
803 for (var i = 0; i < props.length; i++) {
\r
804 if (props[i] in style) {
\r
811 getTranslateString: function (point) {
\r
812 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
\r
813 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
\r
814 // (same speed either way), Opera 12 doesn't support translate3d
\r
816 var is3d = L.Browser.webkit3d,
\r
817 open = 'translate' + (is3d ? '3d' : '') + '(',
\r
818 close = (is3d ? ',0' : '') + ')';
\r
820 return open + point.x + 'px,' + point.y + 'px' + close;
\r
823 getScaleString: function (scale, origin) {
\r
825 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
\r
826 scaleStr = ' scale(' + scale + ') ';
\r
828 return preTranslateStr + scaleStr;
\r
831 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
\r
833 el._leaflet_pos = point;
\r
835 if (!disable3D && L.Browser.any3d) {
\r
836 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
\r
838 // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
\r
839 if (L.Browser.mobileWebkit3d) {
\r
840 el.style.WebkitBackfaceVisibility = 'hidden';
\r
843 el.style.left = point.x + 'px';
\r
844 el.style.top = point.y + 'px';
\r
848 getPosition: function (el) {
\r
849 // this method is only used for elements previously positioned using setPosition,
\r
850 // so it's safe to cache the position for performance
\r
851 return el._leaflet_pos;
\r
856 // prefix style property names
\r
858 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
\r
859 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
\r
861 L.DomUtil.TRANSITION = L.DomUtil.testProp(
\r
862 ['transition', 'webkitTransition', 'OTransition', 'MozTransition', 'msTransition']);
\r
864 L.DomUtil.TRANSITION_END =
\r
865 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
\r
866 L.DomUtil.TRANSITION + 'End' : 'transitionend';
\r
870 CM.LatLng represents a geographical point with latitude and longtitude coordinates.
\r
873 L.LatLng = function (rawLat, rawLng, noWrap) { // (Number, Number[, Boolean])
\r
874 var lat = parseFloat(rawLat),
\r
875 lng = parseFloat(rawLng);
\r
877 if (isNaN(lat) || isNaN(lng)) {
\r
878 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
\r
881 if (noWrap !== true) {
\r
882 lat = Math.max(Math.min(lat, 90), -90); // clamp latitude into -90..90
\r
883 lng = (lng + 180) % 360 + ((lng < -180 || lng === 180) ? 180 : -180); // wrap longtitude into -180..180
\r
890 L.Util.extend(L.LatLng, {
\r
891 DEG_TO_RAD: Math.PI / 180,
\r
892 RAD_TO_DEG: 180 / Math.PI,
\r
893 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
\r
896 L.LatLng.prototype = {
\r
897 equals: function (obj) { // (LatLng) -> Boolean
\r
898 if (!obj) { return false; }
\r
900 obj = L.latLng(obj);
\r
902 var margin = Math.max(Math.abs(this.lat - obj.lat), Math.abs(this.lng - obj.lng));
\r
903 return margin <= L.LatLng.MAX_MARGIN;
\r
906 toString: function () { // -> String
\r
908 L.Util.formatNum(this.lat) + ', ' +
\r
909 L.Util.formatNum(this.lng) + ')';
\r
912 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
\r
913 distanceTo: function (other) { // (LatLng) -> Number
\r
914 other = L.latLng(other);
\r
916 var R = 6378137, // earth radius in meters
\r
917 d2r = L.LatLng.DEG_TO_RAD,
\r
918 dLat = (other.lat - this.lat) * d2r,
\r
919 dLon = (other.lng - this.lng) * d2r,
\r
920 lat1 = this.lat * d2r,
\r
921 lat2 = other.lat * d2r,
\r
922 sin1 = Math.sin(dLat / 2),
\r
923 sin2 = Math.sin(dLon / 2);
\r
925 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
\r
927 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
\r
931 L.latLng = function (a, b, c) { // (LatLng) or ([Number, Number]) or (Number, Number, Boolean)
\r
932 if (a instanceof L.LatLng) {
\r
935 if (a instanceof Array) {
\r
936 return new L.LatLng(a[0], a[1]);
\r
941 return new L.LatLng(a, b, c);
\r
946 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
\r
949 L.LatLngBounds = L.Class.extend({
\r
950 initialize: function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
\r
951 if (!southWest) { return; }
\r
953 var latlngs = northEast ? [southWest, northEast] : southWest;
\r
955 for (var i = 0, len = latlngs.length; i < len; i++) {
\r
956 this.extend(latlngs[i]);
\r
960 // extend the bounds to contain the given point or bounds
\r
961 extend: function (obj) { // (LatLng) or (LatLngBounds)
\r
962 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
\r
963 obj = L.latLng(obj);
\r
965 obj = L.latLngBounds(obj);
\r
968 if (obj instanceof L.LatLng) {
\r
969 if (!this._southWest && !this._northEast) {
\r
970 this._southWest = new L.LatLng(obj.lat, obj.lng, true);
\r
971 this._northEast = new L.LatLng(obj.lat, obj.lng, true);
\r
973 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
\r
974 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
\r
976 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
\r
977 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
\r
979 } else if (obj instanceof L.LatLngBounds) {
\r
980 this.extend(obj._southWest);
\r
981 this.extend(obj._northEast);
\r
986 // extend the bounds by a percentage
\r
987 pad: function (bufferRatio) { // (Number) -> LatLngBounds
\r
988 var sw = this._southWest,
\r
989 ne = this._northEast,
\r
990 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
\r
991 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
\r
993 return new L.LatLngBounds(
\r
994 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
\r
995 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
\r
998 getCenter: function () { // -> LatLng
\r
999 return new L.LatLng(
\r
1000 (this._southWest.lat + this._northEast.lat) / 2,
\r
1001 (this._southWest.lng + this._northEast.lng) / 2);
\r
1004 getSouthWest: function () {
\r
1005 return this._southWest;
\r
1008 getNorthEast: function () {
\r
1009 return this._northEast;
\r
1012 getNorthWest: function () {
\r
1013 return new L.LatLng(this._northEast.lat, this._southWest.lng, true);
\r
1016 getSouthEast: function () {
\r
1017 return new L.LatLng(this._southWest.lat, this._northEast.lng, true);
\r
1020 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
\r
1021 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
\r
1022 obj = L.latLng(obj);
\r
1024 obj = L.latLngBounds(obj);
\r
1027 var sw = this._southWest,
\r
1028 ne = this._northEast,
\r
1031 if (obj instanceof L.LatLngBounds) {
\r
1032 sw2 = obj.getSouthWest();
\r
1033 ne2 = obj.getNorthEast();
\r
1038 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
\r
1039 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
\r
1042 intersects: function (bounds) { // (LatLngBounds)
\r
1043 bounds = L.latLngBounds(bounds);
\r
1045 var sw = this._southWest,
\r
1046 ne = this._northEast,
\r
1047 sw2 = bounds.getSouthWest(),
\r
1048 ne2 = bounds.getNorthEast();
\r
1050 var latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
\r
1051 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
\r
1053 return latIntersects && lngIntersects;
\r
1056 toBBoxString: function () {
\r
1057 var sw = this._southWest,
\r
1058 ne = this._northEast;
\r
1059 return [sw.lng, sw.lat, ne.lng, ne.lat].join(',');
\r
1062 equals: function (bounds) { // (LatLngBounds)
\r
1063 if (!bounds) { return false; }
\r
1065 bounds = L.latLngBounds(bounds);
\r
1067 return this._southWest.equals(bounds.getSouthWest()) &&
\r
1068 this._northEast.equals(bounds.getNorthEast());
\r
1071 isValid: function () {
\r
1072 return !!(this._southWest && this._northEast);
\r
1076 //TODO International date line?
\r
1078 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
\r
1079 if (!a || a instanceof L.LatLngBounds) {
\r
1082 return new L.LatLngBounds(a, b);
\r
1087 * L.Projection contains various geographical projections used by CRS classes.
\r
1090 L.Projection = {};
\r
1094 L.Projection.SphericalMercator = {
\r
1095 MAX_LATITUDE: 85.0511287798,
\r
1097 project: function (latlng) { // (LatLng) -> Point
\r
1098 var d = L.LatLng.DEG_TO_RAD,
\r
1099 max = this.MAX_LATITUDE,
\r
1100 lat = Math.max(Math.min(max, latlng.lat), -max),
\r
1101 x = latlng.lng * d,
\r
1103 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
\r
1105 return new L.Point(x, y);
\r
1108 unproject: function (point) { // (Point, Boolean) -> LatLng
\r
1109 var d = L.LatLng.RAD_TO_DEG,
\r
1110 lng = point.x * d,
\r
1111 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
\r
1113 // TODO refactor LatLng wrapping
\r
1114 return new L.LatLng(lat, lng, true);
\r
1120 L.Projection.LonLat = {
\r
1121 project: function (latlng) {
\r
1122 return new L.Point(latlng.lng, latlng.lat);
\r
1125 unproject: function (point) {
\r
1126 return new L.LatLng(point.y, point.x, true);
\r
1133 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
\r
1134 var projectedPoint = this.projection.project(latlng),
\r
1135 scale = this.scale(zoom);
\r
1137 return this.transformation._transform(projectedPoint, scale);
\r
1140 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
\r
1141 var scale = this.scale(zoom),
\r
1142 untransformedPoint = this.transformation.untransform(point, scale);
\r
1144 return this.projection.unproject(untransformedPoint);
\r
1147 project: function (latlng) {
\r
1148 return this.projection.project(latlng);
\r
1151 scale: function (zoom) {
\r
1152 return 256 * Math.pow(2, zoom);
\r
1158 L.CRS.EPSG3857 = L.Util.extend({}, L.CRS, {
\r
1159 code: 'EPSG:3857',
\r
1161 projection: L.Projection.SphericalMercator,
\r
1162 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
\r
1164 project: function (latlng) { // (LatLng) -> Point
\r
1165 var projectedPoint = this.projection.project(latlng),
\r
1166 earthRadius = 6378137;
\r
1167 return projectedPoint.multiplyBy(earthRadius);
\r
1171 L.CRS.EPSG900913 = L.Util.extend({}, L.CRS.EPSG3857, {
\r
1172 code: 'EPSG:900913'
\r
1177 L.CRS.EPSG4326 = L.Util.extend({}, L.CRS, {
\r
1178 code: 'EPSG:4326',
\r
1180 projection: L.Projection.LonLat,
\r
1181 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
\r
1186 * L.Map is the central class of the API - it is used to create a map.
\r
1189 L.Map = L.Class.extend({
\r
1191 includes: L.Mixin.Events,
\r
1194 crs: L.CRS.EPSG3857,
\r
1202 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
\r
1203 trackResize: true,
\r
1204 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
\r
1207 initialize: function (id, options) { // (HTMLElement or String, Object)
\r
1208 options = L.Util.setOptions(this, options);
\r
1210 this._initContainer(id);
\r
1211 this._initLayout();
\r
1212 this._initHooks();
\r
1213 this._initEvents();
\r
1215 if (options.maxBounds) {
\r
1216 this.setMaxBounds(options.maxBounds);
\r
1219 if (options.center && options.zoom !== undefined) {
\r
1220 this.setView(L.latLng(options.center), options.zoom, true);
\r
1223 this._initLayers(options.layers);
\r
1227 // public methods that modify map state
\r
1229 // replaced by animation-powered implementation in Map.PanAnimation.js
\r
1230 setView: function (center, zoom) {
\r
1231 this._resetView(L.latLng(center), this._limitZoom(zoom));
\r
1235 setZoom: function (zoom) { // (Number)
\r
1236 return this.setView(this.getCenter(), zoom);
\r
1239 zoomIn: function (delta) {
\r
1240 return this.setZoom(this._zoom + (delta || 1));
\r
1243 zoomOut: function (delta) {
\r
1244 return this.setZoom(this._zoom - (delta || 1));
\r
1247 fitBounds: function (bounds) { // (LatLngBounds)
\r
1248 var zoom = this.getBoundsZoom(bounds);
\r
1249 return this.setView(L.latLngBounds(bounds).getCenter(), zoom);
\r
1252 fitWorld: function () {
\r
1253 var sw = new L.LatLng(-60, -170),
\r
1254 ne = new L.LatLng(85, 179);
\r
1256 return this.fitBounds(new L.LatLngBounds(sw, ne));
\r
1259 panTo: function (center) { // (LatLng)
\r
1260 return this.setView(center, this._zoom);
\r
1263 panBy: function (offset) { // (Point)
\r
1264 // replaced with animated panBy in Map.Animation.js
\r
1265 this.fire('movestart');
\r
1267 this._rawPanBy(L.point(offset));
\r
1269 this.fire('move');
\r
1270 return this.fire('moveend');
\r
1273 setMaxBounds: function (bounds) {
\r
1274 bounds = L.latLngBounds(bounds);
\r
1276 this.options.maxBounds = bounds;
\r
1279 this._boundsMinZoom = null;
\r
1283 var minZoom = this.getBoundsZoom(bounds, true);
\r
1285 this._boundsMinZoom = minZoom;
\r
1287 if (this._loaded) {
\r
1288 if (this._zoom < minZoom) {
\r
1289 this.setView(bounds.getCenter(), minZoom);
\r
1291 this.panInsideBounds(bounds);
\r
1298 panInsideBounds: function (bounds) {
\r
1299 bounds = L.latLngBounds(bounds);
\r
1301 var viewBounds = this.getBounds(),
\r
1302 viewSw = this.project(viewBounds.getSouthWest()),
\r
1303 viewNe = this.project(viewBounds.getNorthEast()),
\r
1304 sw = this.project(bounds.getSouthWest()),
\r
1305 ne = this.project(bounds.getNorthEast()),
\r
1309 if (viewNe.y < ne.y) { // north
\r
1310 dy = ne.y - viewNe.y;
\r
1312 if (viewNe.x > ne.x) { // east
\r
1313 dx = ne.x - viewNe.x;
\r
1315 if (viewSw.y > sw.y) { // south
\r
1316 dy = sw.y - viewSw.y;
\r
1318 if (viewSw.x < sw.x) { // west
\r
1319 dx = sw.x - viewSw.x;
\r
1322 return this.panBy(new L.Point(dx, dy, true));
\r
1325 addLayer: function (layer) {
\r
1326 // TODO method is too big, refactor
\r
1328 var id = L.Util.stamp(layer);
\r
1330 if (this._layers[id]) { return this; }
\r
1332 this._layers[id] = layer;
\r
1334 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
\r
1335 if (layer.options && !isNaN(layer.options.maxZoom)) {
\r
1336 this._layersMaxZoom = Math.max(this._layersMaxZoom || 0, layer.options.maxZoom);
\r
1338 if (layer.options && !isNaN(layer.options.minZoom)) {
\r
1339 this._layersMinZoom = Math.min(this._layersMinZoom || Infinity, layer.options.minZoom);
\r
1342 // TODO looks ugly, refactor!!!
\r
1343 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
\r
1344 this._tileLayersNum++;
\r
1345 this._tileLayersToLoad++;
\r
1346 layer.on('load', this._onTileLayerLoad, this);
\r
1349 this.whenReady(function () {
\r
1350 layer.onAdd(this);
\r
1351 this.fire('layeradd', {layer: layer});
\r
1357 removeLayer: function (layer) {
\r
1358 var id = L.Util.stamp(layer);
\r
1360 if (!this._layers[id]) { return; }
\r
1362 layer.onRemove(this);
\r
1364 delete this._layers[id];
\r
1366 // TODO looks ugly, refactor
\r
1367 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
\r
1368 this._tileLayersNum--;
\r
1369 this._tileLayersToLoad--;
\r
1370 layer.off('load', this._onTileLayerLoad, this);
\r
1373 return this.fire('layerremove', {layer: layer});
\r
1376 hasLayer: function (layer) {
\r
1377 var id = L.Util.stamp(layer);
\r
1378 return this._layers.hasOwnProperty(id);
\r
1381 invalidateSize: function (animate) {
\r
1382 var oldSize = this.getSize();
\r
1384 this._sizeChanged = true;
\r
1386 if (this.options.maxBounds) {
\r
1387 this.setMaxBounds(this.options.maxBounds);
\r
1390 if (!this._loaded) { return this; }
\r
1392 var offset = oldSize._subtract(this.getSize())._divideBy(2)._round();
\r
1394 if (animate === true) {
\r
1395 this.panBy(offset);
\r
1397 this._rawPanBy(offset);
\r
1399 this.fire('move');
\r
1401 clearTimeout(this._sizeTimer);
\r
1402 this._sizeTimer = setTimeout(L.Util.bind(this.fire, this, 'moveend'), 200);
\r
1407 // TODO handler.addTo
\r
1408 addHandler: function (name, HandlerClass) {
\r
1409 if (!HandlerClass) { return; }
\r
1411 this[name] = new HandlerClass(this);
\r
1413 if (this.options[name]) {
\r
1414 this[name].enable();
\r
1421 // public methods for getting map state
\r
1423 getCenter: function () { // (Boolean) -> LatLng
\r
1424 return this.layerPointToLatLng(this._getCenterLayerPoint());
\r
1427 getZoom: function () {
\r
1428 return this._zoom;
\r
1431 getBounds: function () {
\r
1432 var bounds = this.getPixelBounds(),
\r
1433 sw = this.unproject(bounds.getBottomLeft()),
\r
1434 ne = this.unproject(bounds.getTopRight());
\r
1436 return new L.LatLngBounds(sw, ne);
\r
1439 getMinZoom: function () {
\r
1440 var z1 = this.options.minZoom || 0,
\r
1441 z2 = this._layersMinZoom || 0,
\r
1442 z3 = this._boundsMinZoom || 0;
\r
1444 return Math.max(z1, z2, z3);
\r
1447 getMaxZoom: function () {
\r
1448 var z1 = this.options.maxZoom === undefined ? Infinity : this.options.maxZoom,
\r
1449 z2 = this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom;
\r
1451 return Math.min(z1, z2);
\r
1454 getBoundsZoom: function (bounds, inside) { // (LatLngBounds, Boolean) -> Number
\r
1455 bounds = L.latLngBounds(bounds);
\r
1457 var size = this.getSize(),
\r
1458 zoom = this.options.minZoom || 0,
\r
1459 maxZoom = this.getMaxZoom(),
\r
1460 ne = bounds.getNorthEast(),
\r
1461 sw = bounds.getSouthWest(),
\r
1465 zoomNotFound = true;
\r
1473 nePoint = this.project(ne, zoom);
\r
1474 swPoint = this.project(sw, zoom);
\r
1475 boundsSize = new L.Point(Math.abs(nePoint.x - swPoint.x), Math.abs(swPoint.y - nePoint.y));
\r
1478 zoomNotFound = boundsSize.x <= size.x && boundsSize.y <= size.y;
\r
1480 zoomNotFound = boundsSize.x < size.x || boundsSize.y < size.y;
\r
1482 } while (zoomNotFound && zoom <= maxZoom);
\r
1484 if (zoomNotFound && inside) {
\r
1488 return inside ? zoom : zoom - 1;
\r
1491 getSize: function () {
\r
1492 if (!this._size || this._sizeChanged) {
\r
1493 this._size = new L.Point(
\r
1494 this._container.clientWidth,
\r
1495 this._container.clientHeight);
\r
1497 this._sizeChanged = false;
\r
1499 return this._size.clone();
\r
1502 getPixelBounds: function () {
\r
1503 var topLeftPoint = this._getTopLeftPoint();
\r
1504 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
\r
1507 getPixelOrigin: function () {
\r
1508 return this._initialTopLeftPoint;
\r
1511 getPanes: function () {
\r
1512 return this._panes;
\r
1515 getContainer: function () {
\r
1516 return this._container;
\r
1520 // TODO replace with universal implementation after refactoring projections
\r
1522 getZoomScale: function (toZoom) {
\r
1523 var crs = this.options.crs;
\r
1524 return crs.scale(toZoom) / crs.scale(this._zoom);
\r
1527 getScaleZoom: function (scale) {
\r
1528 return this._zoom + (Math.log(scale) / Math.LN2);
\r
1532 // conversion methods
\r
1534 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
\r
1535 zoom = zoom === undefined ? this._zoom : zoom;
\r
1536 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
\r
1539 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
\r
1540 zoom = zoom === undefined ? this._zoom : zoom;
\r
1541 return this.options.crs.pointToLatLng(L.point(point), zoom);
\r
1544 layerPointToLatLng: function (point) { // (Point)
\r
1545 var projectedPoint = L.point(point).add(this._initialTopLeftPoint);
\r
1546 return this.unproject(projectedPoint);
\r
1549 latLngToLayerPoint: function (latlng) { // (LatLng)
\r
1550 var projectedPoint = this.project(L.latLng(latlng))._round();
\r
1551 return projectedPoint._subtract(this._initialTopLeftPoint);
\r
1554 containerPointToLayerPoint: function (point) { // (Point)
\r
1555 return L.point(point).subtract(this._getMapPanePos());
\r
1558 layerPointToContainerPoint: function (point) { // (Point)
\r
1559 return L.point(point).add(this._getMapPanePos());
\r
1562 containerPointToLatLng: function (point) {
\r
1563 var layerPoint = this.containerPointToLayerPoint(L.point(point));
\r
1564 return this.layerPointToLatLng(layerPoint);
\r
1567 latLngToContainerPoint: function (latlng) {
\r
1568 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
\r
1571 mouseEventToContainerPoint: function (e) { // (MouseEvent)
\r
1572 return L.DomEvent.getMousePosition(e, this._container);
\r
1575 mouseEventToLayerPoint: function (e) { // (MouseEvent)
\r
1576 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
\r
1579 mouseEventToLatLng: function (e) { // (MouseEvent)
\r
1580 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
\r
1584 // map initialization methods
\r
1586 _initContainer: function (id) {
\r
1587 var container = this._container = L.DomUtil.get(id);
\r
1589 if (container._leaflet) {
\r
1590 throw new Error("Map container is already initialized.");
\r
1593 container._leaflet = true;
\r
1596 _initLayout: function () {
\r
1597 var container = this._container;
\r
1599 container.innerHTML = '';
\r
1600 L.DomUtil.addClass(container, 'leaflet-container');
\r
1602 if (L.Browser.touch) {
\r
1603 L.DomUtil.addClass(container, 'leaflet-touch');
\r
1606 if (this.options.fadeAnimation) {
\r
1607 L.DomUtil.addClass(container, 'leaflet-fade-anim');
\r
1610 var position = L.DomUtil.getStyle(container, 'position');
\r
1612 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
\r
1613 container.style.position = 'relative';
\r
1616 this._initPanes();
\r
1618 if (this._initControlPos) {
\r
1619 this._initControlPos();
\r
1623 _initPanes: function () {
\r
1624 var panes = this._panes = {};
\r
1626 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
\r
1628 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
\r
1629 this._objectsPane = panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
\r
1631 panes.shadowPane = this._createPane('leaflet-shadow-pane');
\r
1632 panes.overlayPane = this._createPane('leaflet-overlay-pane');
\r
1633 panes.markerPane = this._createPane('leaflet-marker-pane');
\r
1634 panes.popupPane = this._createPane('leaflet-popup-pane');
\r
1636 var zoomHide = ' leaflet-zoom-hide';
\r
1638 if (!this.options.markerZoomAnimation) {
\r
1639 L.DomUtil.addClass(panes.markerPane, zoomHide);
\r
1640 L.DomUtil.addClass(panes.shadowPane, zoomHide);
\r
1641 L.DomUtil.addClass(panes.popupPane, zoomHide);
\r
1645 _createPane: function (className, container) {
\r
1646 return L.DomUtil.create('div', className, container || this._objectsPane);
\r
1649 _initializers: [],
\r
1651 _initHooks: function () {
\r
1653 for (i = 0, len = this._initializers.length; i < len; i++) {
\r
1654 this._initializers[i].call(this);
\r
1658 _initLayers: function (layers) {
\r
1659 layers = layers ? (layers instanceof Array ? layers : [layers]) : [];
\r
1661 this._layers = {};
\r
1662 this._tileLayersNum = 0;
\r
1666 for (i = 0, len = layers.length; i < len; i++) {
\r
1667 this.addLayer(layers[i]);
\r
1672 // private methods that modify map state
\r
1674 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
\r
1676 var zoomChanged = (this._zoom !== zoom);
\r
1678 if (!afterZoomAnim) {
\r
1679 this.fire('movestart');
\r
1681 if (zoomChanged) {
\r
1682 this.fire('zoomstart');
\r
1686 this._zoom = zoom;
\r
1688 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
\r
1690 if (!preserveMapOffset) {
\r
1691 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
\r
1693 this._initialTopLeftPoint._add(this._getMapPanePos());
\r
1696 this._tileLayersToLoad = this._tileLayersNum;
\r
1698 var loading = !this._loaded;
\r
1699 this._loaded = true;
\r
1701 this.fire('viewreset', {hard: !preserveMapOffset});
\r
1703 this.fire('move');
\r
1705 if (zoomChanged || afterZoomAnim) {
\r
1706 this.fire('zoomend');
\r
1709 this.fire('moveend', {hard: !preserveMapOffset});
\r
1712 this.fire('load');
\r
1716 _rawPanBy: function (offset) {
\r
1717 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
\r
1723 _initEvents: function () {
\r
1724 if (!L.DomEvent) { return; }
\r
1726 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
\r
1728 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter', 'mouseleave', 'mousemove', 'contextmenu'],
\r
1731 for (i = 0, len = events.length; i < len; i++) {
\r
1732 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
\r
1735 if (this.options.trackResize) {
\r
1736 L.DomEvent.on(window, 'resize', this._onResize, this);
\r
1740 _onResize: function () {
\r
1741 L.Util.cancelAnimFrame(this._resizeRequest);
\r
1742 this._resizeRequest = L.Util.requestAnimFrame(this.invalidateSize, this, false, this._container);
\r
1745 _onMouseClick: function (e) {
\r
1746 if (!this._loaded || (this.dragging && this.dragging.moved())) { return; }
\r
1748 this.fire('preclick');
\r
1749 this._fireMouseEvent(e);
\r
1752 _fireMouseEvent: function (e) {
\r
1753 if (!this._loaded) { return; }
\r
1755 var type = e.type;
\r
1757 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
\r
1759 if (!this.hasEventListeners(type)) { return; }
\r
1761 if (type === 'contextmenu') {
\r
1762 L.DomEvent.preventDefault(e);
\r
1765 var containerPoint = this.mouseEventToContainerPoint(e),
\r
1766 layerPoint = this.containerPointToLayerPoint(containerPoint),
\r
1767 latlng = this.layerPointToLatLng(layerPoint);
\r
1771 layerPoint: layerPoint,
\r
1772 containerPoint: containerPoint,
\r
1777 _onTileLayerLoad: function () {
\r
1778 // TODO super-ugly, refactor!!!
\r
1779 // clear scaled tiles after all new tiles are loaded (for performance)
\r
1780 this._tileLayersToLoad--;
\r
1781 if (this._tileLayersNum && !this._tileLayersToLoad && this._tileBg) {
\r
1782 clearTimeout(this._clearTileBgTimer);
\r
1783 this._clearTileBgTimer = setTimeout(L.Util.bind(this._clearTileBg, this), 500);
\r
1787 whenReady: function (callback, context) {
\r
1788 if (this._loaded) {
\r
1789 callback.call(context || this, this);
\r
1791 this.on('load', callback, context);
\r
1797 // private methods for getting map state
\r
1799 _getMapPanePos: function () {
\r
1800 return L.DomUtil.getPosition(this._mapPane);
\r
1803 _getTopLeftPoint: function () {
\r
1804 if (!this._loaded) {
\r
1805 throw new Error('Set map center and zoom first.');
\r
1808 return this._initialTopLeftPoint.subtract(this._getMapPanePos());
\r
1811 _getNewTopLeftPoint: function (center, zoom) {
\r
1812 var viewHalf = this.getSize()._divideBy(2);
\r
1813 // TODO round on display, not calculation to increase precision?
\r
1814 return this.project(center, zoom)._subtract(viewHalf)._round();
\r
1817 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
\r
1818 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
\r
1819 return this.project(latlng, newZoom)._subtract(topLeft);
\r
1822 _getCenterLayerPoint: function () {
\r
1823 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
\r
1826 _getCenterOffset: function (center) {
\r
1827 return this.latLngToLayerPoint(center).subtract(this._getCenterLayerPoint());
\r
1830 _limitZoom: function (zoom) {
\r
1831 var min = this.getMinZoom(),
\r
1832 max = this.getMaxZoom();
\r
1834 return Math.max(min, Math.min(max, zoom));
\r
1838 L.Map.addInitHook = function (fn) {
\r
1839 var args = Array.prototype.slice.call(arguments, 1);
\r
1841 var init = typeof fn === 'function' ? fn : function () {
\r
1842 this[fn].apply(this, args);
\r
1845 this.prototype._initializers.push(init);
\r
1848 L.map = function (id, options) {
\r
1849 return new L.Map(id, options);
\r
1854 L.Projection.Mercator = {
\r
1855 MAX_LATITUDE: 85.0840591556,
\r
1857 R_MINOR: 6356752.3142,
\r
1860 project: function (latlng) { // (LatLng) -> Point
\r
1861 var d = L.LatLng.DEG_TO_RAD,
\r
1862 max = this.MAX_LATITUDE,
\r
1863 lat = Math.max(Math.min(max, latlng.lat), -max),
\r
1865 r2 = this.R_MINOR,
\r
1866 x = latlng.lng * d * r,
\r
1869 eccent = Math.sqrt(1.0 - tmp * tmp),
\r
1870 con = eccent * Math.sin(y);
\r
1872 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
\r
1874 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
\r
1875 y = -r2 * Math.log(ts);
\r
1877 return new L.Point(x, y);
\r
1880 unproject: function (point) { // (Point, Boolean) -> LatLng
\r
1881 var d = L.LatLng.RAD_TO_DEG,
\r
1883 r2 = this.R_MINOR,
\r
1884 lng = point.x * d / r,
\r
1886 eccent = Math.sqrt(1 - (tmp * tmp)),
\r
1887 ts = Math.exp(- point.y / r2),
\r
1888 phi = (Math.PI / 2) - 2 * Math.atan(ts),
\r
1895 while ((Math.abs(dphi) > tol) && (--i > 0)) {
\r
1896 con = eccent * Math.sin(phi);
\r
1897 dphi = (Math.PI / 2) - 2 * Math.atan(ts * Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
\r
1901 return new L.LatLng(phi * d, lng, true);
\r
1907 L.CRS.EPSG3395 = L.Util.extend({}, L.CRS, {
\r
1908 code: 'EPSG:3395',
\r
1910 projection: L.Projection.Mercator,
\r
1912 transformation: (function () {
\r
1913 var m = L.Projection.Mercator,
\r
1917 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
\r
1923 * L.TileLayer is used for standard xyz-numbered tile layers.
\r
1926 L.TileLayer = L.Class.extend({
\r
1927 includes: L.Mixin.Events,
\r
1933 subdomains: 'abc',
\r
1938 /* (undefined works too)
\r
1941 continuousWorld: false,
\r
1943 zoomReverse: false,
\r
1944 detectRetina: false,
\r
1945 reuseTiles: false,
\r
1947 unloadInvisibleTiles: L.Browser.mobile,
\r
1948 updateWhenIdle: L.Browser.mobile
\r
1951 initialize: function (url, options) {
\r
1952 options = L.Util.setOptions(this, options);
\r
1954 // detecting retina displays, adjusting tileSize and zoom levels
\r
1955 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
\r
1957 options.tileSize = Math.floor(options.tileSize / 2);
\r
1958 options.zoomOffset++;
\r
1960 if (options.minZoom > 0) {
\r
1961 options.minZoom--;
\r
1963 this.options.maxZoom--;
\r
1968 var subdomains = this.options.subdomains;
\r
1970 if (typeof subdomains === 'string') {
\r
1971 this.options.subdomains = subdomains.split('');
\r
1975 onAdd: function (map) {
\r
1978 // create a container div for tiles
\r
1979 this._initContainer();
\r
1981 // create an image to clone for tiles
\r
1982 this._createTileProto();
\r
1986 'viewreset': this._resetCallback,
\r
1987 'moveend': this._update
\r
1990 if (!this.options.updateWhenIdle) {
\r
1991 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
\r
1992 map.on('move', this._limitedUpdate, this);
\r
1999 addTo: function (map) {
\r
2000 map.addLayer(this);
\r
2004 onRemove: function (map) {
\r
2005 map._panes.tilePane.removeChild(this._container);
\r
2008 'viewreset': this._resetCallback,
\r
2009 'moveend': this._update
\r
2012 if (!this.options.updateWhenIdle) {
\r
2013 map.off('move', this._limitedUpdate, this);
\r
2016 this._container = null;
\r
2020 bringToFront: function () {
\r
2021 var pane = this._map._panes.tilePane;
\r
2023 if (this._container) {
\r
2024 pane.appendChild(this._container);
\r
2025 this._setAutoZIndex(pane, Math.max);
\r
2031 bringToBack: function () {
\r
2032 var pane = this._map._panes.tilePane;
\r
2034 if (this._container) {
\r
2035 pane.insertBefore(this._container, pane.firstChild);
\r
2036 this._setAutoZIndex(pane, Math.min);
\r
2042 getAttribution: function () {
\r
2043 return this.options.attribution;
\r
2046 setOpacity: function (opacity) {
\r
2047 this.options.opacity = opacity;
\r
2050 this._updateOpacity();
\r
2056 setZIndex: function (zIndex) {
\r
2057 this.options.zIndex = zIndex;
\r
2058 this._updateZIndex();
\r
2063 setUrl: function (url, noRedraw) {
\r
2073 redraw: function () {
\r
2075 this._map._panes.tilePane.empty = false;
\r
2076 this._reset(true);
\r
2082 _updateZIndex: function () {
\r
2083 if (this._container && this.options.zIndex !== undefined) {
\r
2084 this._container.style.zIndex = this.options.zIndex;
\r
2088 _setAutoZIndex: function (pane, compare) {
\r
2090 var layers = pane.getElementsByClassName('leaflet-layer'),
\r
2091 edgeZIndex = -compare(Infinity, -Infinity), // -Ifinity for max, Infinity for min
\r
2094 for (var i = 0, len = layers.length; i < len; i++) {
\r
2096 if (layers[i] !== this._container) {
\r
2097 zIndex = parseInt(layers[i].style.zIndex, 10);
\r
2099 if (!isNaN(zIndex)) {
\r
2100 edgeZIndex = compare(edgeZIndex, zIndex);
\r
2105 this.options.zIndex = this._container.style.zIndex = (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
\r
2108 _updateOpacity: function () {
\r
2109 L.DomUtil.setOpacity(this._container, this.options.opacity);
\r
2111 // stupid webkit hack to force redrawing of tiles
\r
2113 tiles = this._tiles;
\r
2115 if (L.Browser.webkit) {
\r
2116 for (i in tiles) {
\r
2117 if (tiles.hasOwnProperty(i)) {
\r
2118 tiles[i].style.webkitTransform += ' translate(0,0)';
\r
2124 _initContainer: function () {
\r
2125 var tilePane = this._map._panes.tilePane;
\r
2127 if (!this._container || tilePane.empty) {
\r
2128 this._container = L.DomUtil.create('div', 'leaflet-layer');
\r
2130 this._updateZIndex();
\r
2132 tilePane.appendChild(this._container);
\r
2134 if (this.options.opacity < 1) {
\r
2135 this._updateOpacity();
\r
2140 _resetCallback: function (e) {
\r
2141 this._reset(e.hard);
\r
2144 _reset: function (clearOldContainer) {
\r
2146 tiles = this._tiles;
\r
2148 for (key in tiles) {
\r
2149 if (tiles.hasOwnProperty(key)) {
\r
2150 this.fire('tileunload', {tile: tiles[key]});
\r
2155 this._tilesToLoad = 0;
\r
2157 if (this.options.reuseTiles) {
\r
2158 this._unusedTiles = [];
\r
2161 if (clearOldContainer && this._container) {
\r
2162 this._container.innerHTML = "";
\r
2165 this._initContainer();
\r
2168 _update: function (e) {
\r
2170 if (!this._map) { return; }
\r
2172 var bounds = this._map.getPixelBounds(),
\r
2173 zoom = this._map.getZoom(),
\r
2174 tileSize = this.options.tileSize;
\r
2176 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
\r
2180 var nwTilePoint = new L.Point(
\r
2181 Math.floor(bounds.min.x / tileSize),
\r
2182 Math.floor(bounds.min.y / tileSize)),
\r
2183 seTilePoint = new L.Point(
\r
2184 Math.floor(bounds.max.x / tileSize),
\r
2185 Math.floor(bounds.max.y / tileSize)),
\r
2186 tileBounds = new L.Bounds(nwTilePoint, seTilePoint);
\r
2188 this._addTilesFromCenterOut(tileBounds);
\r
2190 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
\r
2191 this._removeOtherTiles(tileBounds);
\r
2195 _addTilesFromCenterOut: function (bounds) {
\r
2197 center = bounds.getCenter();
\r
2201 for (j = bounds.min.y; j <= bounds.max.y; j++) {
\r
2202 for (i = bounds.min.x; i <= bounds.max.x; i++) {
\r
2203 point = new L.Point(i, j);
\r
2205 if (this._tileShouldBeLoaded(point)) {
\r
2206 queue.push(point);
\r
2211 var tilesToLoad = queue.length;
\r
2213 if (tilesToLoad === 0) { return; }
\r
2215 // load tiles in order of their distance to center
\r
2216 queue.sort(function (a, b) {
\r
2217 return a.distanceTo(center) - b.distanceTo(center);
\r
2220 var fragment = document.createDocumentFragment();
\r
2222 // if its the first batch of tiles to load
\r
2223 if (!this._tilesToLoad) {
\r
2224 this.fire('loading');
\r
2227 this._tilesToLoad += tilesToLoad;
\r
2229 for (i = 0; i < tilesToLoad; i++) {
\r
2230 this._addTile(queue[i], fragment);
\r
2233 this._container.appendChild(fragment);
\r
2236 _tileShouldBeLoaded: function (tilePoint) {
\r
2237 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
\r
2238 return false; // already loaded
\r
2241 if (!this.options.continuousWorld) {
\r
2242 var limit = this._getWrapTileNum();
\r
2244 if (this.options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit) ||
\r
2245 tilePoint.y < 0 || tilePoint.y >= limit) {
\r
2246 return false; // exceeds world bounds
\r
2253 _removeOtherTiles: function (bounds) {
\r
2254 var kArr, x, y, key;
\r
2256 for (key in this._tiles) {
\r
2257 if (this._tiles.hasOwnProperty(key)) {
\r
2258 kArr = key.split(':');
\r
2259 x = parseInt(kArr[0], 10);
\r
2260 y = parseInt(kArr[1], 10);
\r
2262 // remove tile if it's out of bounds
\r
2263 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
\r
2264 this._removeTile(key);
\r
2270 _removeTile: function (key) {
\r
2271 var tile = this._tiles[key];
\r
2273 this.fire("tileunload", {tile: tile, url: tile.src});
\r
2275 if (this.options.reuseTiles) {
\r
2276 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
\r
2277 this._unusedTiles.push(tile);
\r
2278 } else if (tile.parentNode === this._container) {
\r
2279 this._container.removeChild(tile);
\r
2282 if (!L.Browser.android) { //For https://github.com/CloudMade/Leaflet/issues/137
\r
2283 tile.src = L.Util.emptyImageUrl;
\r
2286 delete this._tiles[key];
\r
2289 _addTile: function (tilePoint, container) {
\r
2290 var tilePos = this._getTilePos(tilePoint);
\r
2292 // get unused tile - or create a new tile
\r
2293 var tile = this._getTile();
\r
2295 // Chrome 20 layouts much faster with top/left (Verify with timeline, frames)
\r
2296 // android 4 browser has display issues with top/left and requires transform instead
\r
2297 // android 3 browser not tested
\r
2298 // android 2 browser requires top/left or tiles disappear on load or first drag (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
\r
2299 // (other browsers don't currently care) - see debug/hacks/jitter.html for an example
\r
2300 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
\r
2302 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
\r
2304 this._loadTile(tile, tilePoint);
\r
2306 if (tile.parentNode !== this._container) {
\r
2307 container.appendChild(tile);
\r
2311 _getZoomForUrl: function () {
\r
2313 var options = this.options,
\r
2314 zoom = this._map.getZoom();
\r
2316 if (options.zoomReverse) {
\r
2317 zoom = options.maxZoom - zoom;
\r
2320 return zoom + options.zoomOffset;
\r
2323 _getTilePos: function (tilePoint) {
\r
2324 var origin = this._map.getPixelOrigin(),
\r
2325 tileSize = this.options.tileSize;
\r
2327 return tilePoint.multiplyBy(tileSize).subtract(origin);
\r
2330 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
\r
2332 getTileUrl: function (tilePoint) {
\r
2333 this._adjustTilePoint(tilePoint);
\r
2335 return L.Util.template(this._url, L.Util.extend({
\r
2336 s: this._getSubdomain(tilePoint),
\r
2337 z: this._getZoomForUrl(),
\r
2340 }, this.options));
\r
2343 _getWrapTileNum: function () {
\r
2344 // TODO refactor, limit is not valid for non-standard projections
\r
2345 return Math.pow(2, this._getZoomForUrl());
\r
2348 _adjustTilePoint: function (tilePoint) {
\r
2350 var limit = this._getWrapTileNum();
\r
2352 // wrap tile coordinates
\r
2353 if (!this.options.continuousWorld && !this.options.noWrap) {
\r
2354 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
\r
2357 if (this.options.tms) {
\r
2358 tilePoint.y = limit - tilePoint.y - 1;
\r
2362 _getSubdomain: function (tilePoint) {
\r
2363 var index = (tilePoint.x + tilePoint.y) % this.options.subdomains.length;
\r
2364 return this.options.subdomains[index];
\r
2367 _createTileProto: function () {
\r
2368 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
\r
2369 img.galleryimg = 'no';
\r
2371 var tileSize = this.options.tileSize;
\r
2372 img.style.width = tileSize + 'px';
\r
2373 img.style.height = tileSize + 'px';
\r
2376 _getTile: function () {
\r
2377 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
\r
2378 var tile = this._unusedTiles.pop();
\r
2379 this._resetTile(tile);
\r
2382 return this._createTile();
\r
2385 _resetTile: function (tile) {
\r
2386 // Override if data stored on a tile needs to be cleaned up before reuse
\r
2389 _createTile: function () {
\r
2390 var tile = this._tileImg.cloneNode(false);
\r
2391 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
\r
2395 _loadTile: function (tile, tilePoint) {
\r
2396 tile._layer = this;
\r
2397 tile.onload = this._tileOnLoad;
\r
2398 tile.onerror = this._tileOnError;
\r
2400 tile.src = this.getTileUrl(tilePoint);
\r
2403 _tileLoaded: function () {
\r
2404 this._tilesToLoad--;
\r
2405 if (!this._tilesToLoad) {
\r
2406 this.fire('load');
\r
2410 _tileOnLoad: function (e) {
\r
2411 var layer = this._layer;
\r
2413 //Only if we are loading an actual image
\r
2414 if (this.src !== L.Util.emptyImageUrl) {
\r
2415 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
\r
2417 layer.fire('tileload', {
\r
2423 layer._tileLoaded();
\r
2426 _tileOnError: function (e) {
\r
2427 var layer = this._layer;
\r
2429 layer.fire('tileerror', {
\r
2434 var newUrl = layer.options.errorTileUrl;
\r
2436 this.src = newUrl;
\r
2439 layer._tileLoaded();
\r
2443 L.tileLayer = function (url, options) {
\r
2444 return new L.TileLayer(url, options);
\r
2448 L.TileLayer.WMS = L.TileLayer.extend({
\r
2450 defaultWmsParams: {
\r
2452 request: 'GetMap',
\r
2456 format: 'image/jpeg',
\r
2457 transparent: false
\r
2460 initialize: function (url, options) { // (String, Object)
\r
2464 var wmsParams = L.Util.extend({}, this.defaultWmsParams);
\r
2466 if (options.detectRetina && L.Browser.retina) {
\r
2467 wmsParams.width = wmsParams.height = this.options.tileSize * 2;
\r
2469 wmsParams.width = wmsParams.height = this.options.tileSize;
\r
2472 for (var i in options) {
\r
2473 // all keys that are not TileLayer options go to WMS params
\r
2474 if (!this.options.hasOwnProperty(i)) {
\r
2475 wmsParams[i] = options[i];
\r
2479 this.wmsParams = wmsParams;
\r
2481 L.Util.setOptions(this, options);
\r
2484 onAdd: function (map) {
\r
2486 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
\r
2487 this.wmsParams[projectionKey] = map.options.crs.code;
\r
2489 L.TileLayer.prototype.onAdd.call(this, map);
\r
2492 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
\r
2494 var map = this._map,
\r
2495 crs = map.options.crs,
\r
2496 tileSize = this.options.tileSize,
\r
2498 nwPoint = tilePoint.multiplyBy(tileSize),
\r
2499 sePoint = nwPoint.add(new L.Point(tileSize, tileSize)),
\r
2501 nw = crs.project(map.unproject(nwPoint, zoom)),
\r
2502 se = crs.project(map.unproject(sePoint, zoom)),
\r
2504 bbox = [nw.x, se.y, se.x, nw.y].join(','),
\r
2506 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
\r
2508 return url + L.Util.getParamString(this.wmsParams) + "&bbox=" + bbox;
\r
2511 setParams: function (params, noRedraw) {
\r
2513 L.Util.extend(this.wmsParams, params);
\r
2523 L.tileLayer.wms = function (url, options) {
\r
2524 return new L.TileLayer.WMS(url, options);
\r
2528 L.TileLayer.Canvas = L.TileLayer.extend({
\r
2533 initialize: function (options) {
\r
2534 L.Util.setOptions(this, options);
\r
2537 redraw: function () {
\r
2539 tiles = this._tiles;
\r
2541 for (i in tiles) {
\r
2542 if (tiles.hasOwnProperty(i)) {
\r
2543 this._redrawTile(tiles[i]);
\r
2548 _redrawTile: function (tile) {
\r
2549 this.drawTile(tile, tile._tilePoint, tile._zoom);
\r
2552 _createTileProto: function () {
\r
2553 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
\r
2555 var tileSize = this.options.tileSize;
\r
2556 proto.width = tileSize;
\r
2557 proto.height = tileSize;
\r
2560 _createTile: function () {
\r
2561 var tile = this._canvasProto.cloneNode(false);
\r
2562 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
\r
2566 _loadTile: function (tile, tilePoint, zoom) {
\r
2567 tile._layer = this;
\r
2568 tile._tilePoint = tilePoint;
\r
2569 tile._zoom = zoom;
\r
2571 this.drawTile(tile, tilePoint, zoom);
\r
2573 if (!this.options.async) {
\r
2574 this.tileDrawn(tile);
\r
2578 drawTile: function (tile, tilePoint, zoom) {
\r
2579 // override with rendering code
\r
2582 tileDrawn: function (tile) {
\r
2583 this._tileOnLoad.call(tile);
\r
2588 L.tileLayer.canvas = function (options) {
\r
2589 return new L.TileLayer.Canvas(options);
\r
2592 L.ImageOverlay = L.Class.extend({
\r
2593 includes: L.Mixin.Events,
\r
2599 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
\r
2601 this._bounds = L.latLngBounds(bounds);
\r
2603 L.Util.setOptions(this, options);
\r
2606 onAdd: function (map) {
\r
2609 if (!this._image) {
\r
2610 this._initImage();
\r
2613 map._panes.overlayPane.appendChild(this._image);
\r
2615 map.on('viewreset', this._reset, this);
\r
2617 if (map.options.zoomAnimation && L.Browser.any3d) {
\r
2618 map.on('zoomanim', this._animateZoom, this);
\r
2624 onRemove: function (map) {
\r
2625 map.getPanes().overlayPane.removeChild(this._image);
\r
2627 map.off('viewreset', this._reset, this);
\r
2629 if (map.options.zoomAnimation) {
\r
2630 map.off('zoomanim', this._animateZoom, this);
\r
2634 addTo: function (map) {
\r
2635 map.addLayer(this);
\r
2639 setOpacity: function (opacity) {
\r
2640 this.options.opacity = opacity;
\r
2641 this._updateOpacity();
\r
2645 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
\r
2646 bringToFront: function () {
\r
2647 if (this._image) {
\r
2648 this._map._panes.overlayPane.appendChild(this._image);
\r
2653 bringToBack: function () {
\r
2654 var pane = this._map._panes.overlayPane;
\r
2655 if (this._image) {
\r
2656 pane.insertBefore(this._image, pane.firstChild);
\r
2661 _initImage: function () {
\r
2662 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
\r
2664 if (this._map.options.zoomAnimation && L.Browser.any3d) {
\r
2665 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
\r
2667 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
\r
2670 this._updateOpacity();
\r
2672 //TODO createImage util method to remove duplication
\r
2673 L.Util.extend(this._image, {
\r
2675 onselectstart: L.Util.falseFn,
\r
2676 onmousemove: L.Util.falseFn,
\r
2677 onload: L.Util.bind(this._onImageLoad, this),
\r
2682 _animateZoom: function (e) {
\r
2683 var map = this._map,
\r
2684 image = this._image,
\r
2685 scale = map.getZoomScale(e.zoom),
\r
2686 nw = this._bounds.getNorthWest(),
\r
2687 se = this._bounds.getSouthEast(),
\r
2689 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
\r
2690 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
\r
2691 currentSize = map.latLngToLayerPoint(se)._subtract(map.latLngToLayerPoint(nw)),
\r
2692 origin = topLeft._add(size._subtract(currentSize)._divideBy(2));
\r
2694 image.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
\r
2697 _reset: function () {
\r
2698 var image = this._image,
\r
2699 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
\r
2700 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
\r
2702 L.DomUtil.setPosition(image, topLeft);
\r
2704 image.style.width = size.x + 'px';
\r
2705 image.style.height = size.y + 'px';
\r
2708 _onImageLoad: function () {
\r
2709 this.fire('load');
\r
2712 _updateOpacity: function () {
\r
2713 L.DomUtil.setOpacity(this._image, this.options.opacity);
\r
2717 L.imageOverlay = function (url, bounds, options) {
\r
2718 return new L.ImageOverlay(url, bounds, options);
\r
2722 L.Icon = L.Class.extend({
\r
2725 iconUrl: (String) (required)
\r
2726 iconSize: (Point) (can be set through CSS)
\r
2727 iconAnchor: (Point) (centered by default if size is specified, can be set in CSS with negative margins)
\r
2728 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
\r
2729 shadowUrl: (Point) (no shadow by default)
\r
2730 shadowSize: (Point)
\r
2731 shadowAnchor: (Point)
\r
2736 initialize: function (options) {
\r
2737 L.Util.setOptions(this, options);
\r
2740 createIcon: function () {
\r
2741 return this._createIcon('icon');
\r
2744 createShadow: function () {
\r
2745 return this._createIcon('shadow');
\r
2748 _createIcon: function (name) {
\r
2749 var src = this._getIconUrl(name);
\r
2752 if (name === 'icon') {
\r
2753 throw new Error("iconUrl not set in Icon options (see the docs).");
\r
2758 var img = this._createImg(src);
\r
2759 this._setIconStyles(img, name);
\r
2764 _setIconStyles: function (img, name) {
\r
2765 var options = this.options,
\r
2766 size = L.point(options[name + 'Size']),
\r
2769 if (name === 'shadow') {
\r
2770 anchor = L.point(options.shadowAnchor || options.iconAnchor);
\r
2772 anchor = L.point(options.iconAnchor);
\r
2775 if (!anchor && size) {
\r
2776 anchor = size.divideBy(2, true);
\r
2779 img.className = 'leaflet-marker-' + name + ' ' + options.className;
\r
2782 img.style.marginLeft = (-anchor.x) + 'px';
\r
2783 img.style.marginTop = (-anchor.y) + 'px';
\r
2787 img.style.width = size.x + 'px';
\r
2788 img.style.height = size.y + 'px';
\r
2792 _createImg: function (src) {
\r
2795 if (!L.Browser.ie6) {
\r
2796 el = document.createElement('img');
\r
2799 el = document.createElement('div');
\r
2800 el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
\r
2805 _getIconUrl: function (name) {
\r
2806 return this.options[name + 'Url'];
\r
2810 L.icon = function (options) {
\r
2811 return new L.Icon(options);
\r
2816 L.Icon.Default = L.Icon.extend({
2819 iconSize: new L.Point(25, 41),
2820 iconAnchor: new L.Point(12, 41),
2821 popupAnchor: new L.Point(1, -34),
2823 shadowSize: new L.Point(41, 41)
2826 _getIconUrl: function (name) {
2827 var key = name + 'Url';
2829 if (this.options[key]) {
2830 return this.options[key];
2833 var path = L.Icon.Default.imagePath;
2836 throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");
2839 return path + '/marker-' + name + '.png';
2843 L.Icon.Default.imagePath = (function () {
2844 var scripts = document.getElementsByTagName('script'),
2845 leafletRe = /\/?leaflet[\-\._]?([\w\-\._]*)\.js\??/;
2847 var i, len, src, matches;
2849 for (i = 0, len = scripts.length; i < len; i++) {
2850 src = scripts[i].src;
2851 matches = src.match(leafletRe);
2854 return src.split(leafletRe)[0] + '/images';
2861 * L.Marker is used to display clickable/draggable icons on the map.
\r
2864 L.Marker = L.Class.extend({
\r
2866 includes: L.Mixin.Events,
\r
2869 icon: new L.Icon.Default(),
\r
2877 initialize: function (latlng, options) {
\r
2878 L.Util.setOptions(this, options);
\r
2879 this._latlng = L.latLng(latlng);
\r
2882 onAdd: function (map) {
\r
2885 map.on('viewreset', this.update, this);
\r
2890 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
\r
2891 map.on('zoomanim', this._animateZoom, this);
\r
2895 addTo: function (map) {
\r
2896 map.addLayer(this);
\r
2900 onRemove: function (map) {
\r
2901 this._removeIcon();
\r
2903 this.fire('remove');
\r
2906 'viewreset': this.update,
\r
2907 'zoomanim': this._animateZoom
\r
2913 getLatLng: function () {
\r
2914 return this._latlng;
\r
2917 setLatLng: function (latlng) {
\r
2918 this._latlng = L.latLng(latlng);
\r
2922 this.fire('move', { latlng: this._latlng });
\r
2925 setZIndexOffset: function (offset) {
\r
2926 this.options.zIndexOffset = offset;
\r
2930 setIcon: function (icon) {
\r
2932 this._removeIcon();
\r
2935 this.options.icon = icon;
\r
2943 update: function () {
\r
2944 if (!this._icon) { return; }
\r
2946 var pos = this._map.latLngToLayerPoint(this._latlng).round();
\r
2947 this._setPos(pos);
\r
2950 _initIcon: function () {
\r
2951 var options = this.options,
\r
2953 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
\r
2954 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide',
\r
2955 needOpacityUpdate = false;
\r
2957 if (!this._icon) {
\r
2958 this._icon = options.icon.createIcon();
\r
2960 if (options.title) {
\r
2961 this._icon.title = options.title;
\r
2964 this._initInteraction();
\r
2965 needOpacityUpdate = (this.options.opacity < 1);
\r
2967 L.DomUtil.addClass(this._icon, classToAdd);
\r
2969 if (!this._shadow) {
\r
2970 this._shadow = options.icon.createShadow();
\r
2972 if (this._shadow) {
\r
2973 L.DomUtil.addClass(this._shadow, classToAdd);
\r
2974 needOpacityUpdate = (this.options.opacity < 1);
\r
2978 if (needOpacityUpdate) {
\r
2979 this._updateOpacity();
\r
2982 var panes = this._map._panes;
\r
2984 panes.markerPane.appendChild(this._icon);
\r
2986 if (this._shadow) {
\r
2987 panes.shadowPane.appendChild(this._shadow);
\r
2991 _removeIcon: function () {
\r
2992 var panes = this._map._panes;
\r
2994 panes.markerPane.removeChild(this._icon);
\r
2996 if (this._shadow) {
\r
2997 panes.shadowPane.removeChild(this._shadow);
\r
3000 this._icon = this._shadow = null;
\r
3003 _setPos: function (pos) {
\r
3004 L.DomUtil.setPosition(this._icon, pos);
\r
3006 if (this._shadow) {
\r
3007 L.DomUtil.setPosition(this._shadow, pos);
\r
3010 this._icon.style.zIndex = pos.y + this.options.zIndexOffset;
\r
3013 _animateZoom: function (opt) {
\r
3014 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
\r
3016 this._setPos(pos);
\r
3019 _initInteraction: function () {
\r
3020 if (!this.options.clickable) {
\r
3024 var icon = this._icon,
\r
3025 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout'];
\r
3027 L.DomUtil.addClass(icon, 'leaflet-clickable');
\r
3028 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
\r
3030 for (var i = 0; i < events.length; i++) {
\r
3031 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
\r
3034 if (L.Handler.MarkerDrag) {
\r
3035 this.dragging = new L.Handler.MarkerDrag(this);
\r
3037 if (this.options.draggable) {
\r
3038 this.dragging.enable();
\r
3043 _onMouseClick: function (e) {
\r
3044 if (this.hasEventListeners(e.type)) {
\r
3045 L.DomEvent.stopPropagation(e);
\r
3047 if (this.dragging && this.dragging.moved()) { return; }
\r
3048 if (this._map.dragging && this._map.dragging.moved()) { return; }
\r
3049 this.fire(e.type, {
\r
3054 _fireMouseEvent: function (e) {
\r
3055 this.fire(e.type, {
\r
3058 if (e.type !== 'mousedown') {
\r
3059 L.DomEvent.stopPropagation(e);
\r
3063 setOpacity: function (opacity) {
\r
3064 this.options.opacity = opacity;
\r
3066 this._updateOpacity();
\r
3070 _updateOpacity: function () {
\r
3071 L.DomUtil.setOpacity(this._icon, this.options.opacity);
\r
3072 if (this._shadow) {
\r
3073 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
\r
3078 L.marker = function (latlng, options) {
\r
3079 return new L.Marker(latlng, options);
\r
3083 L.DivIcon = L.Icon.extend({
3085 iconSize: new L.Point(12, 12), // also can be set through CSS
3088 popupAnchor: (Point)
3092 className: 'leaflet-div-icon'
3095 createIcon: function () {
3096 var div = document.createElement('div'),
3097 options = this.options;
3100 div.innerHTML = options.html;
3103 if (options.bgPos) {
3104 div.style.backgroundPosition =
3105 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3108 this._setIconStyles(div, 'icon');
3112 createShadow: function () {
3117 L.divIcon = function (options) {
3118 return new L.DivIcon(options);
3123 L.Map.mergeOptions({
\r
3124 closePopupOnClick: true
\r
3127 L.Popup = L.Class.extend({
\r
3128 includes: L.Mixin.Events,
\r
3135 closeButton: true,
\r
3136 offset: new L.Point(0, 6),
\r
3137 autoPanPadding: new L.Point(5, 5),
\r
3141 initialize: function (options, source) {
\r
3142 L.Util.setOptions(this, options);
\r
3144 this._source = source;
\r
3147 onAdd: function (map) {
\r
3150 if (!this._container) {
\r
3151 this._initLayout();
\r
3153 this._updateContent();
\r
3155 var animFade = map.options.fadeAnimation;
\r
3158 L.DomUtil.setOpacity(this._container, 0);
\r
3160 map._panes.popupPane.appendChild(this._container);
\r
3162 map.on('viewreset', this._updatePosition, this);
\r
3164 if (L.Browser.any3d) {
\r
3165 map.on('zoomanim', this._zoomAnimation, this);
\r
3168 if (map.options.closePopupOnClick) {
\r
3169 map.on('preclick', this._close, this);
\r
3175 L.DomUtil.setOpacity(this._container, 1);
\r
3179 addTo: function (map) {
\r
3180 map.addLayer(this);
\r
3184 openOn: function (map) {
\r
3185 map.openPopup(this);
\r
3189 onRemove: function (map) {
\r
3190 map._panes.popupPane.removeChild(this._container);
\r
3192 L.Util.falseFn(this._container.offsetWidth); // force reflow
\r
3195 viewreset: this._updatePosition,
\r
3196 preclick: this._close,
\r
3197 zoomanim: this._zoomAnimation
\r
3200 if (map.options.fadeAnimation) {
\r
3201 L.DomUtil.setOpacity(this._container, 0);
\r
3207 setLatLng: function (latlng) {
\r
3208 this._latlng = L.latLng(latlng);
\r
3213 setContent: function (content) {
\r
3214 this._content = content;
\r
3219 _close: function () {
\r
3220 var map = this._map;
\r
3223 map._popup = null;
\r
3226 .removeLayer(this)
\r
3227 .fire('popupclose', {popup: this});
\r
3231 _initLayout: function () {
\r
3232 var prefix = 'leaflet-popup',
\r
3233 container = this._container = L.DomUtil.create('div', prefix + ' ' + this.options.className + ' leaflet-zoom-animated'),
\r
3236 if (this.options.closeButton) {
\r
3237 closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
\r
3238 closeButton.href = '#close';
\r
3239 closeButton.innerHTML = '×';
\r
3241 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
\r
3244 var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
\r
3245 L.DomEvent.disableClickPropagation(wrapper);
\r
3247 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
\r
3248 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
\r
3250 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
\r
3251 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
\r
3254 _update: function () {
\r
3255 if (!this._map) { return; }
\r
3257 this._container.style.visibility = 'hidden';
\r
3259 this._updateContent();
\r
3260 this._updateLayout();
\r
3261 this._updatePosition();
\r
3263 this._container.style.visibility = '';
\r
3265 this._adjustPan();
\r
3268 _updateContent: function () {
\r
3269 if (!this._content) { return; }
\r
3271 if (typeof this._content === 'string') {
\r
3272 this._contentNode.innerHTML = this._content;
\r
3274 while (this._contentNode.hasChildNodes()) {
\r
3275 this._contentNode.removeChild(this._contentNode.firstChild);
\r
3277 this._contentNode.appendChild(this._content);
\r
3279 this.fire('contentupdate');
\r
3282 _updateLayout: function () {
\r
3283 var container = this._contentNode,
\r
3284 style = container.style;
\r
3287 style.whiteSpace = 'nowrap';
\r
3289 var width = container.offsetWidth;
\r
3290 width = Math.min(width, this.options.maxWidth);
\r
3291 width = Math.max(width, this.options.minWidth);
\r
3293 style.width = (width + 1) + 'px';
\r
3294 style.whiteSpace = '';
\r
3296 style.height = '';
\r
3298 var height = container.offsetHeight,
\r
3299 maxHeight = this.options.maxHeight,
\r
3300 scrolledClass = 'leaflet-popup-scrolled';
\r
3302 if (maxHeight && height > maxHeight) {
\r
3303 style.height = maxHeight + 'px';
\r
3304 L.DomUtil.addClass(container, scrolledClass);
\r
3306 L.DomUtil.removeClass(container, scrolledClass);
\r
3309 this._containerWidth = this._container.offsetWidth;
\r
3312 _updatePosition: function () {
\r
3313 var pos = this._map.latLngToLayerPoint(this._latlng),
\r
3314 is3d = L.Browser.any3d,
\r
3315 offset = this.options.offset;
\r
3318 L.DomUtil.setPosition(this._container, pos);
\r
3321 this._containerBottom = -offset.y - (is3d ? 0 : pos.y);
\r
3322 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (is3d ? 0 : pos.x);
\r
3324 //Bottom position the popup in case the height of the popup changes (images loading etc)
\r
3325 this._container.style.bottom = this._containerBottom + 'px';
\r
3326 this._container.style.left = this._containerLeft + 'px';
\r
3329 _zoomAnimation: function (opt) {
\r
3330 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
\r
3332 L.DomUtil.setPosition(this._container, pos);
\r
3335 _adjustPan: function () {
\r
3336 if (!this.options.autoPan) { return; }
\r
3338 var map = this._map,
\r
3339 containerHeight = this._container.offsetHeight,
\r
3340 containerWidth = this._containerWidth,
\r
3342 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
\r
3344 if (L.Browser.any3d) {
\r
3345 layerPos._add(L.DomUtil.getPosition(this._container));
\r
3348 var containerPos = map.layerPointToContainerPoint(layerPos),
\r
3349 padding = this.options.autoPanPadding,
\r
3350 size = map.getSize(),
\r
3354 if (containerPos.x < 0) {
\r
3355 dx = containerPos.x - padding.x;
\r
3357 if (containerPos.x + containerWidth > size.x) {
\r
3358 dx = containerPos.x + containerWidth - size.x + padding.x;
\r
3360 if (containerPos.y < 0) {
\r
3361 dy = containerPos.y - padding.y;
\r
3363 if (containerPos.y + containerHeight > size.y) {
\r
3364 dy = containerPos.y + containerHeight - size.y + padding.y;
\r
3368 map.panBy(new L.Point(dx, dy));
\r
3372 _onCloseButtonClick: function (e) {
\r
3374 L.DomEvent.stop(e);
\r
3378 L.popup = function (options, source) {
\r
3379 return new L.Popup(options, source);
\r
3384 * Popup extension to L.Marker, adding openPopup & bindPopup methods.
\r
3387 L.Marker.include({
\r
3388 openPopup: function () {
\r
3389 if (this._popup && this._map) {
\r
3390 this._popup.setLatLng(this._latlng);
\r
3391 this._map.openPopup(this._popup);
\r
3397 closePopup: function () {
\r
3398 if (this._popup) {
\r
3399 this._popup._close();
\r
3404 bindPopup: function (content, options) {
\r
3405 var anchor = L.point(this.options.icon.options.popupAnchor) || new L.Point(0, 0);
\r
3407 anchor = anchor.add(L.Popup.prototype.options.offset);
\r
3409 if (options && options.offset) {
\r
3410 anchor = anchor.add(options.offset);
\r
3413 options = L.Util.extend({offset: anchor}, options);
\r
3415 if (!this._popup) {
\r
3417 .on('click', this.openPopup, this)
\r
3418 .on('remove', this.closePopup, this)
\r
3419 .on('move', this._movePopup, this);
\r
3422 this._popup = new L.Popup(options, this)
\r
3423 .setContent(content);
\r
3428 unbindPopup: function () {
\r
3429 if (this._popup) {
\r
3430 this._popup = null;
\r
3432 .off('click', this.openPopup)
\r
3433 .off('remove', this.closePopup)
\r
3434 .off('move', this._movePopup);
\r
3439 _movePopup: function (e) {
\r
3440 this._popup.setLatLng(e.latlng);
\r
3447 openPopup: function (popup) {
\r
3448 this.closePopup();
\r
3450 this._popup = popup;
\r
3454 .fire('popupopen', {popup: this._popup});
\r
3457 closePopup: function () {
\r
3458 if (this._popup) {
\r
3459 this._popup._close();
\r
3466 * L.LayerGroup is a class to combine several layers so you can manipulate the group (e.g. add/remove it) as one layer.
\r
3469 L.LayerGroup = L.Class.extend({
\r
3470 initialize: function (layers) {
\r
3471 this._layers = {};
\r
3476 for (i = 0, len = layers.length; i < len; i++) {
\r
3477 this.addLayer(layers[i]);
\r
3482 addLayer: function (layer) {
\r
3483 var id = L.Util.stamp(layer);
\r
3485 this._layers[id] = layer;
\r
3488 this._map.addLayer(layer);
\r
3494 removeLayer: function (layer) {
\r
3495 var id = L.Util.stamp(layer);
\r
3497 delete this._layers[id];
\r
3500 this._map.removeLayer(layer);
\r
3506 clearLayers: function () {
\r
3507 this.eachLayer(this.removeLayer, this);
\r
3511 invoke: function (methodName) {
\r
3512 var args = Array.prototype.slice.call(arguments, 1),
\r
3515 for (i in this._layers) {
\r
3516 if (this._layers.hasOwnProperty(i)) {
\r
3517 layer = this._layers[i];
\r
3519 if (layer[methodName]) {
\r
3520 layer[methodName].apply(layer, args);
\r
3528 onAdd: function (map) {
\r
3530 this.eachLayer(map.addLayer, map);
\r
3533 onRemove: function (map) {
\r
3534 this.eachLayer(map.removeLayer, map);
\r
3538 addTo: function (map) {
\r
3539 map.addLayer(this);
\r
3543 eachLayer: function (method, context) {
\r
3544 for (var i in this._layers) {
\r
3545 if (this._layers.hasOwnProperty(i)) {
\r
3546 method.call(context, this._layers[i]);
\r
3552 L.layerGroup = function (layers) {
\r
3553 return new L.LayerGroup(layers);
\r
3558 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and bindPopup method shared between a group of layers.
\r
3561 L.FeatureGroup = L.LayerGroup.extend({
\r
3562 includes: L.Mixin.Events,
\r
3564 addLayer: function (layer) {
\r
3565 if (this._layers[L.Util.stamp(layer)]) {
\r
3569 layer.on('click dblclick mouseover mouseout mousemove contextmenu', this._propagateEvent, this);
\r
3571 L.LayerGroup.prototype.addLayer.call(this, layer);
\r
3573 if (this._popupContent && layer.bindPopup) {
\r
3574 layer.bindPopup(this._popupContent);
\r
3580 removeLayer: function (layer) {
\r
3581 layer.off('click dblclick mouseover mouseout mousemove contextmenu', this._propagateEvent, this);
\r
3583 L.LayerGroup.prototype.removeLayer.call(this, layer);
\r
3585 if (this._popupContent) {
\r
3586 return this.invoke('unbindPopup');
\r
3592 bindPopup: function (content) {
\r
3593 this._popupContent = content;
\r
3594 return this.invoke('bindPopup', content);
\r
3597 setStyle: function (style) {
\r
3598 return this.invoke('setStyle', style);
\r
3601 bringToFront: function () {
\r
3602 return this.invoke('bringToFront');
\r
3605 bringToBack: function () {
\r
3606 return this.invoke('bringToBack');
\r
3609 getBounds: function () {
\r
3610 var bounds = new L.LatLngBounds();
\r
3611 this.eachLayer(function (layer) {
\r
3612 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
\r
3617 _propagateEvent: function (e) {
\r
3618 e.layer = e.target;
\r
3621 this.fire(e.type, e);
\r
3625 L.featureGroup = function (layers) {
\r
3626 return new L.FeatureGroup(layers);
\r
3631 * L.Path is a base class for rendering vector paths on a map. It's inherited by Polyline, Circle, etc.
\r
3634 L.Path = L.Class.extend({
\r
3635 includes: [L.Mixin.Events],
\r
3638 // how much to extend the clip area around the map view
\r
3639 // (relative to its size, e.g. 0.5 is half the screen in each direction)
\r
3640 // set in such way that SVG element doesn't exceed 1280px (vector layers flicker on dragend if it is)
\r
3641 CLIP_PADDING: L.Browser.mobile ?
\r
3642 Math.max(0, Math.min(0.5,
\r
3643 (1280 / Math.max(window.innerWidth, window.innerHeight) - 1) / 2))
\r
3655 fillColor: null, //same as color by default
\r
3661 initialize: function (options) {
\r
3662 L.Util.setOptions(this, options);
\r
3665 onAdd: function (map) {
\r
3668 if (!this._container) {
\r
3669 this._initElements();
\r
3670 this._initEvents();
\r
3673 this.projectLatlngs();
\r
3674 this._updatePath();
\r
3676 if (this._container) {
\r
3677 this._map._pathRoot.appendChild(this._container);
\r
3681 'viewreset': this.projectLatlngs,
\r
3682 'moveend': this._updatePath
\r
3686 addTo: function (map) {
\r
3687 map.addLayer(this);
\r
3691 onRemove: function (map) {
\r
3692 map._pathRoot.removeChild(this._container);
\r
3696 if (L.Browser.vml) {
\r
3697 this._container = null;
\r
3698 this._stroke = null;
\r
3699 this._fill = null;
\r
3702 this.fire('remove');
\r
3705 'viewreset': this.projectLatlngs,
\r
3706 'moveend': this._updatePath
\r
3710 projectLatlngs: function () {
\r
3711 // do all projection stuff here
\r
3714 setStyle: function (style) {
\r
3715 L.Util.setOptions(this, style);
\r
3717 if (this._container) {
\r
3718 this._updateStyle();
\r
3724 redraw: function () {
\r
3726 this.projectLatlngs();
\r
3727 this._updatePath();
\r
3734 _updatePathViewport: function () {
\r
3735 var p = L.Path.CLIP_PADDING,
\r
3736 size = this.getSize(),
\r
3737 panePos = L.DomUtil.getPosition(this._mapPane),
\r
3738 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
\r
3739 max = min.add(size.multiplyBy(1 + p * 2)._round());
\r
3741 this._pathViewport = new L.Bounds(min, max);
\r
3746 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
\r
3748 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
\r
3750 L.Path = L.Path.extend({
\r
3752 SVG: L.Browser.svg
\r
3755 bringToFront: function () {
\r
3756 var root = this._map._pathRoot,
\r
3757 path = this._container;
\r
3759 if (path && root.lastChild !== path) {
\r
3760 root.appendChild(path);
\r
3765 bringToBack: function () {
\r
3766 var root = this._map._pathRoot,
\r
3767 path = this._container,
\r
3768 first = root.firstChild;
\r
3770 if (path && first !== path) {
\r
3771 root.insertBefore(path, first);
\r
3776 getPathString: function () {
\r
3777 // form path string here
\r
3780 _createElement: function (name) {
\r
3781 return document.createElementNS(L.Path.SVG_NS, name);
\r
3784 _initElements: function () {
\r
3785 this._map._initPathRoot();
\r
3787 this._initStyle();
\r
3790 _initPath: function () {
\r
3791 this._container = this._createElement('g');
\r
3793 this._path = this._createElement('path');
\r
3794 this._container.appendChild(this._path);
\r
3797 _initStyle: function () {
\r
3798 if (this.options.stroke) {
\r
3799 this._path.setAttribute('stroke-linejoin', 'round');
\r
3800 this._path.setAttribute('stroke-linecap', 'round');
\r
3802 if (this.options.fill) {
\r
3803 this._path.setAttribute('fill-rule', 'evenodd');
\r
3805 this._updateStyle();
\r
3808 _updateStyle: function () {
\r
3809 if (this.options.stroke) {
\r
3810 this._path.setAttribute('stroke', this.options.color);
\r
3811 this._path.setAttribute('stroke-opacity', this.options.opacity);
\r
3812 this._path.setAttribute('stroke-width', this.options.weight);
\r
3813 if (this.options.dashArray) {
\r
3814 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
\r
3816 this._path.removeAttribute('stroke-dasharray');
\r
3819 this._path.setAttribute('stroke', 'none');
\r
3821 if (this.options.fill) {
\r
3822 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
\r
3823 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
\r
3825 this._path.setAttribute('fill', 'none');
\r
3829 _updatePath: function () {
\r
3830 var str = this.getPathString();
\r
3832 // fix webkit empty string parsing bug
\r
3835 this._path.setAttribute('d', str);
\r
3838 // TODO remove duplication with L.Map
\r
3839 _initEvents: function () {
\r
3840 if (this.options.clickable) {
\r
3841 if (L.Browser.svg || !L.Browser.vml) {
\r
3842 this._path.setAttribute('class', 'leaflet-clickable');
\r
3845 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
\r
3847 var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'mousemove', 'contextmenu'];
\r
3848 for (var i = 0; i < events.length; i++) {
\r
3849 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
\r
3854 _onMouseClick: function (e) {
\r
3855 if (this._map.dragging && this._map.dragging.moved()) {
\r
3859 this._fireMouseEvent(e);
\r
3862 _fireMouseEvent: function (e) {
\r
3863 if (!this.hasEventListeners(e.type)) {
\r
3867 var map = this._map,
\r
3868 containerPoint = map.mouseEventToContainerPoint(e),
\r
3869 layerPoint = map.containerPointToLayerPoint(containerPoint),
\r
3870 latlng = map.layerPointToLatLng(layerPoint);
\r
3872 this.fire(e.type, {
\r
3874 layerPoint: layerPoint,
\r
3875 containerPoint: containerPoint,
\r
3879 if (e.type === 'contextmenu') {
\r
3880 L.DomEvent.preventDefault(e);
\r
3882 L.DomEvent.stopPropagation(e);
\r
3887 _initPathRoot: function () {
\r
3888 if (!this._pathRoot) {
\r
3889 this._pathRoot = L.Path.prototype._createElement('svg');
\r
3890 this._panes.overlayPane.appendChild(this._pathRoot);
\r
3892 if (this.options.zoomAnimation && L.Browser.any3d) {
\r
3893 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
\r
3896 'zoomanim': this._animatePathZoom,
\r
3897 'zoomend': this._endPathZoom
\r
3900 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
\r
3903 this.on('moveend', this._updateSvgViewport);
\r
3904 this._updateSvgViewport();
\r
3908 _animatePathZoom: function (opt) {
\r
3909 var scale = this.getZoomScale(opt.zoom),
\r
3910 offset = this._getCenterOffset(opt.center).divideBy(1 - 1 / scale),
\r
3911 viewportPos = this.containerPointToLayerPoint(this.getSize().multiplyBy(-L.Path.CLIP_PADDING)),
\r
3912 origin = viewportPos.add(offset).round();
\r
3914 this._pathRoot.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString((origin.multiplyBy(-1).add(L.DomUtil.getPosition(this._pathRoot)).multiplyBy(scale).add(origin))) + ' scale(' + scale + ') ';
\r
3916 this._pathZooming = true;
\r
3919 _endPathZoom: function () {
\r
3920 this._pathZooming = false;
\r
3923 _updateSvgViewport: function () {
\r
3924 if (this._pathZooming) {
\r
3925 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
\r
3926 // When the zoom animation ends we will be updated again anyway
\r
3927 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
\r
3931 this._updatePathViewport();
\r
3933 var vp = this._pathViewport,
\r
3936 width = max.x - min.x,
\r
3937 height = max.y - min.y,
\r
3938 root = this._pathRoot,
\r
3939 pane = this._panes.overlayPane;
\r
3941 // Hack to make flicker on drag end on mobile webkit less irritating
\r
3942 if (L.Browser.mobileWebkit) {
\r
3943 pane.removeChild(root);
\r
3946 L.DomUtil.setPosition(root, min);
\r
3947 root.setAttribute('width', width);
\r
3948 root.setAttribute('height', height);
\r
3949 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
\r
3951 if (L.Browser.mobileWebkit) {
\r
3952 pane.appendChild(root);
\r
3959 * Popup extension to L.Path (polylines, polygons, circles), adding bindPopup method.
\r
3964 bindPopup: function (content, options) {
\r
3966 if (!this._popup || this._popup.options !== options) {
\r
3967 this._popup = new L.Popup(options, this);
\r
3970 this._popup.setContent(content);
\r
3972 if (!this._popupHandlersAdded) {
\r
3974 .on('click', this._openPopup, this)
\r
3975 .on('remove', this._closePopup, this);
\r
3976 this._popupHandlersAdded = true;
\r
3982 unbindPopup: function () {
\r
3983 if (this._popup) {
\r
3984 this._popup = null;
\r
3986 .off('click', this.openPopup)
\r
3987 .off('remove', this.closePopup);
\r
3992 openPopup: function (latlng) {
\r
3994 if (this._popup) {
\r
3995 latlng = latlng || this._latlng ||
\r
3996 this._latlngs[Math.floor(this._latlngs.length / 2)];
\r
3998 this._openPopup({latlng: latlng});
\r
4004 _openPopup: function (e) {
\r
4005 this._popup.setLatLng(e.latlng);
\r
4006 this._map.openPopup(this._popup);
\r
4009 _closePopup: function () {
\r
4010 this._popup._close();
\r
4016 * Vector rendering for IE6-8 through VML.
\r
4017 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
\r
4020 L.Browser.vml = !L.Browser.svg && (function () {
\r
4022 var div = document.createElement('div');
\r
4023 div.innerHTML = '<v:shape adj="1"/>';
\r
4025 var shape = div.firstChild;
\r
4026 shape.style.behavior = 'url(#default#VML)';
\r
4028 return shape && (typeof shape.adj === 'object');
\r
4034 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
\r
4037 CLIP_PADDING: 0.02
\r
4040 _createElement: (function () {
\r
4042 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
\r
4043 return function (name) {
\r
4044 return document.createElement('<lvml:' + name + ' class="lvml">');
\r
4047 return function (name) {
\r
4048 return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
\r
4053 _initPath: function () {
\r
4054 var container = this._container = this._createElement('shape');
\r
4055 L.DomUtil.addClass(container, 'leaflet-vml-shape');
\r
4056 if (this.options.clickable) {
\r
4057 L.DomUtil.addClass(container, 'leaflet-clickable');
\r
4059 container.coordsize = '1 1';
\r
4061 this._path = this._createElement('path');
\r
4062 container.appendChild(this._path);
\r
4064 this._map._pathRoot.appendChild(container);
\r
4067 _initStyle: function () {
\r
4068 this._updateStyle();
\r
4071 _updateStyle: function () {
\r
4072 var stroke = this._stroke,
\r
4073 fill = this._fill,
\r
4074 options = this.options,
\r
4075 container = this._container;
\r
4077 container.stroked = options.stroke;
\r
4078 container.filled = options.fill;
\r
4080 if (options.stroke) {
\r
4082 stroke = this._stroke = this._createElement('stroke');
\r
4083 stroke.endcap = 'round';
\r
4084 container.appendChild(stroke);
\r
4086 stroke.weight = options.weight + 'px';
\r
4087 stroke.color = options.color;
\r
4088 stroke.opacity = options.opacity;
\r
4089 if (options.dashArray) {
\r
4090 stroke.dashStyle = options.dashArray.replace(/ *, */g, ' ');
\r
4092 stroke.dashStyle = '';
\r
4094 } else if (stroke) {
\r
4095 container.removeChild(stroke);
\r
4096 this._stroke = null;
\r
4099 if (options.fill) {
\r
4101 fill = this._fill = this._createElement('fill');
\r
4102 container.appendChild(fill);
\r
4104 fill.color = options.fillColor || options.color;
\r
4105 fill.opacity = options.fillOpacity;
\r
4106 } else if (fill) {
\r
4107 container.removeChild(fill);
\r
4108 this._fill = null;
\r
4112 _updatePath: function () {
\r
4113 var style = this._container.style;
\r
4115 style.display = 'none';
\r
4116 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
\r
4117 style.display = '';
\r
4121 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
\r
4122 _initPathRoot: function () {
\r
4123 if (this._pathRoot) { return; }
\r
4125 var root = this._pathRoot = document.createElement('div');
\r
4126 root.className = 'leaflet-vml-container';
\r
4127 this._panes.overlayPane.appendChild(root);
\r
4129 this.on('moveend', this._updatePathViewport);
\r
4130 this._updatePathViewport();
\r
4136 * Vector rendering for all browsers that support canvas.
\r
4139 L.Browser.canvas = (function () {
\r
4140 return !!document.createElement('canvas').getContext;
\r
4143 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
\r
4145 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
\r
4150 redraw: function () {
\r
4152 this.projectLatlngs();
\r
4153 this._requestUpdate();
\r
4158 setStyle: function (style) {
\r
4159 L.Util.setOptions(this, style);
\r
4162 this._updateStyle();
\r
4163 this._requestUpdate();
\r
4168 onRemove: function (map) {
\r
4170 .off('viewreset', this.projectLatlngs, this)
\r
4171 .off('moveend', this._updatePath, this);
\r
4173 this._requestUpdate();
\r
4178 _requestUpdate: function () {
\r
4179 if (this._map && !L.Path._updateRequest) {
\r
4180 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
\r
4184 _fireMapMoveEnd: function () {
\r
4185 L.Path._updateRequest = null;
\r
4186 this.fire('moveend');
\r
4189 _initElements: function () {
\r
4190 this._map._initPathRoot();
\r
4191 this._ctx = this._map._canvasCtx;
\r
4194 _updateStyle: function () {
\r
4195 var options = this.options;
\r
4197 if (options.stroke) {
\r
4198 this._ctx.lineWidth = options.weight;
\r
4199 this._ctx.strokeStyle = options.color;
\r
4201 if (options.fill) {
\r
4202 this._ctx.fillStyle = options.fillColor || options.color;
\r
4206 _drawPath: function () {
\r
4207 var i, j, len, len2, point, drawMethod;
\r
4209 this._ctx.beginPath();
\r
4211 for (i = 0, len = this._parts.length; i < len; i++) {
\r
4212 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
\r
4213 point = this._parts[i][j];
\r
4214 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
\r
4216 this._ctx[drawMethod](point.x, point.y);
\r
4218 // TODO refactor ugly hack
\r
4219 if (this instanceof L.Polygon) {
\r
4220 this._ctx.closePath();
\r
4225 _checkIfEmpty: function () {
\r
4226 return !this._parts.length;
\r
4229 _updatePath: function () {
\r
4230 if (this._checkIfEmpty()) { return; }
\r
4232 var ctx = this._ctx,
\r
4233 options = this.options;
\r
4237 this._updateStyle();
\r
4239 if (options.fill) {
\r
4240 if (options.fillOpacity < 1) {
\r
4241 ctx.globalAlpha = options.fillOpacity;
\r
4246 if (options.stroke) {
\r
4247 if (options.opacity < 1) {
\r
4248 ctx.globalAlpha = options.opacity;
\r
4255 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
\r
4258 _initEvents: function () {
\r
4259 if (this.options.clickable) {
\r
4260 // TODO hand cursor
\r
4261 // TODO mouseover, mouseout, dblclick
\r
4262 this._map.on('click', this._onClick, this);
\r
4266 _onClick: function (e) {
\r
4267 if (this._containsPoint(e.layerPoint)) {
\r
4268 this.fire('click', e);
\r
4273 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
\r
4274 _initPathRoot: function () {
\r
4275 var root = this._pathRoot,
\r
4279 root = this._pathRoot = document.createElement("canvas");
\r
4280 root.style.position = 'absolute';
\r
4281 ctx = this._canvasCtx = root.getContext('2d');
\r
4283 ctx.lineCap = "round";
\r
4284 ctx.lineJoin = "round";
\r
4286 this._panes.overlayPane.appendChild(root);
\r
4288 if (this.options.zoomAnimation) {
\r
4289 this._pathRoot.className = 'leaflet-zoom-animated';
\r
4290 this.on('zoomanim', this._animatePathZoom);
\r
4291 this.on('zoomend', this._endPathZoom);
\r
4293 this.on('moveend', this._updateCanvasViewport);
\r
4294 this._updateCanvasViewport();
\r
4298 _updateCanvasViewport: function () {
\r
4299 if (this._pathZooming) {
\r
4300 //Don't redraw while zooming. See _updateSvgViewport for more details
\r
4303 this._updatePathViewport();
\r
4305 var vp = this._pathViewport,
\r
4307 size = vp.max.subtract(min),
\r
4308 root = this._pathRoot;
\r
4310 //TODO check if this works properly on mobile webkit
\r
4311 L.DomUtil.setPosition(root, min);
\r
4312 root.width = size.x;
\r
4313 root.height = size.y;
\r
4314 root.getContext('2d').translate(-min.x, -min.y);
\r
4320 * L.LineUtil contains different utility functions for line segments
\r
4321 * and polylines (clipping, simplification, distances, etc.)
\r
4326 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
\r
4327 // Improves rendering performance dramatically by lessening the number of points to draw.
\r
4329 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
\r
4330 if (!tolerance || !points.length) {
\r
4331 return points.slice();
\r
4334 var sqTolerance = tolerance * tolerance;
\r
4336 // stage 1: vertex reduction
\r
4337 points = this._reducePoints(points, sqTolerance);
\r
4339 // stage 2: Douglas-Peucker simplification
\r
4340 points = this._simplifyDP(points, sqTolerance);
\r
4345 // distance from a point to a segment between two points
\r
4346 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
\r
4347 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
\r
4350 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
\r
4351 return this._sqClosestPointOnSegment(p, p1, p2);
\r
4354 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
\r
4355 _simplifyDP: function (points, sqTolerance) {
\r
4357 var len = points.length,
\r
4358 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
\r
4359 markers = new ArrayConstructor(len);
\r
4361 markers[0] = markers[len - 1] = 1;
\r
4363 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
\r
4368 for (i = 0; i < len; i++) {
\r
4370 newPoints.push(points[i]);
\r
4377 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
\r
4379 var maxSqDist = 0,
\r
4382 for (i = first + 1; i <= last - 1; i++) {
\r
4383 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
\r
4385 if (sqDist > maxSqDist) {
\r
4387 maxSqDist = sqDist;
\r
4391 if (maxSqDist > sqTolerance) {
\r
4392 markers[index] = 1;
\r
4394 this._simplifyDPStep(points, markers, sqTolerance, first, index);
\r
4395 this._simplifyDPStep(points, markers, sqTolerance, index, last);
\r
4399 // reduce points that are too close to each other to a single point
\r
4400 _reducePoints: function (points, sqTolerance) {
\r
4401 var reducedPoints = [points[0]];
\r
4403 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
\r
4404 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
\r
4405 reducedPoints.push(points[i]);
\r
4409 if (prev < len - 1) {
\r
4410 reducedPoints.push(points[len - 1]);
\r
4412 return reducedPoints;
\r
4415 /*jshint bitwise:false */ // temporarily allow bitwise oprations
\r
4417 // Cohen-Sutherland line clipping algorithm.
\r
4418 // Used to avoid rendering parts of a polyline that are not currently visible.
\r
4420 clipSegment: function (a, b, bounds, useLastCode) {
\r
4421 var min = bounds.min,
\r
4424 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
\r
4425 codeB = this._getBitCode(b, bounds);
\r
4427 // save 2nd code to avoid calculating it on the next segment
\r
4428 this._lastCode = codeB;
\r
4431 // if a,b is inside the clip window (trivial accept)
\r
4432 if (!(codeA | codeB)) {
\r
4434 // if a,b is outside the clip window (trivial reject)
\r
4435 } else if (codeA & codeB) {
\r
4439 var codeOut = codeA || codeB,
\r
4440 p = this._getEdgeIntersection(a, b, codeOut, bounds),
\r
4441 newCode = this._getBitCode(p, bounds);
\r
4443 if (codeOut === codeA) {
\r
4454 _getEdgeIntersection: function (a, b, code, bounds) {
\r
4455 var dx = b.x - a.x,
\r
4460 if (code & 8) { // top
\r
4461 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
\r
4462 } else if (code & 4) { // bottom
\r
4463 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
\r
4464 } else if (code & 2) { // right
\r
4465 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
\r
4466 } else if (code & 1) { // left
\r
4467 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
\r
4471 _getBitCode: function (/*Point*/ p, bounds) {
\r
4474 if (p.x < bounds.min.x) { // left
\r
4476 } else if (p.x > bounds.max.x) { // right
\r
4479 if (p.y < bounds.min.y) { // bottom
\r
4481 } else if (p.y > bounds.max.y) { // top
\r
4488 /*jshint bitwise:true */
\r
4490 // square distance (to avoid unnecessary Math.sqrt calls)
\r
4491 _sqDist: function (p1, p2) {
\r
4492 var dx = p2.x - p1.x,
\r
4494 return dx * dx + dy * dy;
\r
4497 // return closest point on segment or distance to that point
\r
4498 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
\r
4503 dot = dx * dx + dy * dy,
\r
4507 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
\r
4512 } else if (t > 0) {
\r
4521 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
\r
4526 L.Polyline = L.Path.extend({
\r
4527 initialize: function (latlngs, options) {
\r
4528 L.Path.prototype.initialize.call(this, options);
\r
4530 this._latlngs = this._convertLatLngs(latlngs);
\r
4532 // TODO refactor: move to Polyline.Edit.js
\r
4533 if (L.Handler.PolyEdit) {
\r
4534 this.editing = new L.Handler.PolyEdit(this);
\r
4536 if (this.options.editable) {
\r
4537 this.editing.enable();
\r
4543 // how much to simplify the polyline on each zoom level
\r
4544 // more = better performance and smoother look, less = more accurate
\r
4545 smoothFactor: 1.0,
\r
4549 projectLatlngs: function () {
\r
4550 this._originalPoints = [];
\r
4552 for (var i = 0, len = this._latlngs.length; i < len; i++) {
\r
4553 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
\r
4557 getPathString: function () {
\r
4558 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
\r
4559 str += this._getPathPartStr(this._parts[i]);
\r
4564 getLatLngs: function () {
\r
4565 return this._latlngs;
\r
4568 setLatLngs: function (latlngs) {
\r
4569 this._latlngs = this._convertLatLngs(latlngs);
\r
4570 return this.redraw();
\r
4573 addLatLng: function (latlng) {
\r
4574 this._latlngs.push(L.latLng(latlng));
\r
4575 return this.redraw();
\r
4578 spliceLatLngs: function (index, howMany) {
\r
4579 var removed = [].splice.apply(this._latlngs, arguments);
\r
4580 this._convertLatLngs(this._latlngs);
\r
4585 closestLayerPoint: function (p) {
\r
4586 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
\r
4588 for (var j = 0, jLen = parts.length; j < jLen; j++) {
\r
4589 var points = parts[j];
\r
4590 for (var i = 1, len = points.length; i < len; i++) {
\r
4591 p1 = points[i - 1];
\r
4593 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
\r
4594 if (sqDist < minDistance) {
\r
4595 minDistance = sqDist;
\r
4596 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
\r
4601 minPoint.distance = Math.sqrt(minDistance);
\r
4606 getBounds: function () {
\r
4607 var b = new L.LatLngBounds();
\r
4608 var latLngs = this.getLatLngs();
\r
4609 for (var i = 0, len = latLngs.length; i < len; i++) {
\r
4610 b.extend(latLngs[i]);
\r
4615 // TODO refactor: move to Polyline.Edit.js
\r
4616 onAdd: function (map) {
\r
4617 L.Path.prototype.onAdd.call(this, map);
\r
4619 if (this.editing && this.editing.enabled()) {
\r
4620 this.editing.addHooks();
\r
4624 onRemove: function (map) {
\r
4625 if (this.editing && this.editing.enabled()) {
\r
4626 this.editing.removeHooks();
\r
4629 L.Path.prototype.onRemove.call(this, map);
\r
4632 _convertLatLngs: function (latlngs) {
\r
4634 for (i = 0, len = latlngs.length; i < len; i++) {
\r
4635 if (latlngs[i] instanceof Array && typeof latlngs[i][0] !== 'number') {
\r
4638 latlngs[i] = L.latLng(latlngs[i]);
\r
4643 _initEvents: function () {
\r
4644 L.Path.prototype._initEvents.call(this);
\r
4647 _getPathPartStr: function (points) {
\r
4648 var round = L.Path.VML;
\r
4650 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
\r
4655 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
\r
4660 _clipPoints: function () {
\r
4661 var points = this._originalPoints,
\r
4662 len = points.length,
\r
4665 if (this.options.noClip) {
\r
4666 this._parts = [points];
\r
4672 var parts = this._parts,
\r
4673 vp = this._map._pathViewport,
\r
4676 for (i = 0, k = 0; i < len - 1; i++) {
\r
4677 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
\r
4682 parts[k] = parts[k] || [];
\r
4683 parts[k].push(segment[0]);
\r
4685 // if segment goes out of screen, or it's the last one, it's the end of the line part
\r
4686 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
\r
4687 parts[k].push(segment[1]);
\r
4693 // simplify each clipped part of the polyline
\r
4694 _simplifyPoints: function () {
\r
4695 var parts = this._parts,
\r
4698 for (var i = 0, len = parts.length; i < len; i++) {
\r
4699 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
\r
4703 _updatePath: function () {
\r
4704 if (!this._map) { return; }
\r
4706 this._clipPoints();
\r
4707 this._simplifyPoints();
\r
4709 L.Path.prototype._updatePath.call(this);
\r
4713 L.polyline = function (latlngs, options) {
\r
4714 return new L.Polyline(latlngs, options);
\r
4719 * L.PolyUtil contains utilify functions for polygons (clipping, etc.).
\r
4722 /*jshint bitwise:false */ // allow bitwise oprations here
\r
4727 * Sutherland-Hodgeman polygon clipping algorithm.
\r
4728 * Used to avoid rendering parts of a polygon that are not currently visible.
\r
4730 L.PolyUtil.clipPolygon = function (points, bounds) {
\r
4731 var min = bounds.min,
\r
4734 edges = [1, 4, 2, 8],
\r
4740 for (i = 0, len = points.length; i < len; i++) {
\r
4741 points[i]._code = lu._getBitCode(points[i], bounds);
\r
4744 // for each edge (left, bottom, right, top)
\r
4745 for (k = 0; k < 4; k++) {
\r
4747 clippedPoints = [];
\r
4749 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
\r
4753 // if a is inside the clip window
\r
4754 if (!(a._code & edge)) {
\r
4755 // if b is outside the clip window (a->b goes out of screen)
\r
4756 if (b._code & edge) {
\r
4757 p = lu._getEdgeIntersection(b, a, edge, bounds);
\r
4758 p._code = lu._getBitCode(p, bounds);
\r
4759 clippedPoints.push(p);
\r
4761 clippedPoints.push(a);
\r
4763 // else if b is inside the clip window (a->b enters the screen)
\r
4764 } else if (!(b._code & edge)) {
\r
4765 p = lu._getEdgeIntersection(b, a, edge, bounds);
\r
4766 p._code = lu._getBitCode(p, bounds);
\r
4767 clippedPoints.push(p);
\r
4770 points = clippedPoints;
\r
4776 /*jshint bitwise:true */
\r
4780 * L.Polygon is used to display polygons on a map.
\r
4783 L.Polygon = L.Polyline.extend({
\r
4788 initialize: function (latlngs, options) {
\r
4789 L.Polyline.prototype.initialize.call(this, latlngs, options);
\r
4791 if (latlngs && (latlngs[0] instanceof Array) && (typeof latlngs[0][0] !== 'number')) {
\r
4792 this._latlngs = this._convertLatLngs(latlngs[0]);
\r
4793 this._holes = latlngs.slice(1);
\r
4797 projectLatlngs: function () {
\r
4798 L.Polyline.prototype.projectLatlngs.call(this);
\r
4800 // project polygon holes points
\r
4801 // TODO move this logic to Polyline to get rid of duplication
\r
4802 this._holePoints = [];
\r
4804 if (!this._holes) {
\r
4808 for (var i = 0, len = this._holes.length, hole; i < len; i++) {
\r
4809 this._holePoints[i] = [];
\r
4811 for (var j = 0, len2 = this._holes[i].length; j < len2; j++) {
\r
4812 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
\r
4817 _clipPoints: function () {
\r
4818 var points = this._originalPoints,
\r
4821 this._parts = [points].concat(this._holePoints);
\r
4823 if (this.options.noClip) {
\r
4827 for (var i = 0, len = this._parts.length; i < len; i++) {
\r
4828 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
\r
4829 if (!clipped.length) {
\r
4832 newParts.push(clipped);
\r
4835 this._parts = newParts;
\r
4838 _getPathPartStr: function (points) {
\r
4839 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
\r
4840 return str + (L.Browser.svg ? 'z' : 'x');
\r
4844 L.polygon = function (latlngs, options) {
\r
4845 return new L.Polygon(latlngs, options);
\r
4850 * Contains L.MultiPolyline and L.MultiPolygon layers.
\r
4854 function createMulti(Klass) {
\r
4855 return L.FeatureGroup.extend({
\r
4856 initialize: function (latlngs, options) {
\r
4857 this._layers = {};
\r
4858 this._options = options;
\r
4859 this.setLatLngs(latlngs);
\r
4862 setLatLngs: function (latlngs) {
\r
4863 var i = 0, len = latlngs.length;
\r
4865 this.eachLayer(function (layer) {
\r
4867 layer.setLatLngs(latlngs[i++]);
\r
4869 this.removeLayer(layer);
\r
4874 this.addLayer(new Klass(latlngs[i++], this._options));
\r
4882 L.MultiPolyline = createMulti(L.Polyline);
\r
4883 L.MultiPolygon = createMulti(L.Polygon);
\r
4885 L.multiPolyline = function (latlngs, options) {
\r
4886 return new L.MultiPolyline(latlngs, options);
\r
4889 L.multiPolygon = function (latlngs, options) {
\r
4890 return new L.MultiPolygon(latlngs, options);
\r
4896 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds
\r
4899 L.Rectangle = L.Polygon.extend({
\r
4900 initialize: function (latLngBounds, options) {
\r
4901 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
\r
4904 setBounds: function (latLngBounds) {
\r
4905 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
\r
4908 _boundsToLatLngs: function (latLngBounds) {
\r
4909 latLngBounds = L.latLngBounds(latLngBounds);
\r
4911 latLngBounds.getSouthWest(),
\r
4912 latLngBounds.getNorthWest(),
\r
4913 latLngBounds.getNorthEast(),
\r
4914 latLngBounds.getSouthEast(),
\r
4915 latLngBounds.getSouthWest()
\r
4920 L.rectangle = function (latLngBounds, options) {
\r
4921 return new L.Rectangle(latLngBounds, options);
\r
4926 * L.Circle is a circle overlay (with a certain radius in meters).
\r
4929 L.Circle = L.Path.extend({
\r
4930 initialize: function (latlng, radius, options) {
\r
4931 L.Path.prototype.initialize.call(this, options);
\r
4933 this._latlng = L.latLng(latlng);
\r
4934 this._mRadius = radius;
\r
4941 setLatLng: function (latlng) {
\r
4942 this._latlng = L.latLng(latlng);
\r
4943 return this.redraw();
\r
4946 setRadius: function (radius) {
\r
4947 this._mRadius = radius;
\r
4948 return this.redraw();
\r
4951 projectLatlngs: function () {
\r
4952 var lngRadius = this._getLngRadius(),
\r
4953 latlng2 = new L.LatLng(this._latlng.lat, this._latlng.lng - lngRadius, true),
\r
4954 point2 = this._map.latLngToLayerPoint(latlng2);
\r
4956 this._point = this._map.latLngToLayerPoint(this._latlng);
\r
4957 this._radius = Math.max(Math.round(this._point.x - point2.x), 1);
\r
4960 getBounds: function () {
\r
4961 var map = this._map,
\r
4962 delta = this._radius * Math.cos(Math.PI / 4),
\r
4963 point = map.project(this._latlng),
\r
4964 swPoint = new L.Point(point.x - delta, point.y + delta),
\r
4965 nePoint = new L.Point(point.x + delta, point.y - delta),
\r
4966 sw = map.unproject(swPoint),
\r
4967 ne = map.unproject(nePoint);
\r
4969 return new L.LatLngBounds(sw, ne);
\r
4972 getLatLng: function () {
\r
4973 return this._latlng;
\r
4976 getPathString: function () {
\r
4977 var p = this._point,
\r
4980 if (this._checkIfEmpty()) {
\r
4984 if (L.Browser.svg) {
\r
4985 return "M" + p.x + "," + (p.y - r) +
\r
4986 "A" + r + "," + r + ",0,1,1," +
\r
4987 (p.x - 0.1) + "," + (p.y - r) + " z";
\r
4990 r = Math.round(r);
\r
4991 return "AL " + p.x + "," + p.y + " " + r + "," + r + " 0," + (65535 * 360);
\r
4995 getRadius: function () {
\r
4996 return this._mRadius;
\r
4999 _getLngRadius: function () {
\r
5000 var equatorLength = 40075017,
\r
5001 hLength = equatorLength * Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
\r
5003 return (this._mRadius / hLength) * 360;
\r
5006 _checkIfEmpty: function () {
\r
5010 var vp = this._map._pathViewport,
\r
5014 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
\r
5015 p.x + r < vp.min.x || p.y + r < vp.min.y;
\r
5019 L.circle = function (latlng, radius, options) {
\r
5020 return new L.Circle(latlng, radius, options);
\r
5025 * L.CircleMarker is a circle overlay with a permanent pixel radius.
\r
5028 L.CircleMarker = L.Circle.extend({
\r
5034 initialize: function (latlng, options) {
\r
5035 L.Circle.prototype.initialize.call(this, latlng, null, options);
\r
5036 this._radius = this.options.radius;
\r
5039 projectLatlngs: function () {
\r
5040 this._point = this._map.latLngToLayerPoint(this._latlng);
\r
5043 setRadius: function (radius) {
\r
5044 this._radius = radius;
\r
5045 return this.redraw();
\r
5049 L.circleMarker = function (latlng, options) {
\r
5050 return new L.CircleMarker(latlng, options);
\r
5055 L.Polyline.include(!L.Path.CANVAS ? {} : {
\r
5056 _containsPoint: function (p, closed) {
\r
5057 var i, j, k, len, len2, dist, part,
\r
5058 w = this.options.weight / 2;
\r
5060 if (L.Browser.touch) {
\r
5061 w += 10; // polyline click tolerance on touch devices
\r
5064 for (i = 0, len = this._parts.length; i < len; i++) {
\r
5065 part = this._parts[i];
\r
5066 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
\r
5067 if (!closed && (j === 0)) {
\r
5071 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
\r
5084 L.Polygon.include(!L.Path.CANVAS ? {} : {
\r
5085 _containsPoint: function (p) {
\r
5086 var inside = false,
\r
5091 // TODO optimization: check if within bounds first
\r
5093 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
\r
5094 // click on polygon border
\r
5098 // ray casting algorithm for detecting if point is in polygon
\r
5100 for (i = 0, len = this._parts.length; i < len; i++) {
\r
5101 part = this._parts[i];
\r
5103 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
\r
5107 if (((p1.y > p.y) !== (p2.y > p.y)) &&
\r
5108 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
\r
5120 * Circle canvas specific drawing parts.
\r
5123 L.Circle.include(!L.Path.CANVAS ? {} : {
\r
5124 _drawPath: function () {
\r
5125 var p = this._point;
\r
5126 this._ctx.beginPath();
\r
5127 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
\r
5130 _containsPoint: function (p) {
\r
5131 var center = this._point,
\r
5132 w2 = this.options.stroke ? this.options.weight / 2 : 0;
\r
5134 return (p.distanceTo(center) <= this._radius + w2);
\r
5139 L.GeoJSON = L.FeatureGroup.extend({
\r
5140 initialize: function (geojson, options) {
\r
5141 L.Util.setOptions(this, options);
\r
5143 this._layers = {};
\r
5146 this.addData(geojson);
\r
5150 addData: function (geojson) {
\r
5151 var features = geojson instanceof Array ? geojson : geojson.features,
\r
5155 for (i = 0, len = features.length; i < len; i++) {
\r
5156 this.addData(features[i]);
\r
5161 var options = this.options;
\r
5163 if (options.filter && !options.filter(geojson)) { return; }
\r
5165 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer);
\r
5166 layer.feature = geojson;
\r
5168 this.resetStyle(layer);
\r
5170 if (options.onEachFeature) {
\r
5171 options.onEachFeature(geojson, layer);
\r
5174 return this.addLayer(layer);
\r
5177 resetStyle: function (layer) {
\r
5178 var style = this.options.style;
\r
5180 this._setLayerStyle(layer, style);
\r
5184 setStyle: function (style) {
\r
5185 this.eachLayer(function (layer) {
\r
5186 this._setLayerStyle(layer, style);
\r
5190 _setLayerStyle: function (layer, style) {
\r
5191 if (typeof style === 'function') {
\r
5192 style = style(layer.feature);
\r
5194 if (layer.setStyle) {
\r
5195 layer.setStyle(style);
\r
5200 L.Util.extend(L.GeoJSON, {
\r
5201 geometryToLayer: function (geojson, pointToLayer) {
\r
5202 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
\r
5203 coords = geometry.coordinates,
\r
5205 latlng, latlngs, i, len, layer;
\r
5207 switch (geometry.type) {
\r
5209 latlng = this.coordsToLatLng(coords);
\r
5210 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
\r
5212 case 'MultiPoint':
\r
5213 for (i = 0, len = coords.length; i < len; i++) {
\r
5214 latlng = this.coordsToLatLng(coords[i]);
\r
5215 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
\r
5216 layers.push(layer);
\r
5218 return new L.FeatureGroup(layers);
\r
5220 case 'LineString':
\r
5221 latlngs = this.coordsToLatLngs(coords);
\r
5222 return new L.Polyline(latlngs);
\r
5225 latlngs = this.coordsToLatLngs(coords, 1);
\r
5226 return new L.Polygon(latlngs);
\r
5228 case 'MultiLineString':
\r
5229 latlngs = this.coordsToLatLngs(coords, 1);
\r
5230 return new L.MultiPolyline(latlngs);
\r
5232 case "MultiPolygon":
\r
5233 latlngs = this.coordsToLatLngs(coords, 2);
\r
5234 return new L.MultiPolygon(latlngs);
\r
5236 case "GeometryCollection":
\r
5237 for (i = 0, len = geometry.geometries.length; i < len; i++) {
\r
5238 layer = this.geometryToLayer(geometry.geometries[i], pointToLayer);
\r
5239 layers.push(layer);
\r
5241 return new L.FeatureGroup(layers);
\r
5244 throw new Error('Invalid GeoJSON object.');
\r
5248 coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng
\r
5249 var lat = parseFloat(coords[reverse ? 0 : 1]),
\r
5250 lng = parseFloat(coords[reverse ? 1 : 0]);
\r
5252 return new L.LatLng(lat, lng, true);
\r
5255 coordsToLatLngs: function (coords, levelsDeep, reverse) { // (Array, Number, Boolean) -> Array
\r
5260 for (i = 0, len = coords.length; i < len; i++) {
\r
5261 latlng = levelsDeep ?
\r
5262 this.coordsToLatLngs(coords[i], levelsDeep - 1, reverse) :
\r
5263 this.coordsToLatLng(coords[i], reverse);
\r
5265 latlngs.push(latlng);
\r
5272 L.geoJson = function (geojson, options) {
\r
5273 return new L.GeoJSON(geojson, options);
\r
5278 * L.DomEvent contains functions for working with DOM events.
\r
5282 /* inpired by John Resig, Dean Edwards and YUI addEvent implementations */
\r
5283 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
\r
5285 var id = L.Util.stamp(fn),
\r
5286 key = '_leaflet_' + type + id,
\r
5287 handler, originalHandler, newType;
\r
5289 if (obj[key]) { return this; }
\r
5291 handler = function (e) {
\r
5292 return fn.call(context || obj, e || L.DomEvent._getEvent());
\r
5295 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
\r
5296 return this.addDoubleTapListener(obj, handler, id);
\r
5298 } else if ('addEventListener' in obj) {
\r
5300 if (type === 'mousewheel') {
\r
5301 obj.addEventListener('DOMMouseScroll', handler, false);
\r
5302 obj.addEventListener(type, handler, false);
\r
5304 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
\r
5306 originalHandler = handler;
\r
5307 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
\r
5309 handler = function (e) {
\r
5310 if (!L.DomEvent._checkMouse(obj, e)) { return; }
\r
5311 return originalHandler(e);
\r
5314 obj.addEventListener(newType, handler, false);
\r
5317 obj.addEventListener(type, handler, false);
\r
5320 } else if ('attachEvent' in obj) {
\r
5321 obj.attachEvent("on" + type, handler);
\r
5324 obj[key] = handler;
\r
5329 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
\r
5331 var id = L.Util.stamp(fn),
\r
5332 key = '_leaflet_' + type + id,
\r
5333 handler = obj[key];
\r
5335 if (!handler) { return; }
\r
5337 if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
\r
5338 this.removeDoubleTapListener(obj, id);
\r
5340 } else if ('removeEventListener' in obj) {
\r
5342 if (type === 'mousewheel') {
\r
5343 obj.removeEventListener('DOMMouseScroll', handler, false);
\r
5344 obj.removeEventListener(type, handler, false);
\r
5346 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
\r
5347 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
\r
5349 obj.removeEventListener(type, handler, false);
\r
5351 } else if ('detachEvent' in obj) {
\r
5352 obj.detachEvent("on" + type, handler);
\r
5360 stopPropagation: function (e) {
\r
5362 if (e.stopPropagation) {
\r
5363 e.stopPropagation();
\r
5365 e.cancelBubble = true;
\r
5370 disableClickPropagation: function (el) {
\r
5372 var stop = L.DomEvent.stopPropagation;
\r
5375 .addListener(el, L.Draggable.START, stop)
\r
5376 .addListener(el, 'click', stop)
\r
5377 .addListener(el, 'dblclick', stop);
\r
5380 preventDefault: function (e) {
\r
5382 if (e.preventDefault) {
\r
5383 e.preventDefault();
\r
5385 e.returnValue = false;
\r
5390 stop: function (e) {
\r
5391 return L.DomEvent.preventDefault(e).stopPropagation(e);
\r
5394 getMousePosition: function (e, container) {
\r
5396 var body = document.body,
\r
5397 docEl = document.documentElement,
\r
5398 x = e.pageX ? e.pageX : e.clientX + body.scrollLeft + docEl.scrollLeft,
\r
5399 y = e.pageY ? e.pageY : e.clientY + body.scrollTop + docEl.scrollTop,
\r
5400 pos = new L.Point(x, y);
\r
5402 return (container ? pos._subtract(L.DomUtil.getViewportOffset(container)) : pos);
\r
5405 getWheelDelta: function (e) {
\r
5409 if (e.wheelDelta) {
\r
5410 delta = e.wheelDelta / 120;
\r
5413 delta = -e.detail / 3;
\r
5418 // check if element really left/entered the event target (for mouseenter/mouseleave)
\r
5419 _checkMouse: function (el, e) {
\r
5421 var related = e.relatedTarget;
\r
5423 if (!related) { return true; }
\r
5426 while (related && (related !== el)) {
\r
5427 related = related.parentNode;
\r
5432 return (related !== el);
\r
5435 /*jshint noarg:false */
\r
5436 _getEvent: function () { // evil magic for IE
\r
5438 var e = window.event;
\r
5440 var caller = arguments.callee.caller;
\r
5442 e = caller['arguments'][0];
\r
5443 if (e && window.Event === e.constructor) {
\r
5446 caller = caller.caller;
\r
5451 /*jshint noarg:false */
\r
5454 L.DomEvent.on = L.DomEvent.addListener;
\r
5455 L.DomEvent.off = L.DomEvent.removeListener;
5458 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
\r
5461 L.Draggable = L.Class.extend({
\r
5462 includes: L.Mixin.Events,
\r
5465 START: L.Browser.touch ? 'touchstart' : 'mousedown',
\r
5466 END: L.Browser.touch ? 'touchend' : 'mouseup',
\r
5467 MOVE: L.Browser.touch ? 'touchmove' : 'mousemove',
\r
5471 initialize: function (element, dragStartTarget) {
\r
5472 this._element = element;
\r
5473 this._dragStartTarget = dragStartTarget || element;
\r
5476 enable: function () {
\r
5477 if (this._enabled) {
\r
5480 L.DomEvent.on(this._dragStartTarget, L.Draggable.START, this._onDown, this);
\r
5481 this._enabled = true;
\r
5484 disable: function () {
\r
5485 if (!this._enabled) {
\r
5488 L.DomEvent.off(this._dragStartTarget, L.Draggable.START, this._onDown);
\r
5489 this._enabled = false;
\r
5490 this._moved = false;
\r
5493 _onDown: function (e) {
\r
5494 if ((!L.Browser.touch && e.shiftKey) ||
\r
5495 ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
\r
5497 L.DomEvent.preventDefault(e);
\r
5499 if (L.Draggable._disabled) { return; }
\r
5501 this._simulateClick = true;
\r
5503 if (e.touches && e.touches.length > 1) {
\r
5504 this._simulateClick = false;
\r
5508 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
\r
5509 el = first.target;
\r
5511 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
\r
5512 L.DomUtil.addClass(el, 'leaflet-active');
\r
5515 this._moved = false;
\r
5516 if (this._moving) {
\r
5520 this._startPoint = new L.Point(first.clientX, first.clientY);
\r
5521 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
\r
5523 L.DomEvent.on(document, L.Draggable.MOVE, this._onMove, this);
\r
5524 L.DomEvent.on(document, L.Draggable.END, this._onUp, this);
\r
5527 _onMove: function (e) {
\r
5528 if (e.touches && e.touches.length > 1) { return; }
\r
5530 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
\r
5531 newPoint = new L.Point(first.clientX, first.clientY),
\r
5532 diffVec = newPoint.subtract(this._startPoint);
\r
5534 if (!diffVec.x && !diffVec.y) { return; }
\r
5536 L.DomEvent.preventDefault(e);
\r
5538 if (!this._moved) {
\r
5539 this.fire('dragstart');
\r
5540 this._moved = true;
\r
5542 this._startPos = L.DomUtil.getPosition(this._element).subtract(diffVec);
\r
5544 if (!L.Browser.touch) {
\r
5545 L.DomUtil.disableTextSelection();
\r
5546 this._setMovingCursor();
\r
5550 this._newPos = this._startPos.add(diffVec);
\r
5551 this._moving = true;
\r
5553 L.Util.cancelAnimFrame(this._animRequest);
\r
5554 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
\r
5557 _updatePosition: function () {
\r
5558 this.fire('predrag');
\r
5559 L.DomUtil.setPosition(this._element, this._newPos);
\r
5560 this.fire('drag');
\r
5563 _onUp: function (e) {
\r
5564 if (this._simulateClick && e.changedTouches) {
\r
5565 var first = e.changedTouches[0],
\r
5566 el = first.target,
\r
5567 dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;
\r
5569 if (el.tagName.toLowerCase() === 'a') {
\r
5570 L.DomUtil.removeClass(el, 'leaflet-active');
\r
5573 if (dist < L.Draggable.TAP_TOLERANCE) {
\r
5574 this._simulateEvent('click', first);
\r
5578 if (!L.Browser.touch) {
\r
5579 L.DomUtil.enableTextSelection();
\r
5580 this._restoreCursor();
\r
5583 L.DomEvent.off(document, L.Draggable.MOVE, this._onMove);
\r
5584 L.DomEvent.off(document, L.Draggable.END, this._onUp);
\r
5586 if (this._moved) {
\r
5587 // ensure drag is not fired after dragend
\r
5588 L.Util.cancelAnimFrame(this._animRequest);
\r
5590 this.fire('dragend');
\r
5592 this._moving = false;
\r
5595 _setMovingCursor: function () {
\r
5596 L.DomUtil.addClass(document.body, 'leaflet-dragging');
\r
5599 _restoreCursor: function () {
\r
5600 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
\r
5603 _simulateEvent: function (type, e) {
\r
5604 var simulatedEvent = document.createEvent('MouseEvents');
\r
5606 simulatedEvent.initMouseEvent(
\r
5607 type, true, true, window, 1,
\r
5608 e.screenX, e.screenY,
\r
5609 e.clientX, e.clientY,
\r
5610 false, false, false, false, 0, null);
\r
5612 e.target.dispatchEvent(simulatedEvent);
\r
5618 * L.Handler classes are used internally to inject interaction features to classes like Map and Marker.
5621 L.Handler = L.Class.extend({
5622 initialize: function (map) {
5626 enable: function () {
5627 if (this._enabled) { return; }
5629 this._enabled = true;
5633 disable: function () {
5634 if (!this._enabled) { return; }
5636 this._enabled = false;
5640 enabled: function () {
5641 return !!this._enabled;
5647 * L.Handler.MapDrag is used internally by L.Map to make the map draggable.
5650 L.Map.mergeOptions({
5653 inertia: !L.Browser.android23,
5654 inertiaDeceleration: 3400, // px/s^2
5655 inertiaMaxSpeed: 6000, // px/s
5656 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
5658 // TODO refactor, move to CRS
5662 L.Map.Drag = L.Handler.extend({
5663 addHooks: function () {
5664 if (!this._draggable) {
5665 this._draggable = new L.Draggable(this._map._mapPane, this._map._container);
5667 this._draggable.on({
5668 'dragstart': this._onDragStart,
5669 'drag': this._onDrag,
5670 'dragend': this._onDragEnd
5673 var options = this._map.options;
5675 if (options.worldCopyJump) {
5676 this._draggable.on('predrag', this._onPreDrag, this);
5677 this._map.on('viewreset', this._onViewReset, this);
5680 this._draggable.enable();
5683 removeHooks: function () {
5684 this._draggable.disable();
5687 moved: function () {
5688 return this._draggable && this._draggable._moved;
5691 _onDragStart: function () {
5692 var map = this._map;
5695 map._panAnim.stop();
5702 if (map.options.inertia) {
5703 this._positions = [];
5708 _onDrag: function () {
5709 if (this._map.options.inertia) {
5710 var time = this._lastTime = +new Date(),
5711 pos = this._lastPos = this._draggable._newPos;
5713 this._positions.push(pos);
5714 this._times.push(time);
5716 if (time - this._times[0] > 200) {
5717 this._positions.shift();
5718 this._times.shift();
5727 _onViewReset: function () {
5728 var pxCenter = this._map.getSize()._divideBy(2),
5729 pxWorldCenter = this._map.latLngToLayerPoint(new L.LatLng(0, 0));
5731 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
5732 this._worldWidth = this._map.project(new L.LatLng(0, 180)).x;
5735 _onPreDrag: function () {
5736 // TODO refactor to be able to adjust map pane position after zoom
5737 var map = this._map,
5738 worldWidth = this._worldWidth,
5739 halfWidth = Math.round(worldWidth / 2),
5740 dx = this._initialWorldOffset,
5741 x = this._draggable._newPos.x,
5742 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
5743 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
5744 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
5746 this._draggable._newPos.x = newX;
5749 _onDragEnd: function () {
5750 var map = this._map,
5751 options = map.options,
5752 delay = +new Date() - this._lastTime,
5754 noInertia = !options.inertia ||
5755 delay > options.inertiaThreshold ||
5756 this._positions[0] === undefined;
5759 map.fire('moveend');
5763 var direction = this._lastPos.subtract(this._positions[0]),
5764 duration = (this._lastTime + delay - this._times[0]) / 1000,
5766 speedVector = direction.multiplyBy(0.58 / duration),
5767 speed = speedVector.distanceTo(new L.Point(0, 0)),
5769 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
5770 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
5772 decelerationDuration = limitedSpeed / options.inertiaDeceleration,
5773 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
5775 L.Util.requestAnimFrame(L.Util.bind(function () {
5776 this._map.panBy(offset, decelerationDuration);
5780 map.fire('dragend');
5782 if (options.maxBounds) {
5783 // TODO predrag validation instead of animation
5784 L.Util.requestAnimFrame(this._panInsideMaxBounds, map, true, map._container);
5788 _panInsideMaxBounds: function () {
5789 this.panInsideBounds(this.options.maxBounds);
5793 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
5797 * L.Handler.DoubleClickZoom is used internally by L.Map to add double-click zooming.
5800 L.Map.mergeOptions({
5801 doubleClickZoom: true
5804 L.Map.DoubleClickZoom = L.Handler.extend({
5805 addHooks: function () {
5806 this._map.on('dblclick', this._onDoubleClick);
5809 removeHooks: function () {
5810 this._map.off('dblclick', this._onDoubleClick);
5813 _onDoubleClick: function (e) {
5814 this.setView(e.latlng, this._zoom + 1);
5818 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
5821 * L.Handler.ScrollWheelZoom is used internally by L.Map to enable mouse scroll wheel zooming on the map.
5824 L.Map.mergeOptions({
5825 scrollWheelZoom: !L.Browser.touch
5828 L.Map.ScrollWheelZoom = L.Handler.extend({
5829 addHooks: function () {
5830 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
5834 removeHooks: function () {
5835 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
5838 _onWheelScroll: function (e) {
5839 var delta = L.DomEvent.getWheelDelta(e);
5841 this._delta += delta;
5842 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
5844 if (!this._startTime) {
5845 this._startTime = +new Date();
5848 var left = Math.max(40 - (+new Date() - this._startTime), 0);
5850 clearTimeout(this._timer);
5851 this._timer = setTimeout(L.Util.bind(this._performZoom, this), left);
5853 L.DomEvent.preventDefault(e);
5854 L.DomEvent.stopPropagation(e);
5857 _performZoom: function () {
5858 var map = this._map,
5859 delta = Math.round(this._delta),
5860 zoom = map.getZoom();
5862 delta = Math.max(Math.min(delta, 4), -4);
5863 delta = map._limitZoom(zoom + delta) - zoom;
5867 this._startTime = null;
5869 if (!delta) { return; }
5871 var newZoom = zoom + delta,
5872 newCenter = this._getCenterForScrollWheelZoom(newZoom);
5874 map.setView(newCenter, newZoom);
5877 _getCenterForScrollWheelZoom: function (newZoom) {
5878 var map = this._map,
5879 scale = map.getZoomScale(newZoom),
5880 viewHalf = map.getSize()._divideBy(2),
5881 centerOffset = this._lastMousePos._subtract(viewHalf)._multiplyBy(1 - 1 / scale),
5882 newCenterPoint = map._getTopLeftPoint()._add(viewHalf)._add(centerOffset);
5884 return map.unproject(newCenterPoint);
5888 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
5891 L.Util.extend(L.DomEvent, {
\r
5892 // inspired by Zepto touch code by Thomas Fuchs
\r
5893 addDoubleTapListener: function (obj, handler, id) {
\r
5895 doubleTap = false,
\r
5898 pre = '_leaflet_',
\r
5899 touchstart = 'touchstart',
\r
5900 touchend = 'touchend';
\r
5902 function onTouchStart(e) {
\r
5903 if (e.touches.length !== 1) {
\r
5907 var now = Date.now(),
\r
5908 delta = now - (last || now);
\r
5910 touch = e.touches[0];
\r
5911 doubleTap = (delta > 0 && delta <= delay);
\r
5914 function onTouchEnd(e) {
\r
5916 touch.type = 'dblclick';
\r
5921 obj[pre + touchstart + id] = onTouchStart;
\r
5922 obj[pre + touchend + id] = onTouchEnd;
\r
5924 obj.addEventListener(touchstart, onTouchStart, false);
\r
5925 obj.addEventListener(touchend, onTouchEnd, false);
\r
5929 removeDoubleTapListener: function (obj, id) {
\r
5930 var pre = '_leaflet_';
\r
5931 obj.removeEventListener(obj, obj[pre + 'touchstart' + id], false);
\r
5932 obj.removeEventListener(obj, obj[pre + 'touchend' + id], false);
\r
5939 * L.Handler.TouchZoom is used internally by L.Map to add touch-zooming on Webkit-powered mobile browsers.
5942 L.Map.mergeOptions({
5943 touchZoom: L.Browser.touch && !L.Browser.android23
5946 L.Map.TouchZoom = L.Handler.extend({
5947 addHooks: function () {
5948 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
5951 removeHooks: function () {
5952 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
5955 _onTouchStart: function (e) {
5956 var map = this._map;
5958 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
5960 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
5961 p2 = map.mouseEventToLayerPoint(e.touches[1]),
5962 viewCenter = map._getCenterLayerPoint();
5964 this._startCenter = p1.add(p2)._divideBy(2);
5965 this._startDist = p1.distanceTo(p2);
5967 this._moved = false;
5968 this._zooming = true;
5970 this._centerOffset = viewCenter.subtract(this._startCenter);
5973 map._panAnim.stop();
5977 .on(document, 'touchmove', this._onTouchMove, this)
5978 .on(document, 'touchend', this._onTouchEnd, this);
5980 L.DomEvent.preventDefault(e);
5983 _onTouchMove: function (e) {
5984 if (!e.touches || e.touches.length !== 2) { return; }
5986 var map = this._map;
5988 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
5989 p2 = map.mouseEventToLayerPoint(e.touches[1]);
5991 this._scale = p1.distanceTo(p2) / this._startDist;
5992 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
5994 if (this._scale === 1) { return; }
5997 L.DomUtil.addClass(map._mapPane, 'leaflet-zoom-anim leaflet-touching');
6007 L.Util.cancelAnimFrame(this._animRequest);
6008 this._animRequest = L.Util.requestAnimFrame(this._updateOnMove, this, true, this._map._container);
6010 L.DomEvent.preventDefault(e);
6013 _updateOnMove: function () {
6014 var map = this._map,
6015 origin = this._getScaleOrigin(),
6016 center = map.layerPointToLatLng(origin);
6018 map.fire('zoomanim', {
6020 zoom: map.getScaleZoom(this._scale)
6023 // Used 2 translates instead of transform-origin because of a very strange bug -
6024 // it didn't count the origin on the first touch-zoom but worked correctly afterwards
6026 map._tileBg.style[L.DomUtil.TRANSFORM] =
6027 L.DomUtil.getTranslateString(this._delta) + ' ' +
6028 L.DomUtil.getScaleString(this._scale, this._startCenter);
6031 _onTouchEnd: function (e) {
6032 if (!this._moved || !this._zooming) { return; }
6034 var map = this._map;
6036 this._zooming = false;
6037 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
6040 .off(document, 'touchmove', this._onTouchMove)
6041 .off(document, 'touchend', this._onTouchEnd);
6043 var origin = this._getScaleOrigin(),
6044 center = map.layerPointToLatLng(origin),
6046 oldZoom = map.getZoom(),
6047 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
6048 roundZoomDelta = (floatZoomDelta > 0 ? Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
6049 zoom = map._limitZoom(oldZoom + roundZoomDelta);
6051 map.fire('zoomanim', {
6056 map._runAnimation(center, zoom, map.getZoomScale(zoom) / this._scale, origin, true);
6059 _getScaleOrigin: function () {
6060 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
6061 return this._startCenter.add(centerOffset);
6065 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
6069 * L.Handler.ShiftDragZoom is used internally by L.Map to add shift-drag zoom (zoom to a selected bounding box).
6072 L.Map.mergeOptions({
6076 L.Map.BoxZoom = L.Handler.extend({
6077 initialize: function (map) {
6079 this._container = map._container;
6080 this._pane = map._panes.overlayPane;
6083 addHooks: function () {
6084 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
6087 removeHooks: function () {
6088 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
6091 _onMouseDown: function (e) {
6092 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
6094 L.DomUtil.disableTextSelection();
6096 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
6098 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
6099 L.DomUtil.setPosition(this._box, this._startLayerPoint);
6101 //TODO refactor: move cursor to styles
6102 this._container.style.cursor = 'crosshair';
6105 .on(document, 'mousemove', this._onMouseMove, this)
6106 .on(document, 'mouseup', this._onMouseUp, this)
6109 this._map.fire("boxzoomstart");
6112 _onMouseMove: function (e) {
6113 var startPoint = this._startLayerPoint,
6116 layerPoint = this._map.mouseEventToLayerPoint(e),
6117 offset = layerPoint.subtract(startPoint),
6119 newPos = new L.Point(
6120 Math.min(layerPoint.x, startPoint.x),
6121 Math.min(layerPoint.y, startPoint.y));
6123 L.DomUtil.setPosition(box, newPos);
6125 // TODO refactor: remove hardcoded 4 pixels
6126 box.style.width = (Math.abs(offset.x) - 4) + 'px';
6127 box.style.height = (Math.abs(offset.y) - 4) + 'px';
6130 _onMouseUp: function (e) {
6131 this._pane.removeChild(this._box);
6132 this._container.style.cursor = '';
6134 L.DomUtil.enableTextSelection();
6137 .off(document, 'mousemove', this._onMouseMove)
6138 .off(document, 'mouseup', this._onMouseUp);
6140 var map = this._map,
6141 layerPoint = map.mouseEventToLayerPoint(e);
6143 var bounds = new L.LatLngBounds(
6144 map.layerPointToLatLng(this._startLayerPoint),
6145 map.layerPointToLatLng(layerPoint));
6147 map.fitBounds(bounds);
6149 map.fire("boxzoomend", {
6150 boxZoomBounds: bounds
6155 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
6158 L.Map.mergeOptions({
6160 keyboardPanOffset: 80,
6161 keyboardZoomOffset: 1
6164 L.Map.Keyboard = L.Handler.extend({
6166 // list of e.keyCode values for particular actions
6172 zoomIn: [187, 107, 61],
6176 initialize: function (map) {
6179 this._setPanOffset(map.options.keyboardPanOffset);
6180 this._setZoomOffset(map.options.keyboardZoomOffset);
6183 addHooks: function () {
6184 var container = this._map._container;
6186 // make the container focusable by tabbing
6187 if (container.tabIndex === -1) {
6188 container.tabIndex = "0";
6192 .addListener(container, 'focus', this._onFocus, this)
6193 .addListener(container, 'blur', this._onBlur, this)
6194 .addListener(container, 'mousedown', this._onMouseDown, this);
6197 .on('focus', this._addHooks, this)
6198 .on('blur', this._removeHooks, this);
6201 removeHooks: function () {
6202 this._removeHooks();
6204 var container = this._map._container;
6206 .removeListener(container, 'focus', this._onFocus, this)
6207 .removeListener(container, 'blur', this._onBlur, this)
6208 .removeListener(container, 'mousedown', this._onMouseDown, this);
6211 .off('focus', this._addHooks, this)
6212 .off('blur', this._removeHooks, this);
6215 _onMouseDown: function () {
6216 if (!this._focused) {
6217 this._map._container.focus();
6221 _onFocus: function () {
6222 this._focused = true;
6223 this._map.fire('focus');
6226 _onBlur: function () {
6227 this._focused = false;
6228 this._map.fire('blur');
6231 _setPanOffset: function (pan) {
6232 var keys = this._panKeys = {},
6233 codes = this.keyCodes,
6236 for (i = 0, len = codes.left.length; i < len; i++) {
6237 keys[codes.left[i]] = [-1 * pan, 0];
6239 for (i = 0, len = codes.right.length; i < len; i++) {
6240 keys[codes.right[i]] = [pan, 0];
6242 for (i = 0, len = codes.down.length; i < len; i++) {
6243 keys[codes.down[i]] = [0, pan];
6245 for (i = 0, len = codes.up.length; i < len; i++) {
6246 keys[codes.up[i]] = [0, -1 * pan];
6250 _setZoomOffset: function (zoom) {
6251 var keys = this._zoomKeys = {},
6252 codes = this.keyCodes,
6255 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
6256 keys[codes.zoomIn[i]] = zoom;
6258 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
6259 keys[codes.zoomOut[i]] = -zoom;
6263 _addHooks: function () {
6264 L.DomEvent.addListener(document, 'keydown', this._onKeyDown, this);
6267 _removeHooks: function () {
6268 L.DomEvent.removeListener(document, 'keydown', this._onKeyDown, this);
6271 _onKeyDown: function (e) {
6272 var key = e.keyCode;
6274 if (this._panKeys.hasOwnProperty(key)) {
6275 this._map.panBy(this._panKeys[key]);
6277 } else if (this._zoomKeys.hasOwnProperty(key)) {
6278 this._map.setZoom(this._map.getZoom() + this._zoomKeys[key]);
6288 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
6292 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
6295 L.Handler.MarkerDrag = L.Handler.extend({
6296 initialize: function (marker) {
6297 this._marker = marker;
6300 addHooks: function () {
6301 var icon = this._marker._icon;
6302 if (!this._draggable) {
6303 this._draggable = new L.Draggable(icon, icon)
6304 .on('dragstart', this._onDragStart, this)
6305 .on('drag', this._onDrag, this)
6306 .on('dragend', this._onDragEnd, this);
6308 this._draggable.enable();
6311 removeHooks: function () {
6312 this._draggable.disable();
6315 moved: function () {
6316 return this._draggable && this._draggable._moved;
6319 _onDragStart: function (e) {
6326 _onDrag: function (e) {
6327 var marker = this._marker,
6328 shadow = marker._shadow,
6329 iconPos = L.DomUtil.getPosition(marker._icon),
6330 latlng = marker._map.layerPointToLatLng(iconPos);
6332 // update shadow position
6334 L.DomUtil.setPosition(shadow, iconPos);
6337 marker._latlng = latlng;
6340 .fire('move', { latlng: latlng })
6344 _onDragEnd: function () {
6352 L.Handler.PolyEdit = L.Handler.extend({
6354 icon: new L.DivIcon({
6355 iconSize: new L.Point(8, 8),
6356 className: 'leaflet-div-icon leaflet-editing-icon'
6360 initialize: function (poly, options) {
6362 L.Util.setOptions(this, options);
6365 addHooks: function () {
6366 if (this._poly._map) {
6367 if (!this._markerGroup) {
6368 this._initMarkers();
6370 this._poly._map.addLayer(this._markerGroup);
6374 removeHooks: function () {
6375 if (this._poly._map) {
6376 this._poly._map.removeLayer(this._markerGroup);
6377 delete this._markerGroup;
6378 delete this._markers;
6382 updateMarkers: function () {
6383 this._markerGroup.clearLayers();
6384 this._initMarkers();
6387 _initMarkers: function () {
6388 if (!this._markerGroup) {
6389 this._markerGroup = new L.LayerGroup();
6393 var latlngs = this._poly._latlngs,
6396 // TODO refactor holes implementation in Polygon to support it here
6398 for (i = 0, len = latlngs.length; i < len; i++) {
6400 marker = this._createMarker(latlngs[i], i);
6401 marker.on('click', this._onMarkerClick, this);
6402 this._markers.push(marker);
6405 var markerLeft, markerRight;
6407 for (i = 0, j = len - 1; i < len; j = i++) {
6408 if (i === 0 && !(L.Polygon && (this._poly instanceof L.Polygon))) {
6412 markerLeft = this._markers[j];
6413 markerRight = this._markers[i];
6415 this._createMiddleMarker(markerLeft, markerRight);
6416 this._updatePrevNext(markerLeft, markerRight);
6420 _createMarker: function (latlng, index) {
6421 var marker = new L.Marker(latlng, {
6423 icon: this.options.icon
6426 marker._origLatLng = latlng;
6427 marker._index = index;
6429 marker.on('drag', this._onMarkerDrag, this);
6430 marker.on('dragend', this._fireEdit, this);
6432 this._markerGroup.addLayer(marker);
6437 _fireEdit: function () {
6438 this._poly.fire('edit');
6441 _onMarkerDrag: function (e) {
6442 var marker = e.target;
6444 L.Util.extend(marker._origLatLng, marker._latlng);
6446 if (marker._middleLeft) {
6447 marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
6449 if (marker._middleRight) {
6450 marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
6453 this._poly.redraw();
6456 _onMarkerClick: function (e) {
6457 // 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
6458 if (this._poly._latlngs.length < 3) {
6462 var marker = e.target,
6465 // Check existence of previous and next markers since they wouldn't exist for edge points on the polyline
6466 if (marker._prev && marker._next) {
6467 this._createMiddleMarker(marker._prev, marker._next);
6468 } else if (!marker._prev) {
6469 marker._next._middleLeft = null;
6470 } else if (!marker._next) {
6471 marker._prev._middleRight = null;
6473 this._updatePrevNext(marker._prev, marker._next);
6475 // The marker itself is guaranteed to exist and present in the layer, since we managed to click on it
6476 this._markerGroup.removeLayer(marker);
6477 // Check for the existence of middle left or middle right
6478 if (marker._middleLeft) {
6479 this._markerGroup.removeLayer(marker._middleLeft);
6481 if (marker._middleRight) {
6482 this._markerGroup.removeLayer(marker._middleRight);
6484 this._markers.splice(i, 1);
6485 this._poly.spliceLatLngs(i, 1);
6486 this._updateIndexes(i, -1);
6487 this._poly.fire('edit');
6490 _updateIndexes: function (index, delta) {
6491 this._markerGroup.eachLayer(function (marker) {
6492 if (marker._index > index) {
6493 marker._index += delta;
6498 _createMiddleMarker: function (marker1, marker2) {
6499 var latlng = this._getMiddleLatLng(marker1, marker2),
6500 marker = this._createMarker(latlng),
6505 marker.setOpacity(0.6);
6507 marker1._middleRight = marker2._middleLeft = marker;
6509 onDragStart = function () {
6510 var i = marker2._index;
6515 .off('click', onClick)
6516 .on('click', this._onMarkerClick, this);
6518 latlng.lat = marker.getLatLng().lat;
6519 latlng.lng = marker.getLatLng().lng;
6520 this._poly.spliceLatLngs(i, 0, latlng);
6521 this._markers.splice(i, 0, marker);
6523 marker.setOpacity(1);
6525 this._updateIndexes(i, 1);
6527 this._updatePrevNext(marker1, marker);
6528 this._updatePrevNext(marker, marker2);
6531 onDragEnd = function () {
6532 marker.off('dragstart', onDragStart, this);
6533 marker.off('dragend', onDragEnd, this);
6535 this._createMiddleMarker(marker1, marker);
6536 this._createMiddleMarker(marker, marker2);
6539 onClick = function () {
6540 onDragStart.call(this);
6541 onDragEnd.call(this);
6542 this._poly.fire('edit');
6546 .on('click', onClick, this)
6547 .on('dragstart', onDragStart, this)
6548 .on('dragend', onDragEnd, this);
6550 this._markerGroup.addLayer(marker);
6553 _updatePrevNext: function (marker1, marker2) {
6555 marker1._next = marker2;
6558 marker2._prev = marker1;
6562 _getMiddleLatLng: function (marker1, marker2) {
6563 var map = this._poly._map,
6564 p1 = map.latLngToLayerPoint(marker1.getLatLng()),
6565 p2 = map.latLngToLayerPoint(marker2.getLatLng());
6567 return map.layerPointToLatLng(p1._add(p2)._divideBy(2));
6573 L.Control = L.Class.extend({
\r
6575 position: 'topright'
\r
6578 initialize: function (options) {
\r
6579 L.Util.setOptions(this, options);
\r
6582 getPosition: function () {
\r
6583 return this.options.position;
\r
6586 setPosition: function (position) {
\r
6587 var map = this._map;
\r
6590 map.removeControl(this);
\r
6593 this.options.position = position;
\r
6596 map.addControl(this);
\r
6602 addTo: function (map) {
\r
6605 var container = this._container = this.onAdd(map),
\r
6606 pos = this.getPosition(),
\r
6607 corner = map._controlCorners[pos];
\r
6609 L.DomUtil.addClass(container, 'leaflet-control');
\r
6611 if (pos.indexOf('bottom') !== -1) {
\r
6612 corner.insertBefore(container, corner.firstChild);
\r
6614 corner.appendChild(container);
\r
6620 removeFrom: function (map) {
\r
6621 var pos = this.getPosition(),
\r
6622 corner = map._controlCorners[pos];
\r
6624 corner.removeChild(this._container);
\r
6627 if (this.onRemove) {
\r
6628 this.onRemove(map);
\r
6635 L.control = function (options) {
\r
6636 return new L.Control(options);
\r
6641 addControl: function (control) {
6642 control.addTo(this);
6646 removeControl: function (control) {
6647 control.removeFrom(this);
6651 _initControlPos: function () {
6652 var corners = this._controlCorners = {},
6654 container = this._controlContainer =
6655 L.DomUtil.create('div', l + 'control-container', this._container);
6657 function createCorner(vSide, hSide) {
6658 var className = l + vSide + ' ' + l + hSide;
6660 corners[vSide + hSide] =
6661 L.DomUtil.create('div', className, container);
6664 createCorner('top', 'left');
6665 createCorner('top', 'right');
6666 createCorner('bottom', 'left');
6667 createCorner('bottom', 'right');
6672 L.Control.Zoom = L.Control.extend({
\r
6674 position: 'topleft'
\r
6677 onAdd: function (map) {
\r
6678 var className = 'leaflet-control-zoom',
\r
6679 container = L.DomUtil.create('div', className);
\r
6683 this._createButton('Zoom in', className + '-in', container, this._zoomIn, this);
\r
6684 this._createButton('Zoom out', className + '-out', container, this._zoomOut, this);
\r
6689 _zoomIn: function (e) {
\r
6690 this._map.zoomIn(e.shiftKey ? 3 : 1);
\r
6693 _zoomOut: function (e) {
\r
6694 this._map.zoomOut(e.shiftKey ? 3 : 1);
\r
6697 _createButton: function (title, className, container, fn, context) {
\r
6698 var link = L.DomUtil.create('a', className, container);
\r
6700 link.title = title;
\r
6703 .on(link, 'click', L.DomEvent.stopPropagation)
\r
6704 .on(link, 'mousedown', L.DomEvent.stopPropagation)
\r
6705 .on(link, 'dblclick', L.DomEvent.stopPropagation)
\r
6706 .on(link, 'click', L.DomEvent.preventDefault)
\r
6707 .on(link, 'click', fn, context);
\r
6713 L.Map.mergeOptions({
\r
6717 L.Map.addInitHook(function () {
\r
6718 if (this.options.zoomControl) {
\r
6719 this.zoomControl = new L.Control.Zoom();
\r
6720 this.addControl(this.zoomControl);
\r
6724 L.control.zoom = function (options) {
\r
6725 return new L.Control.Zoom(options);
\r
6730 L.Control.Attribution = L.Control.extend({
\r
6732 position: 'bottomright',
\r
6733 prefix: 'Powered by <a href="http://leaflet.cloudmade.com">Leaflet</a>'
\r
6736 initialize: function (options) {
\r
6737 L.Util.setOptions(this, options);
\r
6739 this._attributions = {};
\r
6742 onAdd: function (map) {
\r
6743 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
\r
6744 L.DomEvent.disableClickPropagation(this._container);
\r
6747 .on('layeradd', this._onLayerAdd, this)
\r
6748 .on('layerremove', this._onLayerRemove, this);
\r
6752 return this._container;
\r
6755 onRemove: function (map) {
\r
6757 .off('layeradd', this._onLayerAdd)
\r
6758 .off('layerremove', this._onLayerRemove);
\r
6762 setPrefix: function (prefix) {
\r
6763 this.options.prefix = prefix;
\r
6768 addAttribution: function (text) {
\r
6769 if (!text) { return; }
\r
6771 if (!this._attributions[text]) {
\r
6772 this._attributions[text] = 0;
\r
6774 this._attributions[text]++;
\r
6781 removeAttribution: function (text) {
\r
6782 if (!text) { return; }
\r
6784 this._attributions[text]--;
\r
6790 _update: function () {
\r
6791 if (!this._map) { return; }
\r
6795 for (var i in this._attributions) {
\r
6796 if (this._attributions.hasOwnProperty(i) && this._attributions[i]) {
\r
6801 var prefixAndAttribs = [];
\r
6803 if (this.options.prefix) {
\r
6804 prefixAndAttribs.push(this.options.prefix);
\r
6806 if (attribs.length) {
\r
6807 prefixAndAttribs.push(attribs.join(', '));
\r
6810 this._container.innerHTML = prefixAndAttribs.join(' — ');
\r
6813 _onLayerAdd: function (e) {
\r
6814 if (e.layer.getAttribution) {
\r
6815 this.addAttribution(e.layer.getAttribution());
\r
6819 _onLayerRemove: function (e) {
\r
6820 if (e.layer.getAttribution) {
\r
6821 this.removeAttribution(e.layer.getAttribution());
\r
6826 L.Map.mergeOptions({
\r
6827 attributionControl: true
\r
6830 L.Map.addInitHook(function () {
\r
6831 if (this.options.attributionControl) {
\r
6832 this.attributionControl = (new L.Control.Attribution()).addTo(this);
\r
6836 L.control.attribution = function (options) {
\r
6837 return new L.Control.Attribution(options);
\r
6841 L.Control.Scale = L.Control.extend({
6843 position: 'bottomleft',
6847 updateWhenIdle: false
6850 onAdd: function (map) {
6853 var className = 'leaflet-control-scale',
6854 container = L.DomUtil.create('div', className),
6855 options = this.options;
6857 this._addScales(options, className, container);
6859 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
6860 map.whenReady(this._update, this);
6865 onRemove: function (map) {
6866 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
6869 _addScales: function (options, className, container) {
6870 if (options.metric) {
6871 this._mScale = L.DomUtil.create('div', className + '-line', container);
6873 if (options.imperial) {
6874 this._iScale = L.DomUtil.create('div', className + '-line', container);
6878 _update: function () {
6879 var bounds = this._map.getBounds(),
6880 centerLat = bounds.getCenter().lat,
6881 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
6882 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
6884 size = this._map.getSize(),
6885 options = this.options,
6889 maxMeters = dist * (options.maxWidth / size.x);
6892 this._updateScales(options, maxMeters);
6895 _updateScales: function (options, maxMeters) {
6896 if (options.metric && maxMeters) {
6897 this._updateMetric(maxMeters);
6900 if (options.imperial && maxMeters) {
6901 this._updateImperial(maxMeters);
6905 _updateMetric: function (maxMeters) {
6906 var meters = this._getRoundNum(maxMeters);
6908 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
6909 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
6912 _updateImperial: function (maxMeters) {
6913 var maxFeet = maxMeters * 3.2808399,
6914 scale = this._iScale,
6915 maxMiles, miles, feet;
6917 if (maxFeet > 5280) {
6918 maxMiles = maxFeet / 5280;
6919 miles = this._getRoundNum(maxMiles);
6921 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
6922 scale.innerHTML = miles + ' mi';
6925 feet = this._getRoundNum(maxFeet);
6927 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
6928 scale.innerHTML = feet + ' ft';
6932 _getScaleWidth: function (ratio) {
6933 return Math.round(this.options.maxWidth * ratio) - 10;
6936 _getRoundNum: function (num) {
6937 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
6940 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
6946 L.control.scale = function (options) {
6947 return new L.Control.Scale(options);
6952 L.Control.Layers = L.Control.extend({
\r
6955 position: 'topright',
\r
6959 initialize: function (baseLayers, overlays, options) {
\r
6960 L.Util.setOptions(this, options);
\r
6962 this._layers = {};
\r
6963 this._lastZIndex = 0;
\r
6965 for (var i in baseLayers) {
\r
6966 if (baseLayers.hasOwnProperty(i)) {
\r
6967 this._addLayer(baseLayers[i], i);
\r
6971 for (i in overlays) {
\r
6972 if (overlays.hasOwnProperty(i)) {
\r
6973 this._addLayer(overlays[i], i, true);
\r
6978 onAdd: function (map) {
\r
6979 this._initLayout();
\r
6982 return this._container;
\r
6985 addBaseLayer: function (layer, name) {
\r
6986 this._addLayer(layer, name);
\r
6991 addOverlay: function (layer, name) {
\r
6992 this._addLayer(layer, name, true);
\r
6997 removeLayer: function (layer) {
\r
6998 var id = L.Util.stamp(layer);
\r
6999 delete this._layers[id];
\r
7004 _initLayout: function () {
\r
7005 var className = 'leaflet-control-layers',
\r
7006 container = this._container = L.DomUtil.create('div', className);
\r
7008 if (!L.Browser.touch) {
\r
7009 L.DomEvent.disableClickPropagation(container);
\r
7011 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
\r
7014 var form = this._form = L.DomUtil.create('form', className + '-list');
\r
7016 if (this.options.collapsed) {
\r
7018 .on(container, 'mouseover', this._expand, this)
\r
7019 .on(container, 'mouseout', this._collapse, this);
\r
7021 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
\r
7023 link.title = 'Layers';
\r
7025 if (L.Browser.touch) {
\r
7027 .on(link, 'click', L.DomEvent.stopPropagation)
\r
7028 .on(link, 'click', L.DomEvent.preventDefault)
\r
7029 .on(link, 'click', this._expand, this);
\r
7032 L.DomEvent.on(link, 'focus', this._expand, this);
\r
7035 this._map.on('movestart', this._collapse, this);
\r
7036 // TODO keyboard accessibility
\r
7041 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
\r
7042 this._separator = L.DomUtil.create('div', className + '-separator', form);
\r
7043 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
\r
7045 container.appendChild(form);
\r
7048 _addLayer: function (layer, name, overlay) {
\r
7049 var id = L.Util.stamp(layer);
\r
7051 this._layers[id] = {
\r
7057 if (this.options.autoZIndex && layer.setZIndex) {
\r
7058 this._lastZIndex++;
\r
7059 layer.setZIndex(this._lastZIndex);
\r
7063 _update: function () {
\r
7064 if (!this._container) {
\r
7068 this._baseLayersList.innerHTML = '';
\r
7069 this._overlaysList.innerHTML = '';
\r
7071 var baseLayersPresent = false,
\r
7072 overlaysPresent = false;
\r
7074 for (var i in this._layers) {
\r
7075 if (this._layers.hasOwnProperty(i)) {
\r
7076 var obj = this._layers[i];
\r
7077 this._addItem(obj);
\r
7078 overlaysPresent = overlaysPresent || obj.overlay;
\r
7079 baseLayersPresent = baseLayersPresent || !obj.overlay;
\r
7083 this._separator.style.display = (overlaysPresent && baseLayersPresent ? '' : 'none');
\r
7086 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
\r
7087 _createRadioElement: function (name, checked) {
\r
7089 var radioHtml = '<input type="radio" name="' + name + '"';
\r
7091 radioHtml += ' checked="checked"';
\r
7093 radioHtml += '/>';
\r
7095 var radioFragment = document.createElement('div');
\r
7096 radioFragment.innerHTML = radioHtml;
\r
7098 return radioFragment.firstChild;
\r
7101 _addItem: function (obj) {
\r
7102 var label = document.createElement('label'),
\r
7104 checked = this._map.hasLayer(obj.layer);
\r
7106 if (obj.overlay) {
\r
7107 input = document.createElement('input');
\r
7108 input.type = 'checkbox';
\r
7109 input.defaultChecked = checked;
\r
7111 input = this._createRadioElement('leaflet-base-layers', checked);
\r
7114 input.layerId = L.Util.stamp(obj.layer);
\r
7116 L.DomEvent.on(input, 'click', this._onInputClick, this);
\r
7118 var name = document.createTextNode(' ' + obj.name);
\r
7120 label.appendChild(input);
\r
7121 label.appendChild(name);
\r
7123 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
\r
7124 container.appendChild(label);
\r
7127 _onInputClick: function () {
\r
7128 var i, input, obj,
\r
7129 inputs = this._form.getElementsByTagName('input'),
\r
7130 inputsLen = inputs.length,
\r
7133 for (i = 0; i < inputsLen; i++) {
\r
7134 input = inputs[i];
\r
7135 obj = this._layers[input.layerId];
\r
7137 if (input.checked && !this._map.hasLayer(obj.layer)) {
\r
7138 this._map.addLayer(obj.layer);
\r
7139 if (!obj.overlay) {
\r
7140 baseLayer = obj.layer;
\r
7142 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
\r
7143 this._map.removeLayer(obj.layer);
\r
7148 this._map.fire('baselayerchange', {layer: baseLayer});
\r
7152 _expand: function () {
\r
7153 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
\r
7156 _collapse: function () {
\r
7157 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
\r
7161 L.control.layers = function (baseLayers, overlays, options) {
\r
7162 return new L.Control.Layers(baseLayers, overlays, options);
\r
7167 * L.PosAnimation is used by Leaflet internally for pan animations.
7170 L.PosAnimation = L.Class.extend({
7171 includes: L.Mixin.Events,
7173 run: function (el, newPos, duration, easing) { // (HTMLElement, Point[, Number, String])
7177 this._inProgress = true;
7181 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) + 's ' + (easing || 'ease-out');
7183 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7184 L.DomUtil.setPosition(el, newPos);
7186 // toggle reflow, Chrome flickers for some reason if you don't do this
7187 L.Util.falseFn(el.offsetWidth);
7189 // there's no native way to track value updates of tranisitioned properties, so we imitate this
7190 this._stepTimer = setInterval(L.Util.bind(this.fire, this, 'step'), 50);
7194 if (!this._inProgress) { return; }
7196 // if we just removed the transition property, the element would jump to its final position,
7197 // so we need to make it stay at the current position
7199 L.DomUtil.setPosition(this._el, this._getPos());
7200 this._onTransitionEnd();
7203 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
7204 // we need to parse computed style (in case of transform it returns matrix string)
7206 _transformRe: /(-?[\d\.]+), (-?[\d\.]+)\)/,
7208 _getPos: function () {
7209 var left, top, matches,
7211 style = window.getComputedStyle(el);
7213 if (L.Browser.any3d) {
7214 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
7215 left = parseFloat(matches[1]);
7216 top = parseFloat(matches[2]);
7218 left = parseFloat(style.left);
7219 top = parseFloat(style.top);
7222 return new L.Point(left, top, true);
7225 _onTransitionEnd: function () {
7226 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7228 if (!this._inProgress) { return; }
7229 this._inProgress = false;
7231 this._el.style[L.DomUtil.TRANSITION] = '';
7233 clearInterval(this._stepTimer);
7235 this.fire('step').fire('end');
7244 setView: function (center, zoom, forceReset) {
7245 zoom = this._limitZoom(zoom);
7247 var zoomChanged = (this._zoom !== zoom);
7249 if (this._loaded && !forceReset && this._layers) {
7251 if (this._panAnim) {
7252 this._panAnim.stop();
7255 var done = (zoomChanged ?
7256 this._zoomToIfClose && this._zoomToIfClose(center, zoom) :
7257 this._panByIfClose(center));
7259 // exit if animated pan or zoom started
7261 clearTimeout(this._sizeTimer);
7266 // reset the map view
7267 this._resetView(center, zoom);
7272 panBy: function (offset, duration) {
7273 offset = L.point(offset);
7275 if (!(offset.x || offset.y)) {
7279 if (!this._panAnim) {
7280 this._panAnim = new L.PosAnimation();
7283 'step': this._onPanTransitionStep,
7284 'end': this._onPanTransitionEnd
7288 this.fire('movestart');
7290 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
7292 var newPos = L.DomUtil.getPosition(this._mapPane).subtract(offset);
7293 this._panAnim.run(this._mapPane, newPos, duration || 0.25);
7298 _onPanTransitionStep: function () {
7302 _onPanTransitionEnd: function () {
7303 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
7304 this.fire('moveend');
7307 _panByIfClose: function (center) {
7308 // difference between the new and current centers in pixels
7309 var offset = this._getCenterOffset(center)._floor();
7311 if (this._offsetIsWithinView(offset)) {
7318 _offsetIsWithinView: function (offset, multiplyFactor) {
7319 var m = multiplyFactor || 1,
7320 size = this.getSize();
7322 return (Math.abs(offset.x) <= size.x * m) &&
7323 (Math.abs(offset.y) <= size.y * m);
7329 * L.PosAnimation fallback implementation that powers Leaflet pan animations
7330 * in browsers that don't support CSS3 Transitions.
7333 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
7335 run: function (el, newPos, duration, easing) { // (HTMLElement, Point[, Number, String])
7339 this._inProgress = true;
7340 this._duration = duration || 0.25;
7341 this._ease = this._easings[easing || 'ease-out'];
7343 this._startPos = L.DomUtil.getPosition(el);
7344 this._offset = newPos.subtract(this._startPos);
7345 this._startTime = +new Date();
7353 if (!this._inProgress) { return; }
7359 _animate: function () {
7361 this._animId = L.Util.requestAnimFrame(this._animate, this);
7365 _step: function () {
7366 var elapsed = (+new Date()) - this._startTime,
7367 duration = this._duration * 1000;
7369 if (elapsed < duration) {
7370 this._runFrame(this._ease(elapsed / duration));
7377 _runFrame: function (progress) {
7378 var pos = this._startPos.add(this._offset.multiplyBy(progress));
7379 L.DomUtil.setPosition(this._el, pos);
7384 _complete: function () {
7385 L.Util.cancelAnimFrame(this._animId);
7387 this._inProgress = false;
7391 // easing functions, they map time progress to movement progress
7393 'ease-out': function (t) { return t * (2 - t); },
7394 'linear': function (t) { return t; }
7400 L.Map.mergeOptions({
7401 zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera
7404 if (L.DomUtil.TRANSITION) {
7405 L.Map.addInitHook(function () {
7406 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
7410 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
7412 _zoomToIfClose: function (center, zoom) {
7414 if (this._animatingZoom) { return true; }
7416 if (!this.options.zoomAnimation) { return false; }
7418 var scale = this.getZoomScale(zoom),
7419 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
7421 // if offset does not exceed half of the view
7422 if (!this._offsetIsWithinView(offset, 1)) { return false; }
7424 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
7430 this.fire('zoomanim', {
7435 var origin = this._getCenterLayerPoint().add(offset);
7437 this._prepareTileBg();
7438 this._runAnimation(center, zoom, scale, origin);
7443 _catchTransitionEnd: function (e) {
7444 if (this._animatingZoom) {
7445 this._onZoomTransitionEnd();
7449 _runAnimation: function (center, zoom, scale, origin, backwardsTransform) {
7450 this._animateToCenter = center;
7451 this._animateToZoom = zoom;
7452 this._animatingZoom = true;
7455 L.Draggable._disabled = true;
7458 var transform = L.DomUtil.TRANSFORM,
7459 tileBg = this._tileBg;
7461 clearTimeout(this._clearTileBgTimer);
7463 L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation
7465 var scaleStr = L.DomUtil.getScaleString(scale, origin),
7466 oldTransform = tileBg.style[transform];
7468 tileBg.style[transform] = backwardsTransform ?
7469 oldTransform + ' ' + scaleStr :
7470 scaleStr + ' ' + oldTransform;
7473 _prepareTileBg: function () {
7474 var tilePane = this._tilePane,
7475 tileBg = this._tileBg;
7477 // If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more
7479 this._getLoadedTilesPercentage(tileBg) > 0.5 &&
7480 this._getLoadedTilesPercentage(tilePane) < 0.5) {
7482 tilePane.style.visibility = 'hidden';
7483 tilePane.empty = true;
7484 this._stopLoadingImages(tilePane);
7489 tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane);
7490 tileBg.style.zIndex = 1;
7493 // prepare the background pane to become the main tile pane
7494 tileBg.style[L.DomUtil.TRANSFORM] = '';
7495 tileBg.style.visibility = 'hidden';
7497 // tells tile layers to reinitialize their containers
7498 tileBg.empty = true; //new FG
7499 tilePane.empty = false; //new BG
7501 //Switch out the current layer to be the new bg layer (And vice-versa)
7502 this._tilePane = this._panes.tilePane = tileBg;
7503 var newTileBg = this._tileBg = tilePane;
7505 L.DomUtil.addClass(newTileBg, 'leaflet-zoom-animated');
7507 this._stopLoadingImages(newTileBg);
7510 _getLoadedTilesPercentage: function (container) {
7511 var tiles = container.getElementsByTagName('img'),
7514 for (i = 0, len = tiles.length; i < len; i++) {
7515 if (tiles[i].complete) {
7522 // stops loading all tiles in the background layer
7523 _stopLoadingImages: function (container) {
7524 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
7527 for (i = 0, len = tiles.length; i < len; i++) {
7530 if (!tile.complete) {
7531 tile.onload = L.Util.falseFn;
7532 tile.onerror = L.Util.falseFn;
7533 tile.src = L.Util.emptyImageUrl;
7535 tile.parentNode.removeChild(tile);
7540 _onZoomTransitionEnd: function () {
7541 this._restoreTileFront();
7542 L.Util.falseFn(this._tileBg.offsetWidth); // force reflow
7543 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
7545 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
7546 this._animatingZoom = false;
7549 L.Draggable._disabled = false;
7553 _restoreTileFront: function () {
7554 this._tilePane.innerHTML = '';
7555 this._tilePane.style.visibility = '';
7556 this._tilePane.style.zIndex = 2;
7557 this._tileBg.style.zIndex = 1;
7560 _clearTileBg: function () {
7561 if (!this._animatingZoom && !this.touchZoom._zooming) {
7562 this._tileBg.innerHTML = '';
7569 * Provides L.Map with convenient shortcuts for W3C geolocation.
\r
7573 _defaultLocateOptions: {
\r
7576 maxZoom: Infinity,
\r
7579 enableHighAccuracy: false
\r
7582 locate: function (/*Object*/ options) {
\r
7584 options = this._locationOptions = L.Util.extend(this._defaultLocateOptions, options);
\r
7586 if (!navigator.geolocation) {
\r
7587 this._handleGeolocationError({
\r
7589 message: "Geolocation not supported."
\r
7594 var onResponse = L.Util.bind(this._handleGeolocationResponse, this),
\r
7595 onError = L.Util.bind(this._handleGeolocationError, this);
\r
7597 if (options.watch) {
\r
7598 this._locationWatchId = navigator.geolocation.watchPosition(onResponse, onError, options);
\r
7600 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
\r
7605 stopLocate: function () {
\r
7606 if (navigator.geolocation) {
\r
7607 navigator.geolocation.clearWatch(this._locationWatchId);
\r
7612 _handleGeolocationError: function (error) {
\r
7613 var c = error.code,
\r
7614 message = error.message ||
\r
7615 (c === 1 ? "permission denied" :
\r
7616 (c === 2 ? "position unavailable" : "timeout"));
\r
7618 if (this._locationOptions.setView && !this._loaded) {
\r
7622 this.fire('locationerror', {
\r
7624 message: "Geolocation error: " + message + "."
\r
7628 _handleGeolocationResponse: function (pos) {
\r
7629 var latAccuracy = 180 * pos.coords.accuracy / 4e7,
\r
7630 lngAccuracy = latAccuracy * 2,
\r
7632 lat = pos.coords.latitude,
\r
7633 lng = pos.coords.longitude,
\r
7634 latlng = new L.LatLng(lat, lng),
\r
7636 sw = new L.LatLng(lat - latAccuracy, lng - lngAccuracy),
\r
7637 ne = new L.LatLng(lat + latAccuracy, lng + lngAccuracy),
\r
7638 bounds = new L.LatLngBounds(sw, ne),
\r
7640 options = this._locationOptions;
\r
7642 if (options.setView) {
\r
7643 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
\r
7644 this.setView(latlng, zoom);
\r
7647 this.fire('locationfound', {
\r
7650 accuracy: pos.coords.accuracy
\r