2 Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
3 (c) 2010-2013, Vladimir Agafonkin, CloudMade
5 (function (window, document, undefined) {/*
6 * The L namespace contains all Leaflet classes and functions.
7 * This code allows you to handle any possible namespace conflicts.
12 if (typeof exports !== undefined + '') {
18 L.noConflict = function () {
30 * L.Util contains various utility functions used throughout Leaflet code.
34 extend: function (dest) { // (Object[, Object, ...]) ->
35 var sources = Array.prototype.slice.call(arguments, 1),
38 for (j = 0, len = sources.length; j < len; j++) {
39 src = sources[j] || {};
41 if (src.hasOwnProperty(i)) {
49 bind: function (fn, obj) { // (Function, Object) -> Function
50 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
52 return fn.apply(obj, args || arguments);
57 var lastId = 0, key = '_leaflet_id';
58 return function (/*Object*/ obj) {
59 obj[key] = obj[key] || ++lastId;
64 limitExecByInterval: function (fn, time, context) {
65 var lock, execOnUnlock;
67 return function wrapperFn() {
77 setTimeout(function () {
81 wrapperFn.apply(context, args);
86 fn.apply(context, args);
90 falseFn: function () {
94 formatNum: function (num, digits) {
95 var pow = Math.pow(10, digits || 5);
96 return Math.round(num * pow) / pow;
99 splitWords: function (str) {
100 return str.replace(/^\s+|\s+$/g, '').split(/\s+/);
103 setOptions: function (obj, options) {
104 obj.options = L.extend({}, obj.options, options);
108 getParamString: function (obj, existingUrl) {
111 if (obj.hasOwnProperty(i)) {
112 params.push(i + '=' + obj[i]);
115 return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
118 template: function (str, data) {
119 return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
120 var value = data[key];
121 if (!data.hasOwnProperty(key)) {
122 throw new Error('No value provided for variable ' + str);
128 isArray: function (obj) {
129 return (Object.prototype.toString.call(obj) === '[object Array]');
132 emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
137 // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
139 function getPrefixed(name) {
141 prefixes = ['webkit', 'moz', 'o', 'ms'];
143 for (i = 0; i < prefixes.length && !fn; i++) {
144 fn = window[prefixes[i] + name];
152 function timeoutDefer(fn) {
153 var time = +new Date(),
154 timeToCall = Math.max(0, 16 - (time - lastTime));
156 lastTime = time + timeToCall;
157 return window.setTimeout(fn, timeToCall);
160 var requestFn = window.requestAnimationFrame ||
161 getPrefixed('RequestAnimationFrame') || timeoutDefer;
163 var cancelFn = window.cancelAnimationFrame ||
164 getPrefixed('CancelAnimationFrame') ||
165 getPrefixed('CancelRequestAnimationFrame') ||
166 function (id) { window.clearTimeout(id); };
169 L.Util.requestAnimFrame = function (fn, context, immediate, element) {
170 fn = L.bind(fn, context);
172 if (immediate && requestFn === timeoutDefer) {
175 return requestFn.call(window, fn, element);
179 L.Util.cancelAnimFrame = function (id) {
181 cancelFn.call(window, id);
187 // shortcuts for most used utility functions
188 L.extend = L.Util.extend;
189 L.bind = L.Util.bind;
190 L.stamp = L.Util.stamp;
191 L.setOptions = L.Util.setOptions;
195 * L.Class powers the OOP facilities of the library.
196 * Thanks to John Resig and Dean Edwards for inspiration!
199 L.Class = function () {};
201 L.Class.extend = function (props) {
203 // extended class with the new prototype
204 var NewClass = function () {
206 // call the constructor
207 if (this.initialize) {
208 this.initialize.apply(this, arguments);
211 // call all constructor hooks
212 if (this._initHooks) {
213 this.callInitHooks();
217 // instantiate class without calling constructor
218 var F = function () {};
219 F.prototype = this.prototype;
222 proto.constructor = NewClass;
224 NewClass.prototype = proto;
226 //inherit parent's statics
227 for (var i in this) {
228 if (this.hasOwnProperty(i) && i !== 'prototype') {
229 NewClass[i] = this[i];
233 // mix static properties into the class
235 L.extend(NewClass, props.statics);
236 delete props.statics;
239 // mix includes into the prototype
240 if (props.includes) {
241 L.Util.extend.apply(null, [proto].concat(props.includes));
242 delete props.includes;
246 if (props.options && proto.options) {
247 props.options = L.extend({}, proto.options, props.options);
250 // mix given properties into the prototype
251 L.extend(proto, props);
253 proto._initHooks = [];
256 // add method for calling all hooks
257 proto.callInitHooks = function () {
259 if (this._initHooksCalled) { return; }
261 if (parent.prototype.callInitHooks) {
262 parent.prototype.callInitHooks.call(this);
265 this._initHooksCalled = true;
267 for (var i = 0, len = proto._initHooks.length; i < len; i++) {
268 proto._initHooks[i].call(this);
276 // method for adding properties to prototype
277 L.Class.include = function (props) {
278 L.extend(this.prototype, props);
281 // merge new default options to the Class
282 L.Class.mergeOptions = function (options) {
283 L.extend(this.prototype.options, options);
286 // add a constructor hook
287 L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
288 var args = Array.prototype.slice.call(arguments, 1);
290 var init = typeof fn === 'function' ? fn : function () {
291 this[fn].apply(this, args);
294 this.prototype._initHooks = this.prototype._initHooks || [];
295 this.prototype._initHooks.push(init);
300 * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
303 var key = '_leaflet_events';
309 addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
310 var events = this[key] = this[key] || {},
313 // Types can be a map of types/handlers
314 if (typeof types === 'object') {
315 for (type in types) {
316 if (types.hasOwnProperty(type)) {
317 this.addEventListener(type, types[type], fn);
324 types = L.Util.splitWords(types);
326 for (i = 0, len = types.length; i < len; i++) {
327 events[types[i]] = events[types[i]] || [];
328 events[types[i]].push({
330 context: context || this
337 hasEventListeners: function (type) { // (String) -> Boolean
338 return (key in this) && (type in this[key]) && (this[key][type].length > 0);
341 removeEventListener: function (types, fn, context) { // (String[, Function, Object]) or (Object[, Object])
342 var events = this[key],
343 type, i, len, listeners, j;
345 if (typeof types === 'object') {
346 for (type in types) {
347 if (types.hasOwnProperty(type)) {
348 this.removeEventListener(type, types[type], fn);
355 types = L.Util.splitWords(types);
357 for (i = 0, len = types.length; i < len; i++) {
359 if (this.hasEventListeners(types[i])) {
360 listeners = events[types[i]];
362 for (j = listeners.length - 1; j >= 0; j--) {
364 (!fn || listeners[j].action === fn) &&
365 (!context || (listeners[j].context === context))
367 listeners.splice(j, 1);
376 fireEvent: function (type, data) { // (String[, Object])
377 if (!this.hasEventListeners(type)) {
381 var event = L.extend({
386 var listeners = this[key][type].slice();
388 for (var i = 0, len = listeners.length; i < len; i++) {
389 listeners[i].action.call(listeners[i].context || this, event);
396 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
397 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
398 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
402 * L.Browser handles different browser and feature detections for internal Leaflet use.
407 var ie = !!window.ActiveXObject,
408 ie6 = ie && !window.XMLHttpRequest,
409 ie7 = ie && !document.querySelector,
411 // terrible browser detection to work around Safari / iOS / Android browser bugs
412 ua = navigator.userAgent.toLowerCase(),
413 webkit = ua.indexOf('webkit') !== -1,
414 chrome = ua.indexOf('chrome') !== -1,
415 android = ua.indexOf('android') !== -1,
416 android23 = ua.search('android [23]') !== -1,
418 mobile = typeof orientation !== undefined + '',
419 msTouch = window.navigator && window.navigator.msPointerEnabled &&
420 window.navigator.msMaxTouchPoints,
421 retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
422 ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
423 window.matchMedia('(min-resolution:144dpi)').matches),
425 doc = document.documentElement,
426 ie3d = ie && ('transition' in doc.style),
427 webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
428 gecko3d = 'MozPerspective' in doc.style,
429 opera3d = 'OTransition' in doc.style,
430 any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d);
433 var touch = !window.L_NO_TOUCH && (function () {
435 var startName = 'ontouchstart';
437 // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.MsTouch) or WebKit, etc.
438 if (msTouch || (startName in doc)) {
443 var div = document.createElement('div'),
446 if (!div.setAttribute) {
449 div.setAttribute(startName, 'return;');
451 if (typeof div[startName] === 'function') {
455 div.removeAttribute(startName);
469 android23: android23,
480 mobileWebkit: mobile && webkit,
481 mobileWebkit3d: mobile && webkit3d,
482 mobileOpera: mobile && window.opera,
494 * L.Point represents a point with x and y coordinates.
497 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
498 this.x = (round ? Math.round(x) : x);
499 this.y = (round ? Math.round(y) : y);
502 L.Point.prototype = {
505 return new L.Point(this.x, this.y);
508 // non-destructive, returns a new point
509 add: function (point) {
510 return this.clone()._add(L.point(point));
513 // destructive, used directly for performance in situations where it's safe to modify existing point
514 _add: function (point) {
520 subtract: function (point) {
521 return this.clone()._subtract(L.point(point));
524 _subtract: function (point) {
530 divideBy: function (num) {
531 return this.clone()._divideBy(num);
534 _divideBy: function (num) {
540 multiplyBy: function (num) {
541 return this.clone()._multiplyBy(num);
544 _multiplyBy: function (num) {
551 return this.clone()._round();
554 _round: function () {
555 this.x = Math.round(this.x);
556 this.y = Math.round(this.y);
561 return this.clone()._floor();
564 _floor: function () {
565 this.x = Math.floor(this.x);
566 this.y = Math.floor(this.y);
570 distanceTo: function (point) {
571 point = L.point(point);
573 var x = point.x - this.x,
574 y = point.y - this.y;
576 return Math.sqrt(x * x + y * y);
579 equals: function (point) {
580 return point.x === this.x &&
584 toString: function () {
586 L.Util.formatNum(this.x) + ', ' +
587 L.Util.formatNum(this.y) + ')';
591 L.point = function (x, y, round) {
592 if (x instanceof L.Point) {
595 if (L.Util.isArray(x)) {
596 return new L.Point(x[0], x[1]);
601 return new L.Point(x, y, round);
606 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
609 L.Bounds = function (a, b) { //(Point, Point) or Point[]
612 var points = b ? [a, b] : a;
614 for (var i = 0, len = points.length; i < len; i++) {
615 this.extend(points[i]);
619 L.Bounds.prototype = {
620 // extend the bounds to contain the given point
621 extend: function (point) { // (Point)
622 point = L.point(point);
624 if (!this.min && !this.max) {
625 this.min = point.clone();
626 this.max = point.clone();
628 this.min.x = Math.min(point.x, this.min.x);
629 this.max.x = Math.max(point.x, this.max.x);
630 this.min.y = Math.min(point.y, this.min.y);
631 this.max.y = Math.max(point.y, this.max.y);
636 getCenter: function (round) { // (Boolean) -> Point
638 (this.min.x + this.max.x) / 2,
639 (this.min.y + this.max.y) / 2, round);
642 getBottomLeft: function () { // -> Point
643 return new L.Point(this.min.x, this.max.y);
646 getTopRight: function () { // -> Point
647 return new L.Point(this.max.x, this.min.y);
650 getSize: function () {
651 return this.max.subtract(this.min);
654 contains: function (obj) { // (Bounds) or (Point) -> Boolean
657 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
663 if (obj instanceof L.Bounds) {
670 return (min.x >= this.min.x) &&
671 (max.x <= this.max.x) &&
672 (min.y >= this.min.y) &&
673 (max.y <= this.max.y);
676 intersects: function (bounds) { // (Bounds) -> Boolean
677 bounds = L.bounds(bounds);
683 xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
684 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
686 return xIntersects && yIntersects;
689 isValid: function () {
690 return !!(this.min && this.max);
694 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
695 if (!a || a instanceof L.Bounds) {
698 return new L.Bounds(a, b);
703 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
706 L.Transformation = function (a, b, c, d) {
713 L.Transformation.prototype = {
714 transform: function (point, scale) { // (Point, Number) -> Point
715 return this._transform(point.clone(), scale);
718 // destructive transform (faster)
719 _transform: function (point, scale) {
721 point.x = scale * (this._a * point.x + this._b);
722 point.y = scale * (this._c * point.y + this._d);
726 untransform: function (point, scale) {
729 (point.x / scale - this._b) / this._a,
730 (point.y / scale - this._d) / this._c);
736 * L.DomUtil contains various utility functions for working with DOM.
741 return (typeof id === 'string' ? document.getElementById(id) : id);
744 getStyle: function (el, style) {
746 var value = el.style[style];
748 if (!value && el.currentStyle) {
749 value = el.currentStyle[style];
752 if ((!value || value === 'auto') && document.defaultView) {
753 var css = document.defaultView.getComputedStyle(el, null);
754 value = css ? css[style] : null;
757 return value === 'auto' ? null : value;
760 getViewportOffset: function (element) {
765 docBody = document.body,
770 top += el.offsetTop || 0;
771 left += el.offsetLeft || 0;
774 top += parseInt(L.DomUtil.getStyle(el, "borderTopWidth"), 10) || 0;
775 left += parseInt(L.DomUtil.getStyle(el, "borderLeftWidth"), 10) || 0;
777 pos = L.DomUtil.getStyle(el, 'position');
779 if (el.offsetParent === docBody && pos === 'absolute') { break; }
781 if (pos === 'fixed') {
782 top += docBody.scrollTop || 0;
783 left += docBody.scrollLeft || 0;
786 el = el.offsetParent;
793 if (el === docBody) { break; }
795 top -= el.scrollTop || 0;
796 left -= el.scrollLeft || 0;
798 // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
799 // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
800 if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
801 left += el.scrollWidth - el.clientWidth;
803 // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
804 // need to add it back in if it is visible; scrollbar is on the left as we are RTL
805 if (ie7 && L.DomUtil.getStyle(el, 'overflow-y') !== 'hidden' &&
806 L.DomUtil.getStyle(el, 'overflow') !== 'hidden') {
814 return new L.Point(left, top);
817 documentIsLtr: function () {
818 if (!L.DomUtil._docIsLtrCached) {
819 L.DomUtil._docIsLtrCached = true;
820 L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === "ltr";
822 return L.DomUtil._docIsLtr;
825 create: function (tagName, className, container) {
827 var el = document.createElement(tagName);
828 el.className = className;
831 container.appendChild(el);
837 disableTextSelection: function () {
838 if (document.selection && document.selection.empty) {
839 document.selection.empty();
841 if (!this._onselectstart) {
842 this._onselectstart = document.onselectstart || null;
843 document.onselectstart = L.Util.falseFn;
847 enableTextSelection: function () {
848 if (document.onselectstart === L.Util.falseFn) {
849 document.onselectstart = this._onselectstart;
850 this._onselectstart = null;
854 hasClass: function (el, name) {
855 return (el.className.length > 0) &&
856 new RegExp("(^|\\s)" + name + "(\\s|$)").test(el.className);
859 addClass: function (el, name) {
860 if (!L.DomUtil.hasClass(el, name)) {
861 el.className += (el.className ? ' ' : '') + name;
865 removeClass: function (el, name) {
867 function replaceFn(w, match) {
868 if (match === name) { return ''; }
872 el.className = el.className
873 .replace(/(\S+)\s*/g, replaceFn)
874 .replace(/(^\s+|\s+$)/, '');
877 setOpacity: function (el, value) {
879 if ('opacity' in el.style) {
880 el.style.opacity = value;
882 } else if ('filter' in el.style) {
885 filterName = 'DXImageTransform.Microsoft.Alpha';
887 // filters collection throws an error if we try to retrieve a filter that doesn't exist
888 try { filter = el.filters.item(filterName); } catch (e) {}
890 value = Math.round(value * 100);
893 filter.Enabled = (value !== 100);
894 filter.Opacity = value;
896 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
901 testProp: function (props) {
903 var style = document.documentElement.style;
905 for (var i = 0; i < props.length; i++) {
906 if (props[i] in style) {
913 getTranslateString: function (point) {
914 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
915 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
916 // (same speed either way), Opera 12 doesn't support translate3d
918 var is3d = L.Browser.webkit3d,
919 open = 'translate' + (is3d ? '3d' : '') + '(',
920 close = (is3d ? ',0' : '') + ')';
922 return open + point.x + 'px,' + point.y + 'px' + close;
925 getScaleString: function (scale, origin) {
927 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
928 scaleStr = ' scale(' + scale + ') ';
930 return preTranslateStr + scaleStr;
933 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
935 el._leaflet_pos = point;
937 if (!disable3D && L.Browser.any3d) {
938 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
940 // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
941 if (L.Browser.mobileWebkit3d) {
942 el.style.WebkitBackfaceVisibility = 'hidden';
945 el.style.left = point.x + 'px';
946 el.style.top = point.y + 'px';
950 getPosition: function (el) {
951 // this method is only used for elements previously positioned using setPosition,
952 // so it's safe to cache the position for performance
953 return el._leaflet_pos;
958 // prefix style property names
960 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
961 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
963 // webkitTransition comes first because some browser versions that drop vendor prefix don't do
964 // the same for the transitionend event, in particular the Android 4.1 stock browser
966 L.DomUtil.TRANSITION = L.DomUtil.testProp(
967 ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
969 L.DomUtil.TRANSITION_END =
970 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
971 L.DomUtil.TRANSITION + 'End' : 'transitionend';
975 * L.LatLng represents a geographical point with latitude and longitude coordinates.
978 L.LatLng = function (rawLat, rawLng) { // (Number, Number)
979 var lat = parseFloat(rawLat),
980 lng = parseFloat(rawLng);
982 if (isNaN(lat) || isNaN(lng)) {
983 throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
991 DEG_TO_RAD: Math.PI / 180,
992 RAD_TO_DEG: 180 / Math.PI,
993 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
996 L.LatLng.prototype = {
997 equals: function (obj) { // (LatLng) -> Boolean
998 if (!obj) { return false; }
1000 obj = L.latLng(obj);
1002 var margin = Math.max(
1003 Math.abs(this.lat - obj.lat),
1004 Math.abs(this.lng - obj.lng));
1006 return margin <= L.LatLng.MAX_MARGIN;
1009 toString: function (precision) { // (Number) -> String
1011 L.Util.formatNum(this.lat, precision) + ', ' +
1012 L.Util.formatNum(this.lng, precision) + ')';
1015 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1016 // TODO move to projection code, LatLng shouldn't know about Earth
1017 distanceTo: function (other) { // (LatLng) -> Number
1018 other = L.latLng(other);
1020 var R = 6378137, // earth radius in meters
1021 d2r = L.LatLng.DEG_TO_RAD,
1022 dLat = (other.lat - this.lat) * d2r,
1023 dLon = (other.lng - this.lng) * d2r,
1024 lat1 = this.lat * d2r,
1025 lat2 = other.lat * d2r,
1026 sin1 = Math.sin(dLat / 2),
1027 sin2 = Math.sin(dLon / 2);
1029 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1031 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1034 wrap: function (a, b) { // (Number, Number) -> LatLng
1040 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1042 return new L.LatLng(this.lat, lng);
1046 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1047 if (a instanceof L.LatLng) {
1050 if (L.Util.isArray(a)) {
1051 return new L.LatLng(a[0], a[1]);
1056 return new L.LatLng(a, b);
1062 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1065 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1066 if (!southWest) { return; }
1068 var latlngs = northEast ? [southWest, northEast] : southWest;
1070 for (var i = 0, len = latlngs.length; i < len; i++) {
1071 this.extend(latlngs[i]);
1075 L.LatLngBounds.prototype = {
1076 // extend the bounds to contain the given point or bounds
1077 extend: function (obj) { // (LatLng) or (LatLngBounds)
1078 if (typeof obj[0] === 'number' || typeof obj[0] === 'string' || obj instanceof L.LatLng) {
1079 obj = L.latLng(obj);
1081 obj = L.latLngBounds(obj);
1084 if (obj instanceof L.LatLng) {
1085 if (!this._southWest && !this._northEast) {
1086 this._southWest = new L.LatLng(obj.lat, obj.lng);
1087 this._northEast = new L.LatLng(obj.lat, obj.lng);
1089 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1090 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1092 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1093 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1095 } else if (obj instanceof L.LatLngBounds) {
1096 this.extend(obj._southWest);
1097 this.extend(obj._northEast);
1102 // extend the bounds by a percentage
1103 pad: function (bufferRatio) { // (Number) -> LatLngBounds
1104 var sw = this._southWest,
1105 ne = this._northEast,
1106 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1107 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1109 return new L.LatLngBounds(
1110 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1111 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1114 getCenter: function () { // -> LatLng
1115 return new L.LatLng(
1116 (this._southWest.lat + this._northEast.lat) / 2,
1117 (this._southWest.lng + this._northEast.lng) / 2);
1120 getSouthWest: function () {
1121 return this._southWest;
1124 getNorthEast: function () {
1125 return this._northEast;
1128 getNorthWest: function () {
1129 return new L.LatLng(this._northEast.lat, this._southWest.lng);
1132 getSouthEast: function () {
1133 return new L.LatLng(this._southWest.lat, this._northEast.lng);
1136 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1137 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1138 obj = L.latLng(obj);
1140 obj = L.latLngBounds(obj);
1143 var sw = this._southWest,
1144 ne = this._northEast,
1147 if (obj instanceof L.LatLngBounds) {
1148 sw2 = obj.getSouthWest();
1149 ne2 = obj.getNorthEast();
1154 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1155 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1158 intersects: function (bounds) { // (LatLngBounds)
1159 bounds = L.latLngBounds(bounds);
1161 var sw = this._southWest,
1162 ne = this._northEast,
1163 sw2 = bounds.getSouthWest(),
1164 ne2 = bounds.getNorthEast(),
1166 latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1167 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1169 return latIntersects && lngIntersects;
1172 toBBoxString: function () {
1173 var sw = this._southWest,
1174 ne = this._northEast;
1176 return [sw.lng, sw.lat, ne.lng, ne.lat].join(',');
1179 equals: function (bounds) { // (LatLngBounds)
1180 if (!bounds) { return false; }
1182 bounds = L.latLngBounds(bounds);
1184 return this._southWest.equals(bounds.getSouthWest()) &&
1185 this._northEast.equals(bounds.getNorthEast());
1188 isValid: function () {
1189 return !!(this._southWest && this._northEast);
1193 //TODO International date line?
1195 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1196 if (!a || a instanceof L.LatLngBounds) {
1199 return new L.LatLngBounds(a, b);
1204 * L.Projection contains various geographical projections used by CRS classes.
1211 * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1214 L.Projection.SphericalMercator = {
1215 MAX_LATITUDE: 85.0511287798,
1217 project: function (latlng) { // (LatLng) -> Point
1218 var d = L.LatLng.DEG_TO_RAD,
1219 max = this.MAX_LATITUDE,
1220 lat = Math.max(Math.min(max, latlng.lat), -max),
1224 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1226 return new L.Point(x, y);
1229 unproject: function (point) { // (Point, Boolean) -> LatLng
1230 var d = L.LatLng.RAD_TO_DEG,
1232 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1234 return new L.LatLng(lat, lng);
1240 * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1243 L.Projection.LonLat = {
1244 project: function (latlng) {
1245 return new L.Point(latlng.lng, latlng.lat);
1248 unproject: function (point) {
1249 return new L.LatLng(point.y, point.x);
1255 * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1259 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1260 var projectedPoint = this.projection.project(latlng),
1261 scale = this.scale(zoom);
1263 return this.transformation._transform(projectedPoint, scale);
1266 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1267 var scale = this.scale(zoom),
1268 untransformedPoint = this.transformation.untransform(point, scale);
1270 return this.projection.unproject(untransformedPoint);
1273 project: function (latlng) {
1274 return this.projection.project(latlng);
1277 scale: function (zoom) {
1278 return 256 * Math.pow(2, zoom);
1284 * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1287 L.CRS.Simple = L.extend({}, L.CRS, {
1288 projection: L.Projection.LonLat,
1289 transformation: new L.Transformation(1, 0, -1, 0),
1291 scale: function (zoom) {
1292 return Math.pow(2, zoom);
1298 * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1299 * and is used by Leaflet by default.
1302 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1305 projection: L.Projection.SphericalMercator,
1306 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1308 project: function (latlng) { // (LatLng) -> Point
1309 var projectedPoint = this.projection.project(latlng),
1310 earthRadius = 6378137;
1311 return projectedPoint.multiplyBy(earthRadius);
1315 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1321 * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1324 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1327 projection: L.Projection.LonLat,
1328 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1333 * L.Map is the central class of the API - it is used to create a map.
1336 L.Map = L.Class.extend({
1338 includes: L.Mixin.Events,
1341 crs: L.CRS.EPSG3857,
1349 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1351 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1354 initialize: function (id, options) { // (HTMLElement or String, Object)
1355 options = L.setOptions(this, options);
1357 this._initContainer(id);
1359 this.callInitHooks();
1362 if (options.maxBounds) {
1363 this.setMaxBounds(options.maxBounds);
1366 if (options.center && options.zoom !== undefined) {
1367 this.setView(L.latLng(options.center), options.zoom, true);
1370 this._initLayers(options.layers);
1374 // public methods that modify map state
1376 // replaced by animation-powered implementation in Map.PanAnimation.js
1377 setView: function (center, zoom) {
1378 this._resetView(L.latLng(center), this._limitZoom(zoom));
1382 setZoom: function (zoom) { // (Number)
1383 return this.setView(this.getCenter(), zoom);
1386 zoomIn: function (delta) {
1387 return this.setZoom(this._zoom + (delta || 1));
1390 zoomOut: function (delta) {
1391 return this.setZoom(this._zoom - (delta || 1));
1394 fitBounds: function (bounds) { // (LatLngBounds)
1395 var zoom = this.getBoundsZoom(bounds);
1396 return this.setView(L.latLngBounds(bounds).getCenter(), zoom);
1399 fitWorld: function () {
1400 var sw = new L.LatLng(-60, -170),
1401 ne = new L.LatLng(85, 179);
1403 return this.fitBounds(new L.LatLngBounds(sw, ne));
1406 panTo: function (center) { // (LatLng)
1407 return this.setView(center, this._zoom);
1410 panBy: function (offset) { // (Point)
1411 // replaced with animated panBy in Map.Animation.js
1412 this.fire('movestart');
1414 this._rawPanBy(L.point(offset));
1417 return this.fire('moveend');
1420 setMaxBounds: function (bounds) {
1421 bounds = L.latLngBounds(bounds);
1423 this.options.maxBounds = bounds;
1426 this._boundsMinZoom = null;
1430 var minZoom = this.getBoundsZoom(bounds, true);
1432 this._boundsMinZoom = minZoom;
1435 if (this._zoom < minZoom) {
1436 this.setView(bounds.getCenter(), minZoom);
1438 this.panInsideBounds(bounds);
1445 panInsideBounds: function (bounds) {
1446 bounds = L.latLngBounds(bounds);
1448 var viewBounds = this.getBounds(),
1449 viewSw = this.project(viewBounds.getSouthWest()),
1450 viewNe = this.project(viewBounds.getNorthEast()),
1451 sw = this.project(bounds.getSouthWest()),
1452 ne = this.project(bounds.getNorthEast()),
1456 if (viewNe.y < ne.y) { // north
1457 dy = ne.y - viewNe.y;
1459 if (viewNe.x > ne.x) { // east
1460 dx = ne.x - viewNe.x;
1462 if (viewSw.y > sw.y) { // south
1463 dy = sw.y - viewSw.y;
1465 if (viewSw.x < sw.x) { // west
1466 dx = sw.x - viewSw.x;
1469 return this.panBy(new L.Point(dx, dy, true));
1472 addLayer: function (layer) {
1473 // TODO method is too big, refactor
1475 var id = L.stamp(layer);
1477 if (this._layers[id]) { return this; }
1479 this._layers[id] = layer;
1481 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1482 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1483 this._zoomBoundLayers[id] = layer;
1484 this._updateZoomLevels();
1487 // TODO looks ugly, refactor!!!
1488 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1489 this._tileLayersNum++;
1490 this._tileLayersToLoad++;
1491 layer.on('load', this._onTileLayerLoad, this);
1494 this.whenReady(function () {
1496 this.fire('layeradd', {layer: layer});
1502 removeLayer: function (layer) {
1503 var id = L.stamp(layer);
1505 if (!this._layers[id]) { return; }
1507 layer.onRemove(this);
1509 delete this._layers[id];
1510 if (this._zoomBoundLayers[id]) {
1511 delete this._zoomBoundLayers[id];
1512 this._updateZoomLevels();
1515 // TODO looks ugly, refactor
1516 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1517 this._tileLayersNum--;
1518 this._tileLayersToLoad--;
1519 layer.off('load', this._onTileLayerLoad, this);
1522 return this.fire('layerremove', {layer: layer});
1525 hasLayer: function (layer) {
1526 var id = L.stamp(layer);
1527 return this._layers.hasOwnProperty(id);
1530 invalidateSize: function (animate) {
1531 var oldSize = this.getSize();
1533 this._sizeChanged = true;
1535 if (this.options.maxBounds) {
1536 this.setMaxBounds(this.options.maxBounds);
1539 if (!this._loaded) { return this; }
1541 var offset = oldSize._subtract(this.getSize())._divideBy(2)._round();
1543 if (animate === true) {
1546 this._rawPanBy(offset);
1550 clearTimeout(this._sizeTimer);
1551 this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1556 // TODO handler.addTo
1557 addHandler: function (name, HandlerClass) {
1558 if (!HandlerClass) { return; }
1560 this[name] = new HandlerClass(this);
1562 if (this.options[name]) {
1563 this[name].enable();
1570 // public methods for getting map state
1572 getCenter: function () { // (Boolean) -> LatLng
1573 return this.layerPointToLatLng(this._getCenterLayerPoint());
1576 getZoom: function () {
1580 getBounds: function () {
1581 var bounds = this.getPixelBounds(),
1582 sw = this.unproject(bounds.getBottomLeft()),
1583 ne = this.unproject(bounds.getTopRight());
1585 return new L.LatLngBounds(sw, ne);
1588 getMinZoom: function () {
1589 var z1 = this.options.minZoom || 0,
1590 z2 = this._layersMinZoom || 0,
1591 z3 = this._boundsMinZoom || 0;
1593 return Math.max(z1, z2, z3);
1596 getMaxZoom: function () {
1597 var z1 = this.options.maxZoom === undefined ? Infinity : this.options.maxZoom,
1598 z2 = this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom;
1600 return Math.min(z1, z2);
1603 getBoundsZoom: function (bounds, inside) { // (LatLngBounds, Boolean) -> Number
1604 bounds = L.latLngBounds(bounds);
1606 var size = this.getSize(),
1607 zoom = this.options.minZoom || 0,
1608 maxZoom = this.getMaxZoom(),
1609 ne = bounds.getNorthEast(),
1610 sw = bounds.getSouthWest(),
1614 zoomNotFound = true;
1622 nePoint = this.project(ne, zoom);
1623 swPoint = this.project(sw, zoom);
1625 boundsSize = new L.Point(
1626 Math.abs(nePoint.x - swPoint.x),
1627 Math.abs(swPoint.y - nePoint.y));
1630 zoomNotFound = boundsSize.x <= size.x && boundsSize.y <= size.y;
1632 zoomNotFound = boundsSize.x < size.x || boundsSize.y < size.y;
1634 } while (zoomNotFound && zoom <= maxZoom);
1636 if (zoomNotFound && inside) {
1640 return inside ? zoom : zoom - 1;
1643 getSize: function () {
1644 if (!this._size || this._sizeChanged) {
1645 this._size = new L.Point(
1646 this._container.clientWidth,
1647 this._container.clientHeight);
1649 this._sizeChanged = false;
1651 return this._size.clone();
1654 getPixelBounds: function () {
1655 var topLeftPoint = this._getTopLeftPoint();
1656 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1659 getPixelOrigin: function () {
1660 return this._initialTopLeftPoint;
1663 getPanes: function () {
1667 getContainer: function () {
1668 return this._container;
1672 // TODO replace with universal implementation after refactoring projections
1674 getZoomScale: function (toZoom) {
1675 var crs = this.options.crs;
1676 return crs.scale(toZoom) / crs.scale(this._zoom);
1679 getScaleZoom: function (scale) {
1680 return this._zoom + (Math.log(scale) / Math.LN2);
1684 // conversion methods
1686 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1687 zoom = zoom === undefined ? this._zoom : zoom;
1688 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1691 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1692 zoom = zoom === undefined ? this._zoom : zoom;
1693 return this.options.crs.pointToLatLng(L.point(point), zoom);
1696 layerPointToLatLng: function (point) { // (Point)
1697 var projectedPoint = L.point(point).add(this._initialTopLeftPoint);
1698 return this.unproject(projectedPoint);
1701 latLngToLayerPoint: function (latlng) { // (LatLng)
1702 var projectedPoint = this.project(L.latLng(latlng))._round();
1703 return projectedPoint._subtract(this._initialTopLeftPoint);
1706 containerPointToLayerPoint: function (point) { // (Point)
1707 return L.point(point).subtract(this._getMapPanePos());
1710 layerPointToContainerPoint: function (point) { // (Point)
1711 return L.point(point).add(this._getMapPanePos());
1714 containerPointToLatLng: function (point) {
1715 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1716 return this.layerPointToLatLng(layerPoint);
1719 latLngToContainerPoint: function (latlng) {
1720 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1723 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1724 return L.DomEvent.getMousePosition(e, this._container);
1727 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1728 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1731 mouseEventToLatLng: function (e) { // (MouseEvent)
1732 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1736 // map initialization methods
1738 _initContainer: function (id) {
1739 var container = this._container = L.DomUtil.get(id);
1741 if (container._leaflet) {
1742 throw new Error("Map container is already initialized.");
1745 container._leaflet = true;
1748 _initLayout: function () {
1749 var container = this._container;
1751 L.DomUtil.addClass(container, 'leaflet-container');
1753 if (L.Browser.touch) {
1754 L.DomUtil.addClass(container, 'leaflet-touch');
1757 if (this.options.fadeAnimation) {
1758 L.DomUtil.addClass(container, 'leaflet-fade-anim');
1761 var position = L.DomUtil.getStyle(container, 'position');
1763 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
1764 container.style.position = 'relative';
1769 if (this._initControlPos) {
1770 this._initControlPos();
1774 _initPanes: function () {
1775 var panes = this._panes = {};
1777 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
1779 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
1780 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
1781 panes.shadowPane = this._createPane('leaflet-shadow-pane');
1782 panes.overlayPane = this._createPane('leaflet-overlay-pane');
1783 panes.markerPane = this._createPane('leaflet-marker-pane');
1784 panes.popupPane = this._createPane('leaflet-popup-pane');
1786 var zoomHide = ' leaflet-zoom-hide';
1788 if (!this.options.markerZoomAnimation) {
1789 L.DomUtil.addClass(panes.markerPane, zoomHide);
1790 L.DomUtil.addClass(panes.shadowPane, zoomHide);
1791 L.DomUtil.addClass(panes.popupPane, zoomHide);
1795 _createPane: function (className, container) {
1796 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
1799 _initLayers: function (layers) {
1800 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
1803 this._zoomBoundLayers = {};
1804 this._tileLayersNum = 0;
1808 for (i = 0, len = layers.length; i < len; i++) {
1809 this.addLayer(layers[i]);
1814 // private methods that modify map state
1816 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
1818 var zoomChanged = (this._zoom !== zoom);
1820 if (!afterZoomAnim) {
1821 this.fire('movestart');
1824 this.fire('zoomstart');
1830 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
1832 if (!preserveMapOffset) {
1833 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
1835 this._initialTopLeftPoint._add(this._getMapPanePos());
1838 this._tileLayersToLoad = this._tileLayersNum;
1840 var loading = !this._loaded;
1841 this._loaded = true;
1843 this.fire('viewreset', {hard: !preserveMapOffset});
1847 if (zoomChanged || afterZoomAnim) {
1848 this.fire('zoomend');
1851 this.fire('moveend', {hard: !preserveMapOffset});
1858 _rawPanBy: function (offset) {
1859 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
1862 _updateZoomLevels: function () {
1865 maxZoom = -Infinity;
1867 for (i in this._zoomBoundLayers) {
1868 if (this._zoomBoundLayers.hasOwnProperty(i)) {
1869 var layer = this._zoomBoundLayers[i];
1870 if (!isNaN(layer.options.minZoom)) {
1871 minZoom = Math.min(minZoom, layer.options.minZoom);
1873 if (!isNaN(layer.options.maxZoom)) {
1874 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
1879 if (i === undefined) { // we have no tilelayers
1880 this._layersMaxZoom = this._layersMinZoom = undefined;
1882 this._layersMaxZoom = maxZoom;
1883 this._layersMinZoom = minZoom;
1889 _initEvents: function () {
1890 if (!L.DomEvent) { return; }
1892 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
1894 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
1895 'mouseleave', 'mousemove', 'contextmenu'],
1898 for (i = 0, len = events.length; i < len; i++) {
1899 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
1902 if (this.options.trackResize) {
1903 L.DomEvent.on(window, 'resize', this._onResize, this);
1907 _onResize: function () {
1908 L.Util.cancelAnimFrame(this._resizeRequest);
1909 this._resizeRequest = L.Util.requestAnimFrame(
1910 this.invalidateSize, this, false, this._container);
1913 _onMouseClick: function (e) {
1914 if (!this._loaded || (this.dragging && this.dragging.moved())) { return; }
1916 this.fire('preclick');
1917 this._fireMouseEvent(e);
1920 _fireMouseEvent: function (e) {
1921 if (!this._loaded) { return; }
1925 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
1927 if (!this.hasEventListeners(type)) { return; }
1929 if (type === 'contextmenu') {
1930 L.DomEvent.preventDefault(e);
1933 var containerPoint = this.mouseEventToContainerPoint(e),
1934 layerPoint = this.containerPointToLayerPoint(containerPoint),
1935 latlng = this.layerPointToLatLng(layerPoint);
1939 layerPoint: layerPoint,
1940 containerPoint: containerPoint,
1945 _onTileLayerLoad: function () {
1946 // TODO super-ugly, refactor!!!
1947 // clear scaled tiles after all new tiles are loaded (for performance)
1948 this._tileLayersToLoad--;
1949 if (this._tileLayersNum && !this._tileLayersToLoad && this._tileBg) {
1950 clearTimeout(this._clearTileBgTimer);
1951 this._clearTileBgTimer = setTimeout(L.bind(this._clearTileBg, this), 500);
1955 whenReady: function (callback, context) {
1957 callback.call(context || this, this);
1959 this.on('load', callback, context);
1965 // private methods for getting map state
1967 _getMapPanePos: function () {
1968 return L.DomUtil.getPosition(this._mapPane);
1971 _getTopLeftPoint: function () {
1972 if (!this._loaded) {
1973 throw new Error('Set map center and zoom first.');
1976 return this._initialTopLeftPoint.subtract(this._getMapPanePos());
1979 _getNewTopLeftPoint: function (center, zoom) {
1980 var viewHalf = this.getSize()._divideBy(2);
1981 // TODO round on display, not calculation to increase precision?
1982 return this.project(center, zoom)._subtract(viewHalf)._round();
1985 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
1986 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
1987 return this.project(latlng, newZoom)._subtract(topLeft);
1990 _getCenterLayerPoint: function () {
1991 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
1994 _getCenterOffset: function (center) {
1995 return this.latLngToLayerPoint(center).subtract(this._getCenterLayerPoint());
1998 _limitZoom: function (zoom) {
1999 var min = this.getMinZoom(),
2000 max = this.getMaxZoom();
2002 return Math.max(min, Math.min(max, zoom));
2006 L.map = function (id, options) {
2007 return new L.Map(id, options);
2012 * Mercator projection that takes into account that the Earth is not a perfect sphere.
2013 * Less popular than spherical mercator; used by projections like EPSG:3395.
2016 L.Projection.Mercator = {
2017 MAX_LATITUDE: 85.0840591556,
2019 R_MINOR: 6356752.3142,
2022 project: function (latlng) { // (LatLng) -> Point
2023 var d = L.LatLng.DEG_TO_RAD,
2024 max = this.MAX_LATITUDE,
2025 lat = Math.max(Math.min(max, latlng.lat), -max),
2028 x = latlng.lng * d * r,
2031 eccent = Math.sqrt(1.0 - tmp * tmp),
2032 con = eccent * Math.sin(y);
2034 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2036 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2037 y = -r2 * Math.log(ts);
2039 return new L.Point(x, y);
2042 unproject: function (point) { // (Point, Boolean) -> LatLng
2043 var d = L.LatLng.RAD_TO_DEG,
2046 lng = point.x * d / r,
2048 eccent = Math.sqrt(1 - (tmp * tmp)),
2049 ts = Math.exp(- point.y / r2),
2050 phi = (Math.PI / 2) - 2 * Math.atan(ts),
2057 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2058 con = eccent * Math.sin(phi);
2059 dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2060 Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2064 return new L.LatLng(phi * d, lng);
2070 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2073 projection: L.Projection.Mercator,
2075 transformation: (function () {
2076 var m = L.Projection.Mercator,
2080 return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
2086 * L.TileLayer is used for standard xyz-numbered tile layers.
2089 L.TileLayer = L.Class.extend({
2090 includes: L.Mixin.Events,
2101 /* (undefined works too)
2104 continuousWorld: false,
2107 detectRetina: false,
2110 unloadInvisibleTiles: L.Browser.mobile,
2111 updateWhenIdle: L.Browser.mobile
2114 initialize: function (url, options) {
2115 options = L.setOptions(this, options);
2117 // detecting retina displays, adjusting tileSize and zoom levels
2118 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2120 options.tileSize = Math.floor(options.tileSize / 2);
2121 options.zoomOffset++;
2123 if (options.minZoom > 0) {
2126 this.options.maxZoom--;
2131 var subdomains = this.options.subdomains;
2133 if (typeof subdomains === 'string') {
2134 this.options.subdomains = subdomains.split('');
2138 onAdd: function (map) {
2141 // create a container div for tiles
2142 this._initContainer();
2144 // create an image to clone for tiles
2145 this._createTileProto();
2149 'viewreset': this._resetCallback,
2150 'moveend': this._update
2153 if (!this.options.updateWhenIdle) {
2154 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2155 map.on('move', this._limitedUpdate, this);
2162 addTo: function (map) {
2167 onRemove: function (map) {
2168 this._container.parentNode.removeChild(this._container);
2171 'viewreset': this._resetCallback,
2172 'moveend': this._update
2175 if (!this.options.updateWhenIdle) {
2176 map.off('move', this._limitedUpdate, this);
2179 this._container = null;
2183 bringToFront: function () {
2184 var pane = this._map._panes.tilePane;
2186 if (this._container) {
2187 pane.appendChild(this._container);
2188 this._setAutoZIndex(pane, Math.max);
2194 bringToBack: function () {
2195 var pane = this._map._panes.tilePane;
2197 if (this._container) {
2198 pane.insertBefore(this._container, pane.firstChild);
2199 this._setAutoZIndex(pane, Math.min);
2205 getAttribution: function () {
2206 return this.options.attribution;
2209 setOpacity: function (opacity) {
2210 this.options.opacity = opacity;
2213 this._updateOpacity();
2219 setZIndex: function (zIndex) {
2220 this.options.zIndex = zIndex;
2221 this._updateZIndex();
2226 setUrl: function (url, noRedraw) {
2236 redraw: function () {
2238 this._map._panes.tilePane.empty = false;
2245 _updateZIndex: function () {
2246 if (this._container && this.options.zIndex !== undefined) {
2247 this._container.style.zIndex = this.options.zIndex;
2251 _setAutoZIndex: function (pane, compare) {
2253 var layers = pane.children,
2254 edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2257 for (i = 0, len = layers.length; i < len; i++) {
2259 if (layers[i] !== this._container) {
2260 zIndex = parseInt(layers[i].style.zIndex, 10);
2262 if (!isNaN(zIndex)) {
2263 edgeZIndex = compare(edgeZIndex, zIndex);
2268 this.options.zIndex = this._container.style.zIndex =
2269 (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2272 _updateOpacity: function () {
2273 L.DomUtil.setOpacity(this._container, this.options.opacity);
2275 // stupid webkit hack to force redrawing of tiles
2277 tiles = this._tiles;
2279 if (L.Browser.webkit) {
2281 if (tiles.hasOwnProperty(i)) {
2282 tiles[i].style.webkitTransform += ' translate(0,0)';
2288 _initContainer: function () {
2289 var tilePane = this._map._panes.tilePane;
2291 if (!this._container || tilePane.empty) {
2292 this._container = L.DomUtil.create('div', 'leaflet-layer');
2294 this._updateZIndex();
2296 tilePane.appendChild(this._container);
2298 if (this.options.opacity < 1) {
2299 this._updateOpacity();
2304 _resetCallback: function (e) {
2305 this._reset(e.hard);
2308 _reset: function (clearOldContainer) {
2309 var tiles = this._tiles;
2311 for (var key in tiles) {
2312 if (tiles.hasOwnProperty(key)) {
2313 this.fire('tileunload', {tile: tiles[key]});
2318 this._tilesToLoad = 0;
2320 if (this.options.reuseTiles) {
2321 this._unusedTiles = [];
2324 if (clearOldContainer && this._container) {
2325 this._container.innerHTML = "";
2328 this._initContainer();
2331 _update: function () {
2333 if (!this._map) { return; }
2335 var bounds = this._map.getPixelBounds(),
2336 zoom = this._map.getZoom(),
2337 tileSize = this.options.tileSize;
2339 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2343 var nwTilePoint = new L.Point(
2344 Math.floor(bounds.min.x / tileSize),
2345 Math.floor(bounds.min.y / tileSize)),
2347 seTilePoint = new L.Point(
2348 Math.floor(bounds.max.x / tileSize),
2349 Math.floor(bounds.max.y / tileSize)),
2351 tileBounds = new L.Bounds(nwTilePoint, seTilePoint);
2353 this._addTilesFromCenterOut(tileBounds);
2355 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2356 this._removeOtherTiles(tileBounds);
2360 _addTilesFromCenterOut: function (bounds) {
2362 center = bounds.getCenter();
2366 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2367 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2368 point = new L.Point(i, j);
2370 if (this._tileShouldBeLoaded(point)) {
2376 var tilesToLoad = queue.length;
2378 if (tilesToLoad === 0) { return; }
2380 // load tiles in order of their distance to center
2381 queue.sort(function (a, b) {
2382 return a.distanceTo(center) - b.distanceTo(center);
2385 var fragment = document.createDocumentFragment();
2387 // if its the first batch of tiles to load
2388 if (!this._tilesToLoad) {
2389 this.fire('loading');
2392 this._tilesToLoad += tilesToLoad;
2394 for (i = 0; i < tilesToLoad; i++) {
2395 this._addTile(queue[i], fragment);
2398 this._container.appendChild(fragment);
2401 _tileShouldBeLoaded: function (tilePoint) {
2402 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2403 return false; // already loaded
2406 if (!this.options.continuousWorld) {
2407 var limit = this._getWrapTileNum();
2409 if (this.options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit) ||
2410 tilePoint.y < 0 || tilePoint.y >= limit) {
2411 return false; // exceeds world bounds
2418 _removeOtherTiles: function (bounds) {
2419 var kArr, x, y, key;
2421 for (key in this._tiles) {
2422 if (this._tiles.hasOwnProperty(key)) {
2423 kArr = key.split(':');
2424 x = parseInt(kArr[0], 10);
2425 y = parseInt(kArr[1], 10);
2427 // remove tile if it's out of bounds
2428 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2429 this._removeTile(key);
2435 _removeTile: function (key) {
2436 var tile = this._tiles[key];
2438 this.fire("tileunload", {tile: tile, url: tile.src});
2440 if (this.options.reuseTiles) {
2441 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2442 this._unusedTiles.push(tile);
2444 } else if (tile.parentNode === this._container) {
2445 this._container.removeChild(tile);
2448 // for https://github.com/CloudMade/Leaflet/issues/137
2449 if (!L.Browser.android) {
2450 tile.src = L.Util.emptyImageUrl;
2453 delete this._tiles[key];
2456 _addTile: function (tilePoint, container) {
2457 var tilePos = this._getTilePos(tilePoint);
2459 // get unused tile - or create a new tile
2460 var tile = this._getTile();
2463 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2464 Android 4 browser has display issues with top/left and requires transform instead
2465 Android 3 browser not tested
2466 Android 2 browser requires top/left or tiles disappear on load or first drag
2467 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2468 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2470 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2472 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2474 this._loadTile(tile, tilePoint);
2476 if (tile.parentNode !== this._container) {
2477 container.appendChild(tile);
2481 _getZoomForUrl: function () {
2483 var options = this.options,
2484 zoom = this._map.getZoom();
2486 if (options.zoomReverse) {
2487 zoom = options.maxZoom - zoom;
2490 return zoom + options.zoomOffset;
2493 _getTilePos: function (tilePoint) {
2494 var origin = this._map.getPixelOrigin(),
2495 tileSize = this.options.tileSize;
2497 return tilePoint.multiplyBy(tileSize).subtract(origin);
2500 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2502 getTileUrl: function (tilePoint) {
2503 this._adjustTilePoint(tilePoint);
2505 return L.Util.template(this._url, L.extend({
2506 s: this._getSubdomain(tilePoint),
2507 z: this._getZoomForUrl(),
2513 _getWrapTileNum: function () {
2514 // TODO refactor, limit is not valid for non-standard projections
2515 return Math.pow(2, this._getZoomForUrl());
2518 _adjustTilePoint: function (tilePoint) {
2520 var limit = this._getWrapTileNum();
2522 // wrap tile coordinates
2523 if (!this.options.continuousWorld && !this.options.noWrap) {
2524 tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
2527 if (this.options.tms) {
2528 tilePoint.y = limit - tilePoint.y - 1;
2532 _getSubdomain: function (tilePoint) {
2533 var index = (tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2534 return this.options.subdomains[index];
2537 _createTileProto: function () {
2538 var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
2539 img.style.width = img.style.height = this.options.tileSize + 'px';
2540 img.galleryimg = 'no';
2543 _getTile: function () {
2544 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2545 var tile = this._unusedTiles.pop();
2546 this._resetTile(tile);
2549 return this._createTile();
2552 // Override if data stored on a tile needs to be cleaned up before reuse
2553 _resetTile: function (/*tile*/) {},
2555 _createTile: function () {
2556 var tile = this._tileImg.cloneNode(false);
2557 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2561 _loadTile: function (tile, tilePoint) {
2563 tile.onload = this._tileOnLoad;
2564 tile.onerror = this._tileOnError;
2566 tile.src = this.getTileUrl(tilePoint);
2569 _tileLoaded: function () {
2570 this._tilesToLoad--;
2571 if (!this._tilesToLoad) {
2576 _tileOnLoad: function () {
2577 var layer = this._layer;
2579 //Only if we are loading an actual image
2580 if (this.src !== L.Util.emptyImageUrl) {
2581 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2583 layer.fire('tileload', {
2589 layer._tileLoaded();
2592 _tileOnError: function () {
2593 var layer = this._layer;
2595 layer.fire('tileerror', {
2600 var newUrl = layer.options.errorTileUrl;
2605 layer._tileLoaded();
2609 L.tileLayer = function (url, options) {
2610 return new L.TileLayer(url, options);
2615 * L.TileLayer.WMS is used for putting WMS tile layers on the map.
2618 L.TileLayer.WMS = L.TileLayer.extend({
2626 format: 'image/jpeg',
2630 initialize: function (url, options) { // (String, Object)
2634 var wmsParams = L.extend({}, this.defaultWmsParams);
2636 if (options.detectRetina && L.Browser.retina) {
2637 wmsParams.width = wmsParams.height = this.options.tileSize * 2;
2639 wmsParams.width = wmsParams.height = this.options.tileSize;
2642 for (var i in options) {
2643 // all keys that are not TileLayer options go to WMS params
2644 if (!this.options.hasOwnProperty(i)) {
2645 wmsParams[i] = options[i];
2649 this.wmsParams = wmsParams;
2651 L.setOptions(this, options);
2654 onAdd: function (map) {
2656 var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
2657 this.wmsParams[projectionKey] = map.options.crs.code;
2659 L.TileLayer.prototype.onAdd.call(this, map);
2662 getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
2664 this._adjustTilePoint(tilePoint);
2666 var map = this._map,
2667 crs = map.options.crs,
2668 tileSize = this.options.tileSize,
2670 nwPoint = tilePoint.multiplyBy(tileSize),
2671 sePoint = nwPoint.add(new L.Point(tileSize, tileSize)),
2673 nw = crs.project(map.unproject(nwPoint, zoom)),
2674 se = crs.project(map.unproject(sePoint, zoom)),
2676 bbox = [nw.x, se.y, se.x, nw.y].join(','),
2678 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
2680 return url + L.Util.getParamString(this.wmsParams, url) + "&bbox=" + bbox;
2683 setParams: function (params, noRedraw) {
2685 L.extend(this.wmsParams, params);
2695 L.tileLayer.wms = function (url, options) {
2696 return new L.TileLayer.WMS(url, options);
2701 * L.TileLayer.Canvas is a class that you can use as a base for creating
2702 * dynamically drawn Canvas-based tile layers.
2705 L.TileLayer.Canvas = L.TileLayer.extend({
2710 initialize: function (options) {
2711 L.setOptions(this, options);
2714 redraw: function () {
2715 var tiles = this._tiles;
2717 for (var i in tiles) {
2718 if (tiles.hasOwnProperty(i)) {
2719 this._redrawTile(tiles[i]);
2724 _redrawTile: function (tile) {
2725 this.drawTile(tile, tile._tilePoint, this._map._zoom);
2728 _createTileProto: function () {
2729 var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
2730 proto.width = proto.height = this.options.tileSize;
2733 _createTile: function () {
2734 var tile = this._canvasProto.cloneNode(false);
2735 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2739 _loadTile: function (tile, tilePoint) {
2741 tile._tilePoint = tilePoint;
2743 this._redrawTile(tile);
2745 if (!this.options.async) {
2746 this.tileDrawn(tile);
2750 drawTile: function (/*tile, tilePoint*/) {
2751 // override with rendering code
2754 tileDrawn: function (tile) {
2755 this._tileOnLoad.call(tile);
2760 L.tileLayer.canvas = function (options) {
2761 return new L.TileLayer.Canvas(options);
2766 * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
2769 L.ImageOverlay = L.Class.extend({
2770 includes: L.Mixin.Events,
2776 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
2778 this._bounds = L.latLngBounds(bounds);
2780 L.setOptions(this, options);
2783 onAdd: function (map) {
2790 map._panes.overlayPane.appendChild(this._image);
2792 map.on('viewreset', this._reset, this);
2794 if (map.options.zoomAnimation && L.Browser.any3d) {
2795 map.on('zoomanim', this._animateZoom, this);
2801 onRemove: function (map) {
2802 map.getPanes().overlayPane.removeChild(this._image);
2804 map.off('viewreset', this._reset, this);
2806 if (map.options.zoomAnimation) {
2807 map.off('zoomanim', this._animateZoom, this);
2811 addTo: function (map) {
2816 setOpacity: function (opacity) {
2817 this.options.opacity = opacity;
2818 this._updateOpacity();
2822 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
2823 bringToFront: function () {
2825 this._map._panes.overlayPane.appendChild(this._image);
2830 bringToBack: function () {
2831 var pane = this._map._panes.overlayPane;
2833 pane.insertBefore(this._image, pane.firstChild);
2838 _initImage: function () {
2839 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
2841 if (this._map.options.zoomAnimation && L.Browser.any3d) {
2842 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
2844 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
2847 this._updateOpacity();
2849 //TODO createImage util method to remove duplication
2850 L.extend(this._image, {
2852 onselectstart: L.Util.falseFn,
2853 onmousemove: L.Util.falseFn,
2854 onload: L.bind(this._onImageLoad, this),
2859 _animateZoom: function (e) {
2860 var map = this._map,
2861 image = this._image,
2862 scale = map.getZoomScale(e.zoom),
2863 nw = this._bounds.getNorthWest(),
2864 se = this._bounds.getSouthEast(),
2866 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
2867 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
2868 origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
2870 image.style[L.DomUtil.TRANSFORM] =
2871 L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
2874 _reset: function () {
2875 var image = this._image,
2876 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
2877 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
2879 L.DomUtil.setPosition(image, topLeft);
2881 image.style.width = size.x + 'px';
2882 image.style.height = size.y + 'px';
2885 _onImageLoad: function () {
2889 _updateOpacity: function () {
2890 L.DomUtil.setOpacity(this._image, this.options.opacity);
2894 L.imageOverlay = function (url, bounds, options) {
2895 return new L.ImageOverlay(url, bounds, options);
2900 * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
2903 L.Icon = L.Class.extend({
2906 iconUrl: (String) (required)
2907 iconRetinaUrl: (String) (optional, used for retina devices if detected)
2908 iconSize: (Point) (can be set through CSS)
2909 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
2910 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
2911 shadowUrl: (Point) (no shadow by default)
2912 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
2914 shadowAnchor: (Point)
2919 initialize: function (options) {
2920 L.setOptions(this, options);
2923 createIcon: function () {
2924 return this._createIcon('icon');
2927 createShadow: function () {
2928 return this._createIcon('shadow');
2931 _createIcon: function (name) {
2932 var src = this._getIconUrl(name);
2935 if (name === 'icon') {
2936 throw new Error("iconUrl not set in Icon options (see the docs).");
2941 var img = this._createImg(src);
2942 this._setIconStyles(img, name);
2947 _setIconStyles: function (img, name) {
2948 var options = this.options,
2949 size = L.point(options[name + 'Size']),
2952 if (name === 'shadow') {
2953 anchor = L.point(options.shadowAnchor || options.iconAnchor);
2955 anchor = L.point(options.iconAnchor);
2958 if (!anchor && size) {
2959 anchor = size.divideBy(2, true);
2962 img.className = 'leaflet-marker-' + name + ' ' + options.className;
2965 img.style.marginLeft = (-anchor.x) + 'px';
2966 img.style.marginTop = (-anchor.y) + 'px';
2970 img.style.width = size.x + 'px';
2971 img.style.height = size.y + 'px';
2975 _createImg: function (src) {
2978 if (!L.Browser.ie6) {
2979 el = document.createElement('img');
2982 el = document.createElement('div');
2984 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
2989 _getIconUrl: function (name) {
2990 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
2991 return this.options[name + 'RetinaUrl'];
2993 return this.options[name + 'Url'];
2997 L.icon = function (options) {
2998 return new L.Icon(options);
3003 * L.Icon.Default is the blue marker icon used by default in Leaflet.
3006 L.Icon.Default = L.Icon.extend({
3009 iconSize: new L.Point(25, 41),
3010 iconAnchor: new L.Point(12, 41),
3011 popupAnchor: new L.Point(1, -34),
3013 shadowSize: new L.Point(41, 41)
3016 _getIconUrl: function (name) {
3017 var key = name + 'Url';
3019 if (this.options[key]) {
3020 return this.options[key];
3023 if (L.Browser.retina && name === 'icon') {
3027 var path = L.Icon.Default.imagePath;
3030 throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");
3033 return path + '/marker-' + name + '.png';
3037 L.Icon.Default.imagePath = (function () {
3038 var scripts = document.getElementsByTagName('script'),
3039 leafletRe = /\/?leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3041 var i, len, src, matches;
3043 for (i = 0, len = scripts.length; i < len; i++) {
3044 src = scripts[i].src;
3045 matches = src.match(leafletRe);
3048 return src.split(leafletRe)[0] + '/images';
3055 * L.Marker is used to display clickable/draggable icons on the map.
3058 L.Marker = L.Class.extend({
3060 includes: L.Mixin.Events,
3063 icon: new L.Icon.Default(),
3073 initialize: function (latlng, options) {
3074 L.setOptions(this, options);
3075 this._latlng = L.latLng(latlng);
3078 onAdd: function (map) {
3081 map.on('viewreset', this.update, this);
3086 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3087 map.on('zoomanim', this._animateZoom, this);
3091 addTo: function (map) {
3096 onRemove: function (map) {
3099 this.fire('remove');
3102 'viewreset': this.update,
3103 'zoomanim': this._animateZoom
3109 getLatLng: function () {
3110 return this._latlng;
3113 setLatLng: function (latlng) {
3114 this._latlng = L.latLng(latlng);
3118 return this.fire('move', { latlng: this._latlng });
3121 setZIndexOffset: function (offset) {
3122 this.options.zIndexOffset = offset;
3128 setIcon: function (icon) {
3133 this.options.icon = icon;
3143 update: function () {
3145 var pos = this._map.latLngToLayerPoint(this._latlng).round();
3152 _initIcon: function () {
3153 var options = this.options,
3155 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3156 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide',
3157 needOpacityUpdate = false;
3160 this._icon = options.icon.createIcon();
3162 if (options.title) {
3163 this._icon.title = options.title;
3166 this._initInteraction();
3167 needOpacityUpdate = (this.options.opacity < 1);
3169 L.DomUtil.addClass(this._icon, classToAdd);
3171 if (options.riseOnHover) {
3173 .on(this._icon, 'mouseover', this._bringToFront, this)
3174 .on(this._icon, 'mouseout', this._resetZIndex, this);
3178 if (!this._shadow) {
3179 this._shadow = options.icon.createShadow();
3182 L.DomUtil.addClass(this._shadow, classToAdd);
3183 needOpacityUpdate = (this.options.opacity < 1);
3187 if (needOpacityUpdate) {
3188 this._updateOpacity();
3191 var panes = this._map._panes;
3193 panes.markerPane.appendChild(this._icon);
3196 panes.shadowPane.appendChild(this._shadow);
3200 _removeIcon: function () {
3201 var panes = this._map._panes;
3203 if (this.options.riseOnHover) {
3205 .off(this._icon, 'mouseover', this._bringToFront)
3206 .off(this._icon, 'mouseout', this._resetZIndex);
3209 panes.markerPane.removeChild(this._icon);
3212 panes.shadowPane.removeChild(this._shadow);
3215 this._icon = this._shadow = null;
3218 _setPos: function (pos) {
3219 L.DomUtil.setPosition(this._icon, pos);
3222 L.DomUtil.setPosition(this._shadow, pos);
3225 this._zIndex = pos.y + this.options.zIndexOffset;
3227 this._resetZIndex();
3230 _updateZIndex: function (offset) {
3231 this._icon.style.zIndex = this._zIndex + offset;
3234 _animateZoom: function (opt) {
3235 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3240 _initInteraction: function () {
3242 if (!this.options.clickable) { return; }
3244 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3246 var icon = this._icon,
3247 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3249 L.DomUtil.addClass(icon, 'leaflet-clickable');
3250 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3252 for (var i = 0; i < events.length; i++) {
3253 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3256 if (L.Handler.MarkerDrag) {
3257 this.dragging = new L.Handler.MarkerDrag(this);
3259 if (this.options.draggable) {
3260 this.dragging.enable();
3265 _onMouseClick: function (e) {
3266 var wasDragged = this.dragging && this.dragging.moved();
3268 if (this.hasEventListeners(e.type) || wasDragged) {
3269 L.DomEvent.stopPropagation(e);
3272 if (wasDragged) { return; }
3274 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3281 _fireMouseEvent: function (e) {
3287 // TODO proper custom event propagation
3288 // this line will always be called if marker is in a FeatureGroup
3289 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3290 L.DomEvent.preventDefault(e);
3292 if (e.type !== 'mousedown') {
3293 L.DomEvent.stopPropagation(e);
3297 setOpacity: function (opacity) {
3298 this.options.opacity = opacity;
3300 this._updateOpacity();
3304 _updateOpacity: function () {
3305 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3307 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3311 _bringToFront: function () {
3312 this._updateZIndex(this.options.riseOffset);
3315 _resetZIndex: function () {
3316 this._updateZIndex(0);
3320 L.marker = function (latlng, options) {
3321 return new L.Marker(latlng, options);
3326 * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3327 * to use with L.Marker.
3330 L.DivIcon = L.Icon.extend({
3332 iconSize: new L.Point(12, 12), // also can be set through CSS
3335 popupAnchor: (Point)
3339 className: 'leaflet-div-icon'
3342 createIcon: function () {
3343 var div = document.createElement('div'),
3344 options = this.options;
3347 div.innerHTML = options.html;
3350 if (options.bgPos) {
3351 div.style.backgroundPosition =
3352 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3355 this._setIconStyles(div, 'icon');
3359 createShadow: function () {
3364 L.divIcon = function (options) {
3365 return new L.DivIcon(options);
3370 * L.Popup is used for displaying popups on the map.
3373 L.Map.mergeOptions({
3374 closePopupOnClick: true
3377 L.Popup = L.Class.extend({
3378 includes: L.Mixin.Events,
3386 offset: new L.Point(0, 6),
3387 autoPanPadding: new L.Point(5, 5),
3392 initialize: function (options, source) {
3393 L.setOptions(this, options);
3395 this._source = source;
3396 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3399 onAdd: function (map) {
3402 if (!this._container) {
3405 this._updateContent();
3407 var animFade = map.options.fadeAnimation;
3410 L.DomUtil.setOpacity(this._container, 0);
3412 map._panes.popupPane.appendChild(this._container);
3414 map.on('viewreset', this._updatePosition, this);
3416 if (this._animated) {
3417 map.on('zoomanim', this._zoomAnimation, this);
3420 if (map.options.closePopupOnClick) {
3421 map.on('preclick', this._close, this);
3427 L.DomUtil.setOpacity(this._container, 1);
3431 addTo: function (map) {
3436 openOn: function (map) {
3437 map.openPopup(this);
3441 onRemove: function (map) {
3442 map._panes.popupPane.removeChild(this._container);
3444 L.Util.falseFn(this._container.offsetWidth); // force reflow
3447 viewreset: this._updatePosition,
3448 preclick: this._close,
3449 zoomanim: this._zoomAnimation
3452 if (map.options.fadeAnimation) {
3453 L.DomUtil.setOpacity(this._container, 0);
3459 setLatLng: function (latlng) {
3460 this._latlng = L.latLng(latlng);
3465 setContent: function (content) {
3466 this._content = content;
3471 _close: function () {
3472 var map = this._map;
3479 .fire('popupclose', {popup: this});
3483 _initLayout: function () {
3484 var prefix = 'leaflet-popup',
3485 containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
3486 (this._animated ? 'animated' : 'hide'),
3487 container = this._container = L.DomUtil.create('div', containerClass),
3490 if (this.options.closeButton) {
3491 closeButton = this._closeButton =
3492 L.DomUtil.create('a', prefix + '-close-button', container);
3493 closeButton.href = '#close';
3494 closeButton.innerHTML = '×';
3496 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3499 var wrapper = this._wrapper =
3500 L.DomUtil.create('div', prefix + '-content-wrapper', container);
3501 L.DomEvent.disableClickPropagation(wrapper);
3503 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3504 L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
3506 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3507 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3510 _update: function () {
3511 if (!this._map) { return; }
3513 this._container.style.visibility = 'hidden';
3515 this._updateContent();
3516 this._updateLayout();
3517 this._updatePosition();
3519 this._container.style.visibility = '';
3524 _updateContent: function () {
3525 if (!this._content) { return; }
3527 if (typeof this._content === 'string') {
3528 this._contentNode.innerHTML = this._content;
3530 while (this._contentNode.hasChildNodes()) {
3531 this._contentNode.removeChild(this._contentNode.firstChild);
3533 this._contentNode.appendChild(this._content);
3535 this.fire('contentupdate');
3538 _updateLayout: function () {
3539 var container = this._contentNode,
3540 style = container.style;
3543 style.whiteSpace = 'nowrap';
3545 var width = container.offsetWidth;
3546 width = Math.min(width, this.options.maxWidth);
3547 width = Math.max(width, this.options.minWidth);
3549 style.width = (width + 1) + 'px';
3550 style.whiteSpace = '';
3554 var height = container.offsetHeight,
3555 maxHeight = this.options.maxHeight,
3556 scrolledClass = 'leaflet-popup-scrolled';
3558 if (maxHeight && height > maxHeight) {
3559 style.height = maxHeight + 'px';
3560 L.DomUtil.addClass(container, scrolledClass);
3562 L.DomUtil.removeClass(container, scrolledClass);
3565 this._containerWidth = this._container.offsetWidth;
3568 _updatePosition: function () {
3569 if (!this._map) { return; }
3571 var pos = this._map.latLngToLayerPoint(this._latlng),
3572 animated = this._animated,
3573 offset = this.options.offset;
3576 L.DomUtil.setPosition(this._container, pos);
3579 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
3580 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
3582 //Bottom position the popup in case the height of the popup changes (images loading etc)
3583 this._container.style.bottom = this._containerBottom + 'px';
3584 this._container.style.left = this._containerLeft + 'px';
3587 _zoomAnimation: function (opt) {
3588 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
3590 L.DomUtil.setPosition(this._container, pos);
3593 _adjustPan: function () {
3594 if (!this.options.autoPan) { return; }
3596 var map = this._map,
3597 containerHeight = this._container.offsetHeight,
3598 containerWidth = this._containerWidth,
3600 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
3602 if (this._animated) {
3603 layerPos._add(L.DomUtil.getPosition(this._container));
3606 var containerPos = map.layerPointToContainerPoint(layerPos),
3607 padding = this.options.autoPanPadding,
3608 size = map.getSize(),
3612 if (containerPos.x < 0) {
3613 dx = containerPos.x - padding.x;
3615 if (containerPos.x + containerWidth > size.x) {
3616 dx = containerPos.x + containerWidth - size.x + padding.x;
3618 if (containerPos.y < 0) {
3619 dy = containerPos.y - padding.y;
3621 if (containerPos.y + containerHeight > size.y) {
3622 dy = containerPos.y + containerHeight - size.y + padding.y;
3626 map.panBy(new L.Point(dx, dy));
3630 _onCloseButtonClick: function (e) {
3636 L.popup = function (options, source) {
3637 return new L.Popup(options, source);
3642 * Popup extension to L.Marker, adding popup-related methods.
3646 openPopup: function () {
3647 if (this._popup && this._map) {
3648 this._popup.setLatLng(this._latlng);
3649 this._map.openPopup(this._popup);
3655 closePopup: function () {
3657 this._popup._close();
3662 bindPopup: function (content, options) {
3663 var anchor = L.point(this.options.icon.options.popupAnchor) || new L.Point(0, 0);
3665 anchor = anchor.add(L.Popup.prototype.options.offset);
3667 if (options && options.offset) {
3668 anchor = anchor.add(options.offset);
3671 options = L.extend({offset: anchor}, options);
3675 .on('click', this.openPopup, this)
3676 .on('remove', this.closePopup, this)
3677 .on('move', this._movePopup, this);
3680 this._popup = new L.Popup(options, this)
3681 .setContent(content);
3686 unbindPopup: function () {
3690 .off('click', this.openPopup)
3691 .off('remove', this.closePopup)
3692 .off('move', this._movePopup);
3697 _movePopup: function (e) {
3698 this._popup.setLatLng(e.latlng);
3704 * Adds popup-related methods to L.Map.
3708 openPopup: function (popup) {
3711 this._popup = popup;
3715 .fire('popupopen', {popup: this._popup});
3718 closePopup: function () {
3720 this._popup._close();
3728 * L.LayerGroup is a class to combine several layers into one so that
3729 * you can manipulate the group (e.g. add/remove it) as one layer.
3732 L.LayerGroup = L.Class.extend({
3733 initialize: function (layers) {
3739 for (i = 0, len = layers.length; i < len; i++) {
3740 this.addLayer(layers[i]);
3745 addLayer: function (layer) {
3746 var id = L.stamp(layer);
3748 this._layers[id] = layer;
3751 this._map.addLayer(layer);
3757 removeLayer: function (layer) {
3758 var id = L.stamp(layer);
3760 delete this._layers[id];
3763 this._map.removeLayer(layer);
3769 clearLayers: function () {
3770 this.eachLayer(this.removeLayer, this);
3774 invoke: function (methodName) {
3775 var args = Array.prototype.slice.call(arguments, 1),
3778 for (i in this._layers) {
3779 if (this._layers.hasOwnProperty(i)) {
3780 layer = this._layers[i];
3782 if (layer[methodName]) {
3783 layer[methodName].apply(layer, args);
3791 onAdd: function (map) {
3793 this.eachLayer(map.addLayer, map);
3796 onRemove: function (map) {
3797 this.eachLayer(map.removeLayer, map);
3801 addTo: function (map) {
3806 eachLayer: function (method, context) {
3807 for (var i in this._layers) {
3808 if (this._layers.hasOwnProperty(i)) {
3809 method.call(context, this._layers[i]);
3814 setZIndex: function (zIndex) {
3815 return this.invoke('setZIndex', zIndex);
3819 L.layerGroup = function (layers) {
3820 return new L.LayerGroup(layers);
3825 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
3826 * shared between a group of interactive layers (like vectors or markers).
3829 L.FeatureGroup = L.LayerGroup.extend({
3830 includes: L.Mixin.Events,
3833 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu'
3836 addLayer: function (layer) {
3837 if (this._layers[L.stamp(layer)]) {
3841 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
3843 L.LayerGroup.prototype.addLayer.call(this, layer);
3845 if (this._popupContent && layer.bindPopup) {
3846 layer.bindPopup(this._popupContent, this._popupOptions);
3849 return this.fire('layeradd', {layer: layer});
3852 removeLayer: function (layer) {
3853 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
3855 L.LayerGroup.prototype.removeLayer.call(this, layer);
3858 if (this._popupContent) {
3859 this.invoke('unbindPopup');
3862 return this.fire('layerremove', {layer: layer});
3865 bindPopup: function (content, options) {
3866 this._popupContent = content;
3867 this._popupOptions = options;
3868 return this.invoke('bindPopup', content, options);
3871 setStyle: function (style) {
3872 return this.invoke('setStyle', style);
3875 bringToFront: function () {
3876 return this.invoke('bringToFront');
3879 bringToBack: function () {
3880 return this.invoke('bringToBack');
3883 getBounds: function () {
3884 var bounds = new L.LatLngBounds();
3886 this.eachLayer(function (layer) {
3887 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
3893 _propagateEvent: function (e) {
3897 this.fire(e.type, e);
3901 L.featureGroup = function (layers) {
3902 return new L.FeatureGroup(layers);
3907 * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
3910 L.Path = L.Class.extend({
3911 includes: [L.Mixin.Events],
3914 // how much to extend the clip area around the map view
3915 // (relative to its size, e.g. 0.5 is half the screen in each direction)
3916 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
3917 CLIP_PADDING: L.Browser.mobile ?
3918 Math.max(0, Math.min(0.5,
3919 (1280 / Math.max(window.innerWidth, window.innerHeight) - 1) / 2)) : 0.5
3930 fillColor: null, //same as color by default
3936 initialize: function (options) {
3937 L.setOptions(this, options);
3940 onAdd: function (map) {
3943 if (!this._container) {
3944 this._initElements();
3948 this.projectLatlngs();
3951 if (this._container) {
3952 this._map._pathRoot.appendChild(this._container);
3958 'viewreset': this.projectLatlngs,
3959 'moveend': this._updatePath
3963 addTo: function (map) {
3968 onRemove: function (map) {
3969 map._pathRoot.removeChild(this._container);
3971 // Need to fire remove event before we set _map to null as the event hooks might need the object
3972 this.fire('remove');
3975 if (L.Browser.vml) {
3976 this._container = null;
3977 this._stroke = null;
3982 'viewreset': this.projectLatlngs,
3983 'moveend': this._updatePath
3987 projectLatlngs: function () {
3988 // do all projection stuff here
3991 setStyle: function (style) {
3992 L.setOptions(this, style);
3994 if (this._container) {
3995 this._updateStyle();
4001 redraw: function () {
4003 this.projectLatlngs();
4011 _updatePathViewport: function () {
4012 var p = L.Path.CLIP_PADDING,
4013 size = this.getSize(),
4014 panePos = L.DomUtil.getPosition(this._mapPane),
4015 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4016 max = min.add(size.multiplyBy(1 + p * 2)._round());
4018 this._pathViewport = new L.Bounds(min, max);
4024 * Extends L.Path with SVG-specific rendering code.
4027 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4029 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4031 L.Path = L.Path.extend({
4036 bringToFront: function () {
4037 var root = this._map._pathRoot,
4038 path = this._container;
4040 if (path && root.lastChild !== path) {
4041 root.appendChild(path);
4046 bringToBack: function () {
4047 var root = this._map._pathRoot,
4048 path = this._container,
4049 first = root.firstChild;
4051 if (path && first !== path) {
4052 root.insertBefore(path, first);
4057 getPathString: function () {
4058 // form path string here
4061 _createElement: function (name) {
4062 return document.createElementNS(L.Path.SVG_NS, name);
4065 _initElements: function () {
4066 this._map._initPathRoot();
4071 _initPath: function () {
4072 this._container = this._createElement('g');
4074 this._path = this._createElement('path');
4075 this._container.appendChild(this._path);
4078 _initStyle: function () {
4079 if (this.options.stroke) {
4080 this._path.setAttribute('stroke-linejoin', 'round');
4081 this._path.setAttribute('stroke-linecap', 'round');
4083 if (this.options.fill) {
4084 this._path.setAttribute('fill-rule', 'evenodd');
4086 this._updateStyle();
4089 _updateStyle: function () {
4090 if (this.options.stroke) {
4091 this._path.setAttribute('stroke', this.options.color);
4092 this._path.setAttribute('stroke-opacity', this.options.opacity);
4093 this._path.setAttribute('stroke-width', this.options.weight);
4094 if (this.options.dashArray) {
4095 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4097 this._path.removeAttribute('stroke-dasharray');
4100 this._path.setAttribute('stroke', 'none');
4102 if (this.options.fill) {
4103 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4104 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4106 this._path.setAttribute('fill', 'none');
4110 _updatePath: function () {
4111 var str = this.getPathString();
4113 // fix webkit empty string parsing bug
4116 this._path.setAttribute('d', str);
4119 // TODO remove duplication with L.Map
4120 _initEvents: function () {
4121 if (this.options.clickable) {
4122 if (L.Browser.svg || !L.Browser.vml) {
4123 this._path.setAttribute('class', 'leaflet-clickable');
4126 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4128 var events = ['dblclick', 'mousedown', 'mouseover',
4129 'mouseout', 'mousemove', 'contextmenu'];
4130 for (var i = 0; i < events.length; i++) {
4131 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4136 _onMouseClick: function (e) {
4137 if (this._map.dragging && this._map.dragging.moved()) { return; }
4139 this._fireMouseEvent(e);
4142 _fireMouseEvent: function (e) {
4143 if (!this.hasEventListeners(e.type)) { return; }
4145 var map = this._map,
4146 containerPoint = map.mouseEventToContainerPoint(e),
4147 layerPoint = map.containerPointToLayerPoint(containerPoint),
4148 latlng = map.layerPointToLatLng(layerPoint);
4152 layerPoint: layerPoint,
4153 containerPoint: containerPoint,
4157 if (e.type === 'contextmenu') {
4158 L.DomEvent.preventDefault(e);
4160 if (e.type !== 'mousemove') {
4161 L.DomEvent.stopPropagation(e);
4167 _initPathRoot: function () {
4168 if (!this._pathRoot) {
4169 this._pathRoot = L.Path.prototype._createElement('svg');
4170 this._panes.overlayPane.appendChild(this._pathRoot);
4172 if (this.options.zoomAnimation && L.Browser.any3d) {
4173 this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
4176 'zoomanim': this._animatePathZoom,
4177 'zoomend': this._endPathZoom
4180 this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
4183 this.on('moveend', this._updateSvgViewport);
4184 this._updateSvgViewport();
4188 _animatePathZoom: function (e) {
4189 var scale = this.getZoomScale(e.zoom),
4190 offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4192 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4193 L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4195 this._pathZooming = true;
4198 _endPathZoom: function () {
4199 this._pathZooming = false;
4202 _updateSvgViewport: function () {
4204 if (this._pathZooming) {
4205 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4206 // When the zoom animation ends we will be updated again anyway
4207 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4211 this._updatePathViewport();
4213 var vp = this._pathViewport,
4216 width = max.x - min.x,
4217 height = max.y - min.y,
4218 root = this._pathRoot,
4219 pane = this._panes.overlayPane;
4221 // Hack to make flicker on drag end on mobile webkit less irritating
4222 if (L.Browser.mobileWebkit) {
4223 pane.removeChild(root);
4226 L.DomUtil.setPosition(root, min);
4227 root.setAttribute('width', width);
4228 root.setAttribute('height', height);
4229 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4231 if (L.Browser.mobileWebkit) {
4232 pane.appendChild(root);
4239 * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4244 bindPopup: function (content, options) {
4246 if (!this._popup || options) {
4247 this._popup = new L.Popup(options, this);
4250 this._popup.setContent(content);
4252 if (!this._popupHandlersAdded) {
4254 .on('click', this._openPopup, this)
4255 .on('remove', this.closePopup, this);
4257 this._popupHandlersAdded = true;
4263 unbindPopup: function () {
4267 .off('click', this._openPopup)
4268 .off('remove', this.closePopup);
4270 this._popupHandlersAdded = false;
4275 openPopup: function (latlng) {
4278 // open the popup from one of the path's points if not specified
4279 latlng = latlng || this._latlng ||
4280 this._latlngs[Math.floor(this._latlngs.length / 2)];
4282 this._openPopup({latlng: latlng});
4288 closePopup: function () {
4290 this._popup._close();
4295 _openPopup: function (e) {
4296 this._popup.setLatLng(e.latlng);
4297 this._map.openPopup(this._popup);
4303 * Vector rendering for IE6-8 through VML.
4304 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4307 L.Browser.vml = !L.Browser.svg && (function () {
4309 var div = document.createElement('div');
4310 div.innerHTML = '<v:shape adj="1"/>';
4312 var shape = div.firstChild;
4313 shape.style.behavior = 'url(#default#VML)';
4315 return shape && (typeof shape.adj === 'object');
4322 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4328 _createElement: (function () {
4330 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4331 return function (name) {
4332 return document.createElement('<lvml:' + name + ' class="lvml">');
4335 return function (name) {
4336 return document.createElement(
4337 '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4342 _initPath: function () {
4343 var container = this._container = this._createElement('shape');
4344 L.DomUtil.addClass(container, 'leaflet-vml-shape');
4345 if (this.options.clickable) {
4346 L.DomUtil.addClass(container, 'leaflet-clickable');
4348 container.coordsize = '1 1';
4350 this._path = this._createElement('path');
4351 container.appendChild(this._path);
4353 this._map._pathRoot.appendChild(container);
4356 _initStyle: function () {
4357 this._updateStyle();
4360 _updateStyle: function () {
4361 var stroke = this._stroke,
4363 options = this.options,
4364 container = this._container;
4366 container.stroked = options.stroke;
4367 container.filled = options.fill;
4369 if (options.stroke) {
4371 stroke = this._stroke = this._createElement('stroke');
4372 stroke.endcap = 'round';
4373 container.appendChild(stroke);
4375 stroke.weight = options.weight + 'px';
4376 stroke.color = options.color;
4377 stroke.opacity = options.opacity;
4379 if (options.dashArray) {
4380 stroke.dashStyle = options.dashArray instanceof Array ?
4381 options.dashArray.join(' ') :
4382 options.dashArray.replace(/ *, */g, ' ');
4384 stroke.dashStyle = '';
4387 } else if (stroke) {
4388 container.removeChild(stroke);
4389 this._stroke = null;
4394 fill = this._fill = this._createElement('fill');
4395 container.appendChild(fill);
4397 fill.color = options.fillColor || options.color;
4398 fill.opacity = options.fillOpacity;
4401 container.removeChild(fill);
4406 _updatePath: function () {
4407 var style = this._container.style;
4409 style.display = 'none';
4410 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
4415 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
4416 _initPathRoot: function () {
4417 if (this._pathRoot) { return; }
4419 var root = this._pathRoot = document.createElement('div');
4420 root.className = 'leaflet-vml-container';
4421 this._panes.overlayPane.appendChild(root);
4423 this.on('moveend', this._updatePathViewport);
4424 this._updatePathViewport();
4430 * Vector rendering for all browsers that support canvas.
4433 L.Browser.canvas = (function () {
4434 return !!document.createElement('canvas').getContext;
4437 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
4439 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
4444 redraw: function () {
4446 this.projectLatlngs();
4447 this._requestUpdate();
4452 setStyle: function (style) {
4453 L.setOptions(this, style);
4456 this._updateStyle();
4457 this._requestUpdate();
4462 onRemove: function (map) {
4464 .off('viewreset', this.projectLatlngs, this)
4465 .off('moveend', this._updatePath, this);
4467 if (this.options.clickable) {
4468 this._map.off('click', this._onClick, this);
4471 this._requestUpdate();
4476 _requestUpdate: function () {
4477 if (this._map && !L.Path._updateRequest) {
4478 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
4482 _fireMapMoveEnd: function () {
4483 L.Path._updateRequest = null;
4484 this.fire('moveend');
4487 _initElements: function () {
4488 this._map._initPathRoot();
4489 this._ctx = this._map._canvasCtx;
4492 _updateStyle: function () {
4493 var options = this.options;
4495 if (options.stroke) {
4496 this._ctx.lineWidth = options.weight;
4497 this._ctx.strokeStyle = options.color;
4500 this._ctx.fillStyle = options.fillColor || options.color;
4504 _drawPath: function () {
4505 var i, j, len, len2, point, drawMethod;
4507 this._ctx.beginPath();
4509 for (i = 0, len = this._parts.length; i < len; i++) {
4510 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
4511 point = this._parts[i][j];
4512 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
4514 this._ctx[drawMethod](point.x, point.y);
4516 // TODO refactor ugly hack
4517 if (this instanceof L.Polygon) {
4518 this._ctx.closePath();
4523 _checkIfEmpty: function () {
4524 return !this._parts.length;
4527 _updatePath: function () {
4528 if (this._checkIfEmpty()) { return; }
4530 var ctx = this._ctx,
4531 options = this.options;
4535 this._updateStyle();
4538 ctx.globalAlpha = options.fillOpacity;
4542 if (options.stroke) {
4543 ctx.globalAlpha = options.opacity;
4549 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
4552 _initEvents: function () {
4553 if (this.options.clickable) {
4555 // TODO mouseover, mouseout, dblclick
4556 this._map.on('click', this._onClick, this);
4560 _onClick: function (e) {
4561 if (this._containsPoint(e.layerPoint)) {
4562 this.fire('click', {
4564 layerPoint: e.layerPoint,
4565 containerPoint: e.containerPoint,
4572 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
4573 _initPathRoot: function () {
4574 var root = this._pathRoot,
4578 root = this._pathRoot = document.createElement("canvas");
4579 root.style.position = 'absolute';
4580 ctx = this._canvasCtx = root.getContext('2d');
4582 ctx.lineCap = "round";
4583 ctx.lineJoin = "round";
4585 this._panes.overlayPane.appendChild(root);
4587 if (this.options.zoomAnimation) {
4588 this._pathRoot.className = 'leaflet-zoom-animated';
4589 this.on('zoomanim', this._animatePathZoom);
4590 this.on('zoomend', this._endPathZoom);
4592 this.on('moveend', this._updateCanvasViewport);
4593 this._updateCanvasViewport();
4597 _updateCanvasViewport: function () {
4598 // don't redraw while zooming. See _updateSvgViewport for more details
4599 if (this._pathZooming) { return; }
4600 this._updatePathViewport();
4602 var vp = this._pathViewport,
4604 size = vp.max.subtract(min),
4605 root = this._pathRoot;
4607 //TODO check if this works properly on mobile webkit
4608 L.DomUtil.setPosition(root, min);
4609 root.width = size.x;
4610 root.height = size.y;
4611 root.getContext('2d').translate(-min.x, -min.y);
4617 * L.LineUtil contains different utility functions for line segments
4618 * and polylines (clipping, simplification, distances, etc.)
4621 /*jshint bitwise:false */ // allow bitwise oprations for this file
4625 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
4626 // Improves rendering performance dramatically by lessening the number of points to draw.
4628 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
4629 if (!tolerance || !points.length) {
4630 return points.slice();
4633 var sqTolerance = tolerance * tolerance;
4635 // stage 1: vertex reduction
4636 points = this._reducePoints(points, sqTolerance);
4638 // stage 2: Douglas-Peucker simplification
4639 points = this._simplifyDP(points, sqTolerance);
4644 // distance from a point to a segment between two points
4645 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
4646 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
4649 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
4650 return this._sqClosestPointOnSegment(p, p1, p2);
4653 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
4654 _simplifyDP: function (points, sqTolerance) {
4656 var len = points.length,
4657 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
4658 markers = new ArrayConstructor(len);
4660 markers[0] = markers[len - 1] = 1;
4662 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
4667 for (i = 0; i < len; i++) {
4669 newPoints.push(points[i]);
4676 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
4681 for (i = first + 1; i <= last - 1; i++) {
4682 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
4684 if (sqDist > maxSqDist) {
4690 if (maxSqDist > sqTolerance) {
4693 this._simplifyDPStep(points, markers, sqTolerance, first, index);
4694 this._simplifyDPStep(points, markers, sqTolerance, index, last);
4698 // reduce points that are too close to each other to a single point
4699 _reducePoints: function (points, sqTolerance) {
4700 var reducedPoints = [points[0]];
4702 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
4703 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
4704 reducedPoints.push(points[i]);
4708 if (prev < len - 1) {
4709 reducedPoints.push(points[len - 1]);
4711 return reducedPoints;
4714 // Cohen-Sutherland line clipping algorithm.
4715 // Used to avoid rendering parts of a polyline that are not currently visible.
4717 clipSegment: function (a, b, bounds, useLastCode) {
4718 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
4719 codeB = this._getBitCode(b, bounds),
4721 codeOut, p, newCode;
4723 // save 2nd code to avoid calculating it on the next segment
4724 this._lastCode = codeB;
4727 // if a,b is inside the clip window (trivial accept)
4728 if (!(codeA | codeB)) {
4730 // if a,b is outside the clip window (trivial reject)
4731 } else if (codeA & codeB) {
4735 codeOut = codeA || codeB,
4736 p = this._getEdgeIntersection(a, b, codeOut, bounds),
4737 newCode = this._getBitCode(p, bounds);
4739 if (codeOut === codeA) {
4750 _getEdgeIntersection: function (a, b, code, bounds) {
4756 if (code & 8) { // top
4757 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
4758 } else if (code & 4) { // bottom
4759 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
4760 } else if (code & 2) { // right
4761 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
4762 } else if (code & 1) { // left
4763 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
4767 _getBitCode: function (/*Point*/ p, bounds) {
4770 if (p.x < bounds.min.x) { // left
4772 } else if (p.x > bounds.max.x) { // right
4775 if (p.y < bounds.min.y) { // bottom
4777 } else if (p.y > bounds.max.y) { // top
4784 // square distance (to avoid unnecessary Math.sqrt calls)
4785 _sqDist: function (p1, p2) {
4786 var dx = p2.x - p1.x,
4788 return dx * dx + dy * dy;
4791 // return closest point on segment or distance to that point
4792 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
4797 dot = dx * dx + dy * dy,
4801 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
4815 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
4821 * L.Polygon is used to display polylines on a map.
4824 L.Polyline = L.Path.extend({
4825 initialize: function (latlngs, options) {
4826 L.Path.prototype.initialize.call(this, options);
4828 this._latlngs = this._convertLatLngs(latlngs);
4832 // how much to simplify the polyline on each zoom level
4833 // more = better performance and smoother look, less = more accurate
4838 projectLatlngs: function () {
4839 this._originalPoints = [];
4841 for (var i = 0, len = this._latlngs.length; i < len; i++) {
4842 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
4846 getPathString: function () {
4847 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
4848 str += this._getPathPartStr(this._parts[i]);
4853 getLatLngs: function () {
4854 return this._latlngs;
4857 setLatLngs: function (latlngs) {
4858 this._latlngs = this._convertLatLngs(latlngs);
4859 return this.redraw();
4862 addLatLng: function (latlng) {
4863 this._latlngs.push(L.latLng(latlng));
4864 return this.redraw();
4867 spliceLatLngs: function () { // (Number index, Number howMany)
4868 var removed = [].splice.apply(this._latlngs, arguments);
4869 this._convertLatLngs(this._latlngs);
4874 closestLayerPoint: function (p) {
4875 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
4877 for (var j = 0, jLen = parts.length; j < jLen; j++) {
4878 var points = parts[j];
4879 for (var i = 1, len = points.length; i < len; i++) {
4882 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
4883 if (sqDist < minDistance) {
4884 minDistance = sqDist;
4885 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
4890 minPoint.distance = Math.sqrt(minDistance);
4895 getBounds: function () {
4896 var bounds = new L.LatLngBounds(),
4897 latLngs = this.getLatLngs(),
4900 for (i = 0, len = latLngs.length; i < len; i++) {
4901 bounds.extend(latLngs[i]);
4907 _convertLatLngs: function (latlngs) {
4909 for (i = 0, len = latlngs.length; i < len; i++) {
4910 if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
4913 latlngs[i] = L.latLng(latlngs[i]);
4918 _initEvents: function () {
4919 L.Path.prototype._initEvents.call(this);
4922 _getPathPartStr: function (points) {
4923 var round = L.Path.VML;
4925 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
4930 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
4935 _clipPoints: function () {
4936 var points = this._originalPoints,
4937 len = points.length,
4940 if (this.options.noClip) {
4941 this._parts = [points];
4947 var parts = this._parts,
4948 vp = this._map._pathViewport,
4951 for (i = 0, k = 0; i < len - 1; i++) {
4952 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
4957 parts[k] = parts[k] || [];
4958 parts[k].push(segment[0]);
4960 // if segment goes out of screen, or it's the last one, it's the end of the line part
4961 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
4962 parts[k].push(segment[1]);
4968 // simplify each clipped part of the polyline
4969 _simplifyPoints: function () {
4970 var parts = this._parts,
4973 for (var i = 0, len = parts.length; i < len; i++) {
4974 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
4978 _updatePath: function () {
4979 if (!this._map) { return; }
4982 this._simplifyPoints();
4984 L.Path.prototype._updatePath.call(this);
4988 L.polyline = function (latlngs, options) {
4989 return new L.Polyline(latlngs, options);
4994 * L.PolyUtil contains utility functions for polygons (clipping, etc.).
4997 /*jshint bitwise:false */ // allow bitwise operations here
5002 * Sutherland-Hodgeman polygon clipping algorithm.
5003 * Used to avoid rendering parts of a polygon that are not currently visible.
5005 L.PolyUtil.clipPolygon = function (points, bounds) {
5007 edges = [1, 4, 2, 8],
5013 for (i = 0, len = points.length; i < len; i++) {
5014 points[i]._code = lu._getBitCode(points[i], bounds);
5017 // for each edge (left, bottom, right, top)
5018 for (k = 0; k < 4; k++) {
5022 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5026 // if a is inside the clip window
5027 if (!(a._code & edge)) {
5028 // if b is outside the clip window (a->b goes out of screen)
5029 if (b._code & edge) {
5030 p = lu._getEdgeIntersection(b, a, edge, bounds);
5031 p._code = lu._getBitCode(p, bounds);
5032 clippedPoints.push(p);
5034 clippedPoints.push(a);
5036 // else if b is inside the clip window (a->b enters the screen)
5037 } else if (!(b._code & edge)) {
5038 p = lu._getEdgeIntersection(b, a, edge, bounds);
5039 p._code = lu._getBitCode(p, bounds);
5040 clippedPoints.push(p);
5043 points = clippedPoints;
5051 * L.Polygon is used to display polygons on a map.
5054 L.Polygon = L.Polyline.extend({
5059 initialize: function (latlngs, options) {
5060 L.Polyline.prototype.initialize.call(this, latlngs, options);
5062 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5063 this._latlngs = this._convertLatLngs(latlngs[0]);
5064 this._holes = latlngs.slice(1);
5068 projectLatlngs: function () {
5069 L.Polyline.prototype.projectLatlngs.call(this);
5071 // project polygon holes points
5072 // TODO move this logic to Polyline to get rid of duplication
5073 this._holePoints = [];
5075 if (!this._holes) { return; }
5077 var i, j, len, len2;
5079 for (i = 0, len = this._holes.length; i < len; i++) {
5080 this._holePoints[i] = [];
5082 for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5083 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5088 _clipPoints: function () {
5089 var points = this._originalPoints,
5092 this._parts = [points].concat(this._holePoints);
5094 if (this.options.noClip) { return; }
5096 for (var i = 0, len = this._parts.length; i < len; i++) {
5097 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5098 if (clipped.length) {
5099 newParts.push(clipped);
5103 this._parts = newParts;
5106 _getPathPartStr: function (points) {
5107 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5108 return str + (L.Browser.svg ? 'z' : 'x');
5112 L.polygon = function (latlngs, options) {
5113 return new L.Polygon(latlngs, options);
5118 * Contains L.MultiPolyline and L.MultiPolygon layers.
5122 function createMulti(Klass) {
5124 return L.FeatureGroup.extend({
5126 initialize: function (latlngs, options) {
5128 this._options = options;
5129 this.setLatLngs(latlngs);
5132 setLatLngs: function (latlngs) {
5134 len = latlngs.length;
5136 this.eachLayer(function (layer) {
5138 layer.setLatLngs(latlngs[i++]);
5140 this.removeLayer(layer);
5145 this.addLayer(new Klass(latlngs[i++], this._options));
5153 L.MultiPolyline = createMulti(L.Polyline);
5154 L.MultiPolygon = createMulti(L.Polygon);
5156 L.multiPolyline = function (latlngs, options) {
5157 return new L.MultiPolyline(latlngs, options);
5160 L.multiPolygon = function (latlngs, options) {
5161 return new L.MultiPolygon(latlngs, options);
5167 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5170 L.Rectangle = L.Polygon.extend({
5171 initialize: function (latLngBounds, options) {
5172 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5175 setBounds: function (latLngBounds) {
5176 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5179 _boundsToLatLngs: function (latLngBounds) {
5180 latLngBounds = L.latLngBounds(latLngBounds);
5182 latLngBounds.getSouthWest(),
5183 latLngBounds.getNorthWest(),
5184 latLngBounds.getNorthEast(),
5185 latLngBounds.getSouthEast()
5190 L.rectangle = function (latLngBounds, options) {
5191 return new L.Rectangle(latLngBounds, options);
5196 * L.Circle is a circle overlay (with a certain radius in meters).
5199 L.Circle = L.Path.extend({
5200 initialize: function (latlng, radius, options) {
5201 L.Path.prototype.initialize.call(this, options);
5203 this._latlng = L.latLng(latlng);
5204 this._mRadius = radius;
5211 setLatLng: function (latlng) {
5212 this._latlng = L.latLng(latlng);
5213 return this.redraw();
5216 setRadius: function (radius) {
5217 this._mRadius = radius;
5218 return this.redraw();
5221 projectLatlngs: function () {
5222 var lngRadius = this._getLngRadius(),
5223 latlng2 = new L.LatLng(this._latlng.lat, this._latlng.lng - lngRadius),
5224 point2 = this._map.latLngToLayerPoint(latlng2);
5226 this._point = this._map.latLngToLayerPoint(this._latlng);
5227 this._radius = Math.max(Math.round(this._point.x - point2.x), 1);
5230 getBounds: function () {
5231 var lngRadius = this._getLngRadius(),
5232 latRadius = (this._mRadius / 40075017) * 360,
5233 latlng = this._latlng,
5234 sw = new L.LatLng(latlng.lat - latRadius, latlng.lng - lngRadius),
5235 ne = new L.LatLng(latlng.lat + latRadius, latlng.lng + lngRadius);
5237 return new L.LatLngBounds(sw, ne);
5240 getLatLng: function () {
5241 return this._latlng;
5244 getPathString: function () {
5245 var p = this._point,
5248 if (this._checkIfEmpty()) {
5252 if (L.Browser.svg) {
5253 return "M" + p.x + "," + (p.y - r) +
5254 "A" + r + "," + r + ",0,1,1," +
5255 (p.x - 0.1) + "," + (p.y - r) + " z";
5259 return "AL " + p.x + "," + p.y + " " + r + "," + r + " 0," + (65535 * 360);
5263 getRadius: function () {
5264 return this._mRadius;
5267 // TODO Earth hardcoded, move into projection code!
5269 _getLatRadius: function () {
5270 return (this._mRadius / 40075017) * 360;
5273 _getLngRadius: function () {
5274 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5277 _checkIfEmpty: function () {
5281 var vp = this._map._pathViewport,
5285 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5286 p.x + r < vp.min.x || p.y + r < vp.min.y;
5290 L.circle = function (latlng, radius, options) {
5291 return new L.Circle(latlng, radius, options);
5296 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5299 L.CircleMarker = L.Circle.extend({
5305 initialize: function (latlng, options) {
5306 L.Circle.prototype.initialize.call(this, latlng, null, options);
5307 this._radius = this.options.radius;
5310 projectLatlngs: function () {
5311 this._point = this._map.latLngToLayerPoint(this._latlng);
5314 _updateStyle : function () {
5315 L.Circle.prototype._updateStyle.call(this);
5316 this.setRadius(this.options.radius);
5319 setRadius: function (radius) {
5320 this._radius = radius;
5321 return this.redraw();
5325 L.circleMarker = function (latlng, options) {
5326 return new L.CircleMarker(latlng, options);
5331 * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
5334 L.Polyline.include(!L.Path.CANVAS ? {} : {
5335 _containsPoint: function (p, closed) {
5336 var i, j, k, len, len2, dist, part,
5337 w = this.options.weight / 2;
5339 if (L.Browser.touch) {
5340 w += 10; // polyline click tolerance on touch devices
5343 for (i = 0, len = this._parts.length; i < len; i++) {
5344 part = this._parts[i];
5345 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5346 if (!closed && (j === 0)) {
5350 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
5363 * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
5366 L.Polygon.include(!L.Path.CANVAS ? {} : {
5367 _containsPoint: function (p) {
5373 // TODO optimization: check if within bounds first
5375 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
5376 // click on polygon border
5380 // ray casting algorithm for detecting if point is in polygon
5382 for (i = 0, len = this._parts.length; i < len; i++) {
5383 part = this._parts[i];
5385 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5389 if (((p1.y > p.y) !== (p2.y > p.y)) &&
5390 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
5402 * Extends L.Circle with Canvas-specific code.
5405 L.Circle.include(!L.Path.CANVAS ? {} : {
5406 _drawPath: function () {
5407 var p = this._point;
5408 this._ctx.beginPath();
5409 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
5412 _containsPoint: function (p) {
5413 var center = this._point,
5414 w2 = this.options.stroke ? this.options.weight / 2 : 0;
5416 return (p.distanceTo(center) <= this._radius + w2);
5422 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
5425 L.GeoJSON = L.FeatureGroup.extend({
5427 initialize: function (geojson, options) {
5428 L.setOptions(this, options);
5433 this.addData(geojson);
5437 addData: function (geojson) {
5438 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
5442 for (i = 0, len = features.length; i < len; i++) {
5443 // Only add this if geometry or geometries are set and not null
5444 if (features[i].geometries || features[i].geometry) {
5445 this.addData(features[i]);
5451 var options = this.options;
5453 if (options.filter && !options.filter(geojson)) { return; }
5455 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer);
5456 layer.feature = geojson;
5458 layer.defaultOptions = layer.options;
5459 this.resetStyle(layer);
5461 if (options.onEachFeature) {
5462 options.onEachFeature(geojson, layer);
5465 return this.addLayer(layer);
5468 resetStyle: function (layer) {
5469 var style = this.options.style;
5471 // reset any custom styles
5472 L.Util.extend(layer.options, layer.defaultOptions);
5474 this._setLayerStyle(layer, style);
5478 setStyle: function (style) {
5479 this.eachLayer(function (layer) {
5480 this._setLayerStyle(layer, style);
5484 _setLayerStyle: function (layer, style) {
5485 if (typeof style === 'function') {
5486 style = style(layer.feature);
5488 if (layer.setStyle) {
5489 layer.setStyle(style);
5494 L.extend(L.GeoJSON, {
5495 geometryToLayer: function (geojson, pointToLayer) {
5496 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
5497 coords = geometry.coordinates,
5499 latlng, latlngs, i, len, layer;
5501 switch (geometry.type) {
5503 latlng = this.coordsToLatLng(coords);
5504 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
5507 for (i = 0, len = coords.length; i < len; i++) {
5508 latlng = this.coordsToLatLng(coords[i]);
5509 layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
5512 return new L.FeatureGroup(layers);
5515 latlngs = this.coordsToLatLngs(coords);
5516 return new L.Polyline(latlngs);
5519 latlngs = this.coordsToLatLngs(coords, 1);
5520 return new L.Polygon(latlngs);
5522 case 'MultiLineString':
5523 latlngs = this.coordsToLatLngs(coords, 1);
5524 return new L.MultiPolyline(latlngs);
5526 case 'MultiPolygon':
5527 latlngs = this.coordsToLatLngs(coords, 2);
5528 return new L.MultiPolygon(latlngs);
5530 case 'GeometryCollection':
5531 for (i = 0, len = geometry.geometries.length; i < len; i++) {
5532 layer = this.geometryToLayer({
5533 geometry: geometry.geometries[i],
5535 properties: geojson.properties
5539 return new L.FeatureGroup(layers);
5542 throw new Error('Invalid GeoJSON object.');
5546 coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng
5547 var lat = parseFloat(coords[reverse ? 0 : 1]),
5548 lng = parseFloat(coords[reverse ? 1 : 0]);
5550 return new L.LatLng(lat, lng);
5553 coordsToLatLngs: function (coords, levelsDeep, reverse) { // (Array, Number, Boolean) -> Array
5558 for (i = 0, len = coords.length; i < len; i++) {
5559 latlng = levelsDeep ?
5560 this.coordsToLatLngs(coords[i], levelsDeep - 1, reverse) :
5561 this.coordsToLatLng(coords[i], reverse);
5563 latlngs.push(latlng);
5570 L.geoJson = function (geojson, options) {
5571 return new L.GeoJSON(geojson, options);
5576 * L.DomEvent contains functions for working with DOM events.
5580 /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
5581 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
5583 var id = L.stamp(fn),
5584 key = '_leaflet_' + type + id,
5585 handler, originalHandler, newType;
5587 if (obj[key]) { return this; }
5589 handler = function (e) {
5590 return fn.call(context || obj, e || L.DomEvent._getEvent());
5593 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
5594 return this.addMsTouchListener(obj, type, handler, id);
5596 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
5597 this.addDoubleTapListener(obj, handler, id);
5600 if ('addEventListener' in obj) {
5602 if (type === 'mousewheel') {
5603 obj.addEventListener('DOMMouseScroll', handler, false);
5604 obj.addEventListener(type, handler, false);
5606 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
5608 originalHandler = handler;
5609 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
5611 handler = function (e) {
5612 if (!L.DomEvent._checkMouse(obj, e)) { return; }
5613 return originalHandler(e);
5616 obj.addEventListener(newType, handler, false);
5619 obj.addEventListener(type, handler, false);
5622 } else if ('attachEvent' in obj) {
5623 obj.attachEvent("on" + type, handler);
5631 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
5633 var id = L.stamp(fn),
5634 key = '_leaflet_' + type + id,
5637 if (!handler) { return; }
5639 if (L.Browser.msTouch && type.indexOf('touch') === 0) {
5640 this.removeMsTouchListener(obj, type, id);
5641 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
5642 this.removeDoubleTapListener(obj, id);
5644 } else if ('removeEventListener' in obj) {
5646 if (type === 'mousewheel') {
5647 obj.removeEventListener('DOMMouseScroll', handler, false);
5648 obj.removeEventListener(type, handler, false);
5650 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
5651 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
5653 obj.removeEventListener(type, handler, false);
5655 } else if ('detachEvent' in obj) {
5656 obj.detachEvent("on" + type, handler);
5664 stopPropagation: function (e) {
5666 if (e.stopPropagation) {
5667 e.stopPropagation();
5669 e.cancelBubble = true;
5674 disableClickPropagation: function (el) {
5676 var stop = L.DomEvent.stopPropagation;
5678 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
5679 L.DomEvent.addListener(el, L.Draggable.START[i], stop);
5683 .addListener(el, 'click', stop)
5684 .addListener(el, 'dblclick', stop);
5687 preventDefault: function (e) {
5689 if (e.preventDefault) {
5692 e.returnValue = false;
5697 stop: function (e) {
5698 return L.DomEvent.preventDefault(e).stopPropagation(e);
5701 getMousePosition: function (e, container) {
5703 var body = document.body,
5704 docEl = document.documentElement,
5705 x = e.pageX ? e.pageX : e.clientX + body.scrollLeft + docEl.scrollLeft,
5706 y = e.pageY ? e.pageY : e.clientY + body.scrollTop + docEl.scrollTop,
5707 pos = new L.Point(x, y);
5709 return (container ? pos._subtract(L.DomUtil.getViewportOffset(container)) : pos);
5712 getWheelDelta: function (e) {
5717 delta = e.wheelDelta / 120;
5720 delta = -e.detail / 3;
5725 // check if element really left/entered the event target (for mouseenter/mouseleave)
5726 _checkMouse: function (el, e) {
5728 var related = e.relatedTarget;
5730 if (!related) { return true; }
5733 while (related && (related !== el)) {
5734 related = related.parentNode;
5739 return (related !== el);
5742 _getEvent: function () { // evil magic for IE
5743 /*jshint noarg:false */
5744 var e = window.event;
5746 var caller = arguments.callee.caller;
5748 e = caller['arguments'][0];
5749 if (e && window.Event === e.constructor) {
5752 caller = caller.caller;
5759 L.DomEvent.on = L.DomEvent.addListener;
5760 L.DomEvent.off = L.DomEvent.removeListener;
5764 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
5767 L.Draggable = L.Class.extend({
5768 includes: L.Mixin.Events,
5771 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
5773 mousedown: 'mouseup',
5774 touchstart: 'touchend',
5775 MSPointerDown: 'touchend'
5778 mousedown: 'mousemove',
5779 touchstart: 'touchmove',
5780 MSPointerDown: 'touchmove'
5785 initialize: function (element, dragStartTarget, longPress) {
5786 this._element = element;
5787 this._dragStartTarget = dragStartTarget || element;
5788 this._longPress = longPress && !L.Browser.msTouch;
5791 enable: function () {
5792 if (this._enabled) { return; }
5794 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
5795 L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
5797 this._enabled = true;
5800 disable: function () {
5801 if (!this._enabled) { return; }
5803 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
5804 L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
5806 this._enabled = false;
5807 this._moved = false;
5810 _onDown: function (e) {
5811 if ((!L.Browser.touch && e.shiftKey) ||
5812 ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
5814 L.DomEvent.preventDefault(e);
5815 L.DomEvent.stopPropagation(e);
5817 if (L.Draggable._disabled) { return; }
5819 this._simulateClick = true;
5821 if (e.touches && e.touches.length > 1) {
5822 this._simulateClick = false;
5823 clearTimeout(this._longPressTimeout);
5827 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
5830 if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
5831 L.DomUtil.addClass(el, 'leaflet-active');
5834 this._moved = false;
5835 if (this._moving) { return; }
5837 this._startPoint = new L.Point(first.clientX, first.clientY);
5838 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
5840 //Touch contextmenu event emulation
5841 if (e.touches && e.touches.length === 1 && L.Browser.touch && this._longPress) {
5842 this._longPressTimeout = setTimeout(L.bind(function () {
5843 var dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;
5845 if (dist < L.Draggable.TAP_TOLERANCE) {
5846 this._simulateClick = false;
5848 this._simulateEvent('contextmenu', first);
5853 L.DomEvent.on(document, L.Draggable.MOVE[e.type], this._onMove, this);
5854 L.DomEvent.on(document, L.Draggable.END[e.type], this._onUp, this);
5857 _onMove: function (e) {
5858 if (e.touches && e.touches.length > 1) { return; }
5860 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
5861 newPoint = new L.Point(first.clientX, first.clientY),
5862 diffVec = newPoint.subtract(this._startPoint);
5864 if (!diffVec.x && !diffVec.y) { return; }
5866 L.DomEvent.preventDefault(e);
5869 this.fire('dragstart');
5872 this._startPos = L.DomUtil.getPosition(this._element).subtract(diffVec);
5874 if (!L.Browser.touch) {
5875 L.DomUtil.disableTextSelection();
5876 this._setMovingCursor();
5880 this._newPos = this._startPos.add(diffVec);
5881 this._moving = true;
5883 L.Util.cancelAnimFrame(this._animRequest);
5884 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
5887 _updatePosition: function () {
5888 this.fire('predrag');
5889 L.DomUtil.setPosition(this._element, this._newPos);
5893 _onUp: function (e) {
5894 var simulateClickTouch;
5895 clearTimeout(this._longPressTimeout);
5896 if (this._simulateClick && e.changedTouches) {
5897 var first = e.changedTouches[0],
5899 dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;
5901 if (el.tagName.toLowerCase() === 'a') {
5902 L.DomUtil.removeClass(el, 'leaflet-active');
5905 if (dist < L.Draggable.TAP_TOLERANCE) {
5906 simulateClickTouch = first;
5910 if (!L.Browser.touch) {
5911 L.DomUtil.enableTextSelection();
5912 this._restoreCursor();
5915 for (var i in L.Draggable.MOVE) {
5916 if (L.Draggable.MOVE.hasOwnProperty(i)) {
5917 L.DomEvent.off(document, L.Draggable.MOVE[i], this._onMove);
5918 L.DomEvent.off(document, L.Draggable.END[i], this._onUp);
5923 // ensure drag is not fired after dragend
5924 L.Util.cancelAnimFrame(this._animRequest);
5926 this.fire('dragend');
5928 this._moving = false;
5930 if (simulateClickTouch) {
5931 this._moved = false;
5932 this._simulateEvent('click', simulateClickTouch);
5936 _setMovingCursor: function () {
5937 L.DomUtil.addClass(document.body, 'leaflet-dragging');
5940 _restoreCursor: function () {
5941 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
5944 _simulateEvent: function (type, e) {
5945 var simulatedEvent = document.createEvent('MouseEvents');
5947 simulatedEvent.initMouseEvent(
5948 type, true, true, window, 1,
5949 e.screenX, e.screenY,
5950 e.clientX, e.clientY,
5951 false, false, false, false, 0, null);
5953 e.target.dispatchEvent(simulatedEvent);
5959 L.Handler is a base class for handler classes that are used internally to inject
5960 interaction features like dragging to classes like Map and Marker.
5963 L.Handler = L.Class.extend({
5964 initialize: function (map) {
5968 enable: function () {
5969 if (this._enabled) { return; }
5971 this._enabled = true;
5975 disable: function () {
5976 if (!this._enabled) { return; }
5978 this._enabled = false;
5982 enabled: function () {
5983 return !!this._enabled;
5989 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
5992 L.Map.mergeOptions({
5995 inertia: !L.Browser.android23,
5996 inertiaDeceleration: 3400, // px/s^2
5997 inertiaMaxSpeed: Infinity, // px/s
5998 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
5999 easeLinearity: 0.25,
6003 // TODO refactor, move to CRS
6004 worldCopyJump: false
6007 L.Map.Drag = L.Handler.extend({
6008 addHooks: function () {
6009 if (!this._draggable) {
6010 var map = this._map;
6012 this._draggable = new L.Draggable(map._mapPane, map._container, map.options.longPress);
6014 this._draggable.on({
6015 'dragstart': this._onDragStart,
6016 'drag': this._onDrag,
6017 'dragend': this._onDragEnd
6020 if (map.options.worldCopyJump) {
6021 this._draggable.on('predrag', this._onPreDrag, this);
6022 map.on('viewreset', this._onViewReset, this);
6025 this._draggable.enable();
6028 removeHooks: function () {
6029 this._draggable.disable();
6032 moved: function () {
6033 return this._draggable && this._draggable._moved;
6036 _onDragStart: function () {
6037 var map = this._map;
6040 map._panAnim.stop();
6047 if (map.options.inertia) {
6048 this._positions = [];
6053 _onDrag: function () {
6054 if (this._map.options.inertia) {
6055 var time = this._lastTime = +new Date(),
6056 pos = this._lastPos = this._draggable._newPos;
6058 this._positions.push(pos);
6059 this._times.push(time);
6061 if (time - this._times[0] > 200) {
6062 this._positions.shift();
6063 this._times.shift();
6072 _onViewReset: function () {
6073 // TODO fix hardcoded Earth values
6074 var pxCenter = this._map.getSize()._divideBy(2),
6075 pxWorldCenter = this._map.latLngToLayerPoint(new L.LatLng(0, 0));
6077 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6078 this._worldWidth = this._map.project(new L.LatLng(0, 180)).x;
6081 _onPreDrag: function () {
6082 // TODO refactor to be able to adjust map pane position after zoom
6083 var worldWidth = this._worldWidth,
6084 halfWidth = Math.round(worldWidth / 2),
6085 dx = this._initialWorldOffset,
6086 x = this._draggable._newPos.x,
6087 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6088 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6089 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6091 this._draggable._newPos.x = newX;
6094 _onDragEnd: function () {
6095 var map = this._map,
6096 options = map.options,
6097 delay = +new Date() - this._lastTime,
6099 noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6102 map.fire('moveend');
6106 var direction = this._lastPos.subtract(this._positions[0]),
6107 duration = (this._lastTime + delay - this._times[0]) / 1000,
6108 ease = options.easeLinearity,
6110 speedVector = direction.multiplyBy(ease / duration),
6111 speed = speedVector.distanceTo(new L.Point(0, 0)),
6113 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6114 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6116 decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6117 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6119 L.Util.requestAnimFrame(function () {
6120 map.panBy(offset, decelerationDuration, ease);
6124 map.fire('dragend');
6126 if (options.maxBounds) {
6127 // TODO predrag validation instead of animation
6128 L.Util.requestAnimFrame(this._panInsideMaxBounds, map, true, map._container);
6132 _panInsideMaxBounds: function () {
6133 this.panInsideBounds(this.options.maxBounds);
6137 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6141 * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6144 L.Map.mergeOptions({
6145 doubleClickZoom: true
6148 L.Map.DoubleClickZoom = L.Handler.extend({
6149 addHooks: function () {
6150 this._map.on('dblclick', this._onDoubleClick);
6153 removeHooks: function () {
6154 this._map.off('dblclick', this._onDoubleClick);
6157 _onDoubleClick: function (e) {
6158 this.setView(e.latlng, this._zoom + 1);
6162 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
6166 * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
6169 L.Map.mergeOptions({
6170 scrollWheelZoom: true
6173 L.Map.ScrollWheelZoom = L.Handler.extend({
6174 addHooks: function () {
6175 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
6179 removeHooks: function () {
6180 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
6183 _onWheelScroll: function (e) {
6184 var delta = L.DomEvent.getWheelDelta(e);
6186 this._delta += delta;
6187 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
6189 if (!this._startTime) {
6190 this._startTime = +new Date();
6193 var left = Math.max(40 - (+new Date() - this._startTime), 0);
6195 clearTimeout(this._timer);
6196 this._timer = setTimeout(L.bind(this._performZoom, this), left);
6198 L.DomEvent.preventDefault(e);
6199 L.DomEvent.stopPropagation(e);
6202 _performZoom: function () {
6203 var map = this._map,
6204 delta = this._delta,
6205 zoom = map.getZoom();
6207 delta = delta > 0 ? Math.ceil(delta) : Math.round(delta);
6208 delta = Math.max(Math.min(delta, 4), -4);
6209 delta = map._limitZoom(zoom + delta) - zoom;
6213 this._startTime = null;
6215 if (!delta) { return; }
6217 var newZoom = zoom + delta,
6218 newCenter = this._getCenterForScrollWheelZoom(newZoom);
6220 map.setView(newCenter, newZoom);
6223 _getCenterForScrollWheelZoom: function (newZoom) {
6224 var map = this._map,
6225 scale = map.getZoomScale(newZoom),
6226 viewHalf = map.getSize()._divideBy(2),
6227 centerOffset = this._lastMousePos._subtract(viewHalf)._multiplyBy(1 - 1 / scale),
6228 newCenterPoint = map._getTopLeftPoint()._add(viewHalf)._add(centerOffset);
6230 return map.unproject(newCenterPoint);
6234 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
6238 * Extends the event handling code with double tap support for mobile browsers.
6241 L.extend(L.DomEvent, {
6243 _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
6244 _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
6246 // inspired by Zepto touch code by Thomas Fuchs
6247 addDoubleTapListener: function (obj, handler, id) {
6253 touchstart = this._touchstart,
6254 touchend = this._touchend,
6255 trackedTouches = [];
6257 function onTouchStart(e) {
6259 if (L.Browser.msTouch) {
6260 trackedTouches.push(e.pointerId);
6261 count = trackedTouches.length;
6263 count = e.touches.length;
6269 var now = Date.now(),
6270 delta = now - (last || now);
6272 touch = e.touches ? e.touches[0] : e;
6273 doubleTap = (delta > 0 && delta <= delay);
6277 function onTouchEnd(e) {
6278 /*jshint forin:false */
6279 if (L.Browser.msTouch) {
6280 var idx = trackedTouches.indexOf(e.pointerId);
6284 trackedTouches.splice(idx, 1);
6288 if (L.Browser.msTouch) {
6289 //Work around .type being readonly with MSPointer* events
6293 for (var i in touch) {
6295 if (typeof prop === 'function') {
6296 newTouch[i] = prop.bind(touch);
6303 touch.type = 'dblclick';
6308 obj[pre + touchstart + id] = onTouchStart;
6309 obj[pre + touchend + id] = onTouchEnd;
6311 //On msTouch we need to listen on the document otherwise a drag starting on the map and moving off screen will not come through to us
6312 // so we will lose track of how many touches are ongoing
6313 var endElement = L.Browser.msTouch ? document.documentElement : obj;
6315 obj.addEventListener(touchstart, onTouchStart, false);
6316 endElement.addEventListener(touchend, onTouchEnd, false);
6317 if (L.Browser.msTouch) {
6318 endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
6323 removeDoubleTapListener: function (obj, id) {
6324 var pre = '_leaflet_';
6325 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
6326 (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(this._touchend, obj[pre + this._touchend + id], false);
6327 if (L.Browser.msTouch) {
6328 document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
6336 * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
6339 L.extend(L.DomEvent, {
6342 _msDocumentListener: false,
6344 // Provides a touch events wrapper for msPointer events.
6345 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
6347 addMsTouchListener: function (obj, type, handler, id) {
6351 return this.addMsTouchListenerStart(obj, type, handler, id);
6353 return this.addMsTouchListenerEnd(obj, type, handler, id);
6355 return this.addMsTouchListenerMove(obj, type, handler, id);
6357 throw 'Unknown touch event type';
6361 addMsTouchListenerStart: function (obj, type, handler, id) {
6362 var pre = '_leaflet_',
6363 touches = this._msTouches;
6365 var cb = function (e) {
6367 var alreadyInArray = false;
6368 for (var i = 0; i < touches.length; i++) {
6369 if (touches[i].pointerId === e.pointerId) {
6370 alreadyInArray = true;
6374 if (!alreadyInArray) {
6378 e.touches = touches.slice();
6379 e.changedTouches = [e];
6384 obj[pre + 'touchstart' + id] = cb;
6385 obj.addEventListener('MSPointerDown', cb, false);
6387 // need to also listen for end events to keep the _msTouches list accurate
6388 // this needs to be on the body and never go away
6389 if (!this._msDocumentListener) {
6390 var internalCb = function (e) {
6391 for (var i = 0; i < touches.length; i++) {
6392 if (touches[i].pointerId === e.pointerId) {
6393 touches.splice(i, 1);
6398 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
6399 document.documentElement.addEventListener('MSPointerUp', internalCb, false);
6400 document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
6402 this._msDocumentListener = true;
6408 addMsTouchListenerMove: function (obj, type, handler, id) {
6409 var pre = '_leaflet_',
6410 touches = this._msTouches;
6414 // don't fire touch moves when mouse isn't down
6415 if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) { return; }
6417 for (var i = 0; i < touches.length; i++) {
6418 if (touches[i].pointerId === e.pointerId) {
6424 e.touches = touches.slice();
6425 e.changedTouches = [e];
6430 obj[pre + 'touchmove' + id] = cb;
6431 obj.addEventListener('MSPointerMove', cb, false);
6436 addMsTouchListenerEnd: function (obj, type, handler, id) {
6437 var pre = '_leaflet_',
6438 touches = this._msTouches;
6440 var cb = function (e) {
6441 for (var i = 0; i < touches.length; i++) {
6442 if (touches[i].pointerId === e.pointerId) {
6443 touches.splice(i, 1);
6448 e.touches = touches.slice();
6449 e.changedTouches = [e];
6454 obj[pre + 'touchend' + id] = cb;
6455 obj.addEventListener('MSPointerUp', cb, false);
6456 obj.addEventListener('MSPointerCancel', cb, false);
6461 removeMsTouchListener: function (obj, type, id) {
6462 var pre = '_leaflet_',
6463 cb = obj[pre + type + id];
6467 obj.removeEventListener('MSPointerDown', cb, false);
6470 obj.removeEventListener('MSPointerMove', cb, false);
6473 obj.removeEventListener('MSPointerUp', cb, false);
6474 obj.removeEventListener('MSPointerCancel', cb, false);
6484 * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
6487 L.Map.mergeOptions({
6488 touchZoom: L.Browser.touch && !L.Browser.android23
6491 L.Map.TouchZoom = L.Handler.extend({
6492 addHooks: function () {
6493 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
6496 removeHooks: function () {
6497 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
6500 _onTouchStart: function (e) {
6501 var map = this._map;
6503 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
6505 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
6506 p2 = map.mouseEventToLayerPoint(e.touches[1]),
6507 viewCenter = map._getCenterLayerPoint();
6509 this._startCenter = p1.add(p2)._divideBy(2);
6510 this._startDist = p1.distanceTo(p2);
6512 this._moved = false;
6513 this._zooming = true;
6515 this._centerOffset = viewCenter.subtract(this._startCenter);
6518 map._panAnim.stop();
6522 .on(document, 'touchmove', this._onTouchMove, this)
6523 .on(document, 'touchend', this._onTouchEnd, this);
6525 L.DomEvent.preventDefault(e);
6528 _onTouchMove: function (e) {
6529 if (!e.touches || e.touches.length !== 2) { return; }
6531 var map = this._map;
6533 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
6534 p2 = map.mouseEventToLayerPoint(e.touches[1]);
6536 this._scale = p1.distanceTo(p2) / this._startDist;
6537 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
6539 if (this._scale === 1) { return; }
6542 L.DomUtil.addClass(map._mapPane, 'leaflet-zoom-anim leaflet-touching');
6552 L.Util.cancelAnimFrame(this._animRequest);
6553 this._animRequest = L.Util.requestAnimFrame(
6554 this._updateOnMove, this, true, this._map._container);
6556 L.DomEvent.preventDefault(e);
6559 _updateOnMove: function () {
6560 var map = this._map,
6561 origin = this._getScaleOrigin(),
6562 center = map.layerPointToLatLng(origin);
6564 map.fire('zoomanim', {
6566 zoom: map.getScaleZoom(this._scale)
6569 // Used 2 translates instead of transform-origin because of a very strange bug -
6570 // it didn't count the origin on the first touch-zoom but worked correctly afterwards
6572 map._tileBg.style[L.DomUtil.TRANSFORM] =
6573 L.DomUtil.getTranslateString(this._delta) + ' ' +
6574 L.DomUtil.getScaleString(this._scale, this._startCenter);
6577 _onTouchEnd: function () {
6578 if (!this._moved || !this._zooming) { return; }
6580 var map = this._map;
6582 this._zooming = false;
6583 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
6586 .off(document, 'touchmove', this._onTouchMove)
6587 .off(document, 'touchend', this._onTouchEnd);
6589 var origin = this._getScaleOrigin(),
6590 center = map.layerPointToLatLng(origin),
6592 oldZoom = map.getZoom(),
6593 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
6594 roundZoomDelta = (floatZoomDelta > 0 ?
6595 Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
6597 zoom = map._limitZoom(oldZoom + roundZoomDelta);
6599 map.fire('zoomanim', {
6604 map._runAnimation(center, zoom, map.getZoomScale(zoom) / this._scale, origin, true);
6607 _getScaleOrigin: function () {
6608 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
6609 return this._startCenter.add(centerOffset);
6613 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
6617 * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
6618 * (zoom to a selected bounding box), enabled by default.
6621 L.Map.mergeOptions({
6625 L.Map.BoxZoom = L.Handler.extend({
6626 initialize: function (map) {
6628 this._container = map._container;
6629 this._pane = map._panes.overlayPane;
6632 addHooks: function () {
6633 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
6636 removeHooks: function () {
6637 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
6640 _onMouseDown: function (e) {
6641 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
6643 L.DomUtil.disableTextSelection();
6645 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
6647 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
6648 L.DomUtil.setPosition(this._box, this._startLayerPoint);
6650 //TODO refactor: move cursor to styles
6651 this._container.style.cursor = 'crosshair';
6654 .on(document, 'mousemove', this._onMouseMove, this)
6655 .on(document, 'mouseup', this._onMouseUp, this)
6658 this._map.fire("boxzoomstart");
6661 _onMouseMove: function (e) {
6662 var startPoint = this._startLayerPoint,
6665 layerPoint = this._map.mouseEventToLayerPoint(e),
6666 offset = layerPoint.subtract(startPoint),
6668 newPos = new L.Point(
6669 Math.min(layerPoint.x, startPoint.x),
6670 Math.min(layerPoint.y, startPoint.y));
6672 L.DomUtil.setPosition(box, newPos);
6674 // TODO refactor: remove hardcoded 4 pixels
6675 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
6676 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
6679 _onMouseUp: function (e) {
6680 this._pane.removeChild(this._box);
6681 this._container.style.cursor = '';
6683 L.DomUtil.enableTextSelection();
6686 .off(document, 'mousemove', this._onMouseMove)
6687 .off(document, 'mouseup', this._onMouseUp);
6689 var map = this._map,
6690 layerPoint = map.mouseEventToLayerPoint(e);
6692 if (this._startLayerPoint.equals(layerPoint)) { return; }
6694 var bounds = new L.LatLngBounds(
6695 map.layerPointToLatLng(this._startLayerPoint),
6696 map.layerPointToLatLng(layerPoint));
6698 map.fitBounds(bounds);
6700 map.fire("boxzoomend", {
6701 boxZoomBounds: bounds
6706 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
6710 * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
6713 L.Map.mergeOptions({
6715 keyboardPanOffset: 80,
6716 keyboardZoomOffset: 1
6719 L.Map.Keyboard = L.Handler.extend({
6726 zoomIn: [187, 107, 61],
6727 zoomOut: [189, 109, 173]
6730 initialize: function (map) {
6733 this._setPanOffset(map.options.keyboardPanOffset);
6734 this._setZoomOffset(map.options.keyboardZoomOffset);
6737 addHooks: function () {
6738 var container = this._map._container;
6740 // make the container focusable by tabbing
6741 if (container.tabIndex === -1) {
6742 container.tabIndex = "0";
6746 .on(container, 'focus', this._onFocus, this)
6747 .on(container, 'blur', this._onBlur, this)
6748 .on(container, 'mousedown', this._onMouseDown, this);
6751 .on('focus', this._addHooks, this)
6752 .on('blur', this._removeHooks, this);
6755 removeHooks: function () {
6756 this._removeHooks();
6758 var container = this._map._container;
6761 .off(container, 'focus', this._onFocus, this)
6762 .off(container, 'blur', this._onBlur, this)
6763 .off(container, 'mousedown', this._onMouseDown, this);
6766 .off('focus', this._addHooks, this)
6767 .off('blur', this._removeHooks, this);
6770 _onMouseDown: function () {
6771 if (!this._focused) {
6772 this._map._container.focus();
6776 _onFocus: function () {
6777 this._focused = true;
6778 this._map.fire('focus');
6781 _onBlur: function () {
6782 this._focused = false;
6783 this._map.fire('blur');
6786 _setPanOffset: function (pan) {
6787 var keys = this._panKeys = {},
6788 codes = this.keyCodes,
6791 for (i = 0, len = codes.left.length; i < len; i++) {
6792 keys[codes.left[i]] = [-1 * pan, 0];
6794 for (i = 0, len = codes.right.length; i < len; i++) {
6795 keys[codes.right[i]] = [pan, 0];
6797 for (i = 0, len = codes.down.length; i < len; i++) {
6798 keys[codes.down[i]] = [0, pan];
6800 for (i = 0, len = codes.up.length; i < len; i++) {
6801 keys[codes.up[i]] = [0, -1 * pan];
6805 _setZoomOffset: function (zoom) {
6806 var keys = this._zoomKeys = {},
6807 codes = this.keyCodes,
6810 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
6811 keys[codes.zoomIn[i]] = zoom;
6813 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
6814 keys[codes.zoomOut[i]] = -zoom;
6818 _addHooks: function () {
6819 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
6822 _removeHooks: function () {
6823 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
6826 _onKeyDown: function (e) {
6827 var key = e.keyCode,
6830 if (this._panKeys.hasOwnProperty(key)) {
6831 map.panBy(this._panKeys[key]);
6833 if (map.options.maxBounds) {
6834 map.panInsideBounds(map.options.maxBounds);
6837 } else if (this._zoomKeys.hasOwnProperty(key)) {
6838 map.setZoom(map.getZoom() + this._zoomKeys[key]);
6848 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
6852 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
6855 L.Handler.MarkerDrag = L.Handler.extend({
6856 initialize: function (marker) {
6857 this._marker = marker;
6860 addHooks: function () {
6861 var icon = this._marker._icon;
6862 if (!this._draggable) {
6863 this._draggable = new L.Draggable(icon, icon)
6864 .on('dragstart', this._onDragStart, this)
6865 .on('drag', this._onDrag, this)
6866 .on('dragend', this._onDragEnd, this);
6868 this._draggable.enable();
6871 removeHooks: function () {
6872 this._draggable.disable();
6875 moved: function () {
6876 return this._draggable && this._draggable._moved;
6879 _onDragStart: function () {
6886 _onDrag: function () {
6887 var marker = this._marker,
6888 shadow = marker._shadow,
6889 iconPos = L.DomUtil.getPosition(marker._icon),
6890 latlng = marker._map.layerPointToLatLng(iconPos);
6892 // update shadow position
6894 L.DomUtil.setPosition(shadow, iconPos);
6897 marker._latlng = latlng;
6900 .fire('move', {latlng: latlng})
6904 _onDragEnd: function () {
6913 * L.Handler.PolyEdit is an editing handler for polylines and polygons.
6916 L.Handler.PolyEdit = L.Handler.extend({
6918 icon: new L.DivIcon({
6919 iconSize: new L.Point(8, 8),
6920 className: 'leaflet-div-icon leaflet-editing-icon'
6924 initialize: function (poly, options) {
6926 L.setOptions(this, options);
6929 addHooks: function () {
6930 if (this._poly._map) {
6931 if (!this._markerGroup) {
6932 this._initMarkers();
6934 this._poly._map.addLayer(this._markerGroup);
6938 removeHooks: function () {
6939 if (this._poly._map) {
6940 this._poly._map.removeLayer(this._markerGroup);
6941 delete this._markerGroup;
6942 delete this._markers;
6946 updateMarkers: function () {
6947 this._markerGroup.clearLayers();
6948 this._initMarkers();
6951 _initMarkers: function () {
6952 if (!this._markerGroup) {
6953 this._markerGroup = new L.LayerGroup();
6957 var latlngs = this._poly._latlngs,
6960 // TODO refactor holes implementation in Polygon to support it here
6962 for (i = 0, len = latlngs.length; i < len; i++) {
6964 marker = this._createMarker(latlngs[i], i);
6965 marker.on('click', this._onMarkerClick, this);
6966 this._markers.push(marker);
6969 var markerLeft, markerRight;
6971 for (i = 0, j = len - 1; i < len; j = i++) {
6972 if (i === 0 && !(L.Polygon && (this._poly instanceof L.Polygon))) {
6976 markerLeft = this._markers[j];
6977 markerRight = this._markers[i];
6979 this._createMiddleMarker(markerLeft, markerRight);
6980 this._updatePrevNext(markerLeft, markerRight);
6984 _createMarker: function (latlng, index) {
6985 var marker = new L.Marker(latlng, {
6987 icon: this.options.icon
6990 marker._origLatLng = latlng;
6991 marker._index = index;
6993 marker.on('drag', this._onMarkerDrag, this);
6994 marker.on('dragend', this._fireEdit, this);
6996 this._markerGroup.addLayer(marker);
7001 _fireEdit: function () {
7002 this._poly.fire('edit');
7005 _onMarkerDrag: function (e) {
7006 var marker = e.target;
7008 L.extend(marker._origLatLng, marker._latlng);
7010 if (marker._middleLeft) {
7011 marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
7013 if (marker._middleRight) {
7014 marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
7017 this._poly.redraw();
7020 _onMarkerClick: function (e) {
7021 // we want to remove the marker on click, but if latlng count < 3, polyline would be invalid
7022 if (this._poly._latlngs.length < 3) { return; }
7024 var marker = e.target,
7027 // remove the marker
7028 this._markerGroup.removeLayer(marker);
7029 this._markers.splice(i, 1);
7030 this._poly.spliceLatLngs(i, 1);
7031 this._updateIndexes(i, -1);
7033 // update prev/next links of adjacent markers
7034 this._updatePrevNext(marker._prev, marker._next);
7036 // remove ghost markers near the removed marker
7037 if (marker._middleLeft) {
7038 this._markerGroup.removeLayer(marker._middleLeft);
7040 if (marker._middleRight) {
7041 this._markerGroup.removeLayer(marker._middleRight);
7044 // create a ghost marker in place of the removed one
7045 if (marker._prev && marker._next) {
7046 this._createMiddleMarker(marker._prev, marker._next);
7048 } else if (!marker._prev) {
7049 marker._next._middleLeft = null;
7051 } else if (!marker._next) {
7052 marker._prev._middleRight = null;
7055 this._poly.fire('edit');
7058 _updateIndexes: function (index, delta) {
7059 this._markerGroup.eachLayer(function (marker) {
7060 if (marker._index > index) {
7061 marker._index += delta;
7066 _createMiddleMarker: function (marker1, marker2) {
7067 var latlng = this._getMiddleLatLng(marker1, marker2),
7068 marker = this._createMarker(latlng),
7073 marker.setOpacity(0.6);
7075 marker1._middleRight = marker2._middleLeft = marker;
7077 onDragStart = function () {
7078 var i = marker2._index;
7083 .off('click', onClick)
7084 .on('click', this._onMarkerClick, this);
7086 latlng.lat = marker.getLatLng().lat;
7087 latlng.lng = marker.getLatLng().lng;
7088 this._poly.spliceLatLngs(i, 0, latlng);
7089 this._markers.splice(i, 0, marker);
7091 marker.setOpacity(1);
7093 this._updateIndexes(i, 1);
7095 this._updatePrevNext(marker1, marker);
7096 this._updatePrevNext(marker, marker2);
7099 onDragEnd = function () {
7100 marker.off('dragstart', onDragStart, this);
7101 marker.off('dragend', onDragEnd, this);
7103 this._createMiddleMarker(marker1, marker);
7104 this._createMiddleMarker(marker, marker2);
7107 onClick = function () {
7108 onDragStart.call(this);
7109 onDragEnd.call(this);
7110 this._poly.fire('edit');
7114 .on('click', onClick, this)
7115 .on('dragstart', onDragStart, this)
7116 .on('dragend', onDragEnd, this);
7118 this._markerGroup.addLayer(marker);
7121 _updatePrevNext: function (marker1, marker2) {
7123 marker1._next = marker2;
7126 marker2._prev = marker1;
7130 _getMiddleLatLng: function (marker1, marker2) {
7131 var map = this._poly._map,
7132 p1 = map.latLngToLayerPoint(marker1.getLatLng()),
7133 p2 = map.latLngToLayerPoint(marker2.getLatLng());
7135 return map.layerPointToLatLng(p1._add(p2)._divideBy(2));
7139 L.Polyline.addInitHook(function () {
7141 if (L.Handler.PolyEdit) {
7142 this.editing = new L.Handler.PolyEdit(this);
7144 if (this.options.editable) {
7145 this.editing.enable();
7149 this.on('add', function () {
7150 if (this.editing && this.editing.enabled()) {
7151 this.editing.addHooks();
7155 this.on('remove', function () {
7156 if (this.editing && this.editing.enabled()) {
7157 this.editing.removeHooks();
7164 * L.Control is a base class for implementing map controls. Handles positioning.
7165 * All other controls extend from this class.
7168 L.Control = L.Class.extend({
7170 position: 'topright'
7173 initialize: function (options) {
7174 L.setOptions(this, options);
7177 getPosition: function () {
7178 return this.options.position;
7181 setPosition: function (position) {
7182 var map = this._map;
7185 map.removeControl(this);
7188 this.options.position = position;
7191 map.addControl(this);
7197 addTo: function (map) {
7200 var container = this._container = this.onAdd(map),
7201 pos = this.getPosition(),
7202 corner = map._controlCorners[pos];
7204 L.DomUtil.addClass(container, 'leaflet-control');
7206 if (pos.indexOf('bottom') !== -1) {
7207 corner.insertBefore(container, corner.firstChild);
7209 corner.appendChild(container);
7215 removeFrom: function (map) {
7216 var pos = this.getPosition(),
7217 corner = map._controlCorners[pos];
7219 corner.removeChild(this._container);
7222 if (this.onRemove) {
7230 L.control = function (options) {
7231 return new L.Control(options);
7236 * Adds control-related methods to L.Map.
7240 addControl: function (control) {
7241 control.addTo(this);
7245 removeControl: function (control) {
7246 control.removeFrom(this);
7250 _initControlPos: function () {
7251 var corners = this._controlCorners = {},
7253 container = this._controlContainer =
7254 L.DomUtil.create('div', l + 'control-container', this._container);
7256 function createCorner(vSide, hSide) {
7257 var className = l + vSide + ' ' + l + hSide;
7259 corners[vSide + hSide] = L.DomUtil.create('div', className, container);
7262 createCorner('top', 'left');
7263 createCorner('top', 'right');
7264 createCorner('bottom', 'left');
7265 createCorner('bottom', 'right');
7271 * L.Control.Zoom is used for the default zoom buttons on the map.
7274 L.Control.Zoom = L.Control.extend({
7279 onAdd: function (map) {
7280 var zoomName = 'leaflet-control-zoom',
7281 barName = 'leaflet-bar',
7282 partName = barName + '-part',
7283 container = L.DomUtil.create('div', zoomName + ' ' + barName);
7287 this._zoomInButton = this._createButton('+', 'Zoom in',
7291 container, this._zoomIn, this);
7293 this._zoomOutButton = this._createButton('-', 'Zoom out',
7294 zoomName + '-out ' +
7296 partName + '-bottom',
7297 container, this._zoomOut, this);
7299 map.on('zoomend', this._updateDisabled, this);
7304 onRemove: function (map) {
7305 map.off('zoomend', this._updateDisabled, this);
7308 _zoomIn: function (e) {
7309 this._map.zoomIn(e.shiftKey ? 3 : 1);
7312 _zoomOut: function (e) {
7313 this._map.zoomOut(e.shiftKey ? 3 : 1);
7316 _createButton: function (html, title, className, container, fn, context) {
7317 var link = L.DomUtil.create('a', className, container);
7318 link.innerHTML = html;
7322 var stop = L.DomEvent.stopPropagation;
7325 .on(link, 'click', stop)
7326 .on(link, 'mousedown', stop)
7327 .on(link, 'dblclick', stop)
7328 .on(link, 'click', L.DomEvent.preventDefault)
7329 .on(link, 'click', fn, context);
7334 _updateDisabled: function () {
7335 var map = this._map,
7336 className = 'leaflet-control-zoom-disabled';
7338 L.DomUtil.removeClass(this._zoomInButton, className);
7339 L.DomUtil.removeClass(this._zoomOutButton, className);
7341 if (map._zoom === map.getMinZoom()) {
7342 L.DomUtil.addClass(this._zoomOutButton, className);
7344 if (map._zoom === map.getMaxZoom()) {
7345 L.DomUtil.addClass(this._zoomInButton, className);
7350 L.Map.mergeOptions({
7354 L.Map.addInitHook(function () {
7355 if (this.options.zoomControl) {
7356 this.zoomControl = new L.Control.Zoom();
7357 this.addControl(this.zoomControl);
7361 L.control.zoom = function (options) {
7362 return new L.Control.Zoom(options);
7368 * L.Control.Attribution is used for displaying attribution on the map (added by default).
7371 L.Control.Attribution = L.Control.extend({
7373 position: 'bottomright',
7374 prefix: 'Powered by <a href="http://leafletjs.com">Leaflet</a>'
7377 initialize: function (options) {
7378 L.setOptions(this, options);
7380 this._attributions = {};
7383 onAdd: function (map) {
7384 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
7385 L.DomEvent.disableClickPropagation(this._container);
7388 .on('layeradd', this._onLayerAdd, this)
7389 .on('layerremove', this._onLayerRemove, this);
7393 return this._container;
7396 onRemove: function (map) {
7398 .off('layeradd', this._onLayerAdd)
7399 .off('layerremove', this._onLayerRemove);
7403 setPrefix: function (prefix) {
7404 this.options.prefix = prefix;
7409 addAttribution: function (text) {
7410 if (!text) { return; }
7412 if (!this._attributions[text]) {
7413 this._attributions[text] = 0;
7415 this._attributions[text]++;
7422 removeAttribution: function (text) {
7423 if (!text) { return; }
7425 this._attributions[text]--;
7431 _update: function () {
7432 if (!this._map) { return; }
7436 for (var i in this._attributions) {
7437 if (this._attributions.hasOwnProperty(i) && this._attributions[i]) {
7442 var prefixAndAttribs = [];
7444 if (this.options.prefix) {
7445 prefixAndAttribs.push(this.options.prefix);
7447 if (attribs.length) {
7448 prefixAndAttribs.push(attribs.join(', '));
7451 this._container.innerHTML = prefixAndAttribs.join(' — ');
7454 _onLayerAdd: function (e) {
7455 if (e.layer.getAttribution) {
7456 this.addAttribution(e.layer.getAttribution());
7460 _onLayerRemove: function (e) {
7461 if (e.layer.getAttribution) {
7462 this.removeAttribution(e.layer.getAttribution());
7467 L.Map.mergeOptions({
7468 attributionControl: true
7471 L.Map.addInitHook(function () {
7472 if (this.options.attributionControl) {
7473 this.attributionControl = (new L.Control.Attribution()).addTo(this);
7477 L.control.attribution = function (options) {
7478 return new L.Control.Attribution(options);
7483 * L.Control.Scale is used for displaying metric/imperial scale on the map.
7486 L.Control.Scale = L.Control.extend({
7488 position: 'bottomleft',
7492 updateWhenIdle: false
7495 onAdd: function (map) {
7498 var className = 'leaflet-control-scale',
7499 container = L.DomUtil.create('div', className),
7500 options = this.options;
7502 this._addScales(options, className, container);
7504 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
7505 map.whenReady(this._update, this);
7510 onRemove: function (map) {
7511 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
7514 _addScales: function (options, className, container) {
7515 if (options.metric) {
7516 this._mScale = L.DomUtil.create('div', className + '-line', container);
7518 if (options.imperial) {
7519 this._iScale = L.DomUtil.create('div', className + '-line', container);
7523 _update: function () {
7524 var bounds = this._map.getBounds(),
7525 centerLat = bounds.getCenter().lat,
7526 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
7527 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
7529 size = this._map.getSize(),
7530 options = this.options,
7534 maxMeters = dist * (options.maxWidth / size.x);
7537 this._updateScales(options, maxMeters);
7540 _updateScales: function (options, maxMeters) {
7541 if (options.metric && maxMeters) {
7542 this._updateMetric(maxMeters);
7545 if (options.imperial && maxMeters) {
7546 this._updateImperial(maxMeters);
7550 _updateMetric: function (maxMeters) {
7551 var meters = this._getRoundNum(maxMeters);
7553 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
7554 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
7557 _updateImperial: function (maxMeters) {
7558 var maxFeet = maxMeters * 3.2808399,
7559 scale = this._iScale,
7560 maxMiles, miles, feet;
7562 if (maxFeet > 5280) {
7563 maxMiles = maxFeet / 5280;
7564 miles = this._getRoundNum(maxMiles);
7566 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
7567 scale.innerHTML = miles + ' mi';
7570 feet = this._getRoundNum(maxFeet);
7572 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
7573 scale.innerHTML = feet + ' ft';
7577 _getScaleWidth: function (ratio) {
7578 return Math.round(this.options.maxWidth * ratio) - 10;
7581 _getRoundNum: function (num) {
7582 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
7585 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
7591 L.control.scale = function (options) {
7592 return new L.Control.Scale(options);
7597 * L.Control.Layers is a control to allow users to switch between different layers on the map.
7600 L.Control.Layers = L.Control.extend({
7603 position: 'topright',
7607 initialize: function (baseLayers, overlays, options) {
7608 L.setOptions(this, options);
7611 this._lastZIndex = 0;
7612 this._handlingClick = false;
7614 for (var i in baseLayers) {
7615 if (baseLayers.hasOwnProperty(i)) {
7616 this._addLayer(baseLayers[i], i);
7620 for (i in overlays) {
7621 if (overlays.hasOwnProperty(i)) {
7622 this._addLayer(overlays[i], i, true);
7627 onAdd: function (map) {
7632 .on('layeradd', this._onLayerChange, this)
7633 .on('layerremove', this._onLayerChange, this);
7635 return this._container;
7638 onRemove: function (map) {
7640 .off('layeradd', this._onLayerChange)
7641 .off('layerremove', this._onLayerChange);
7644 addBaseLayer: function (layer, name) {
7645 this._addLayer(layer, name);
7650 addOverlay: function (layer, name) {
7651 this._addLayer(layer, name, true);
7656 removeLayer: function (layer) {
7657 var id = L.stamp(layer);
7658 delete this._layers[id];
7663 _initLayout: function () {
7664 var className = 'leaflet-control-layers',
7665 container = this._container = L.DomUtil.create('div', className);
7667 if (!L.Browser.touch) {
7668 L.DomEvent.disableClickPropagation(container);
7669 L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
7671 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
7674 var form = this._form = L.DomUtil.create('form', className + '-list');
7676 if (this.options.collapsed) {
7678 .on(container, 'mouseover', this._expand, this)
7679 .on(container, 'mouseout', this._collapse, this);
7681 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
7683 link.title = 'Layers';
7685 if (L.Browser.touch) {
7687 .on(link, 'click', L.DomEvent.stopPropagation)
7688 .on(link, 'click', L.DomEvent.preventDefault)
7689 .on(link, 'click', this._expand, this);
7692 L.DomEvent.on(link, 'focus', this._expand, this);
7695 this._map.on('movestart', this._collapse, this);
7696 // TODO keyboard accessibility
7701 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
7702 this._separator = L.DomUtil.create('div', className + '-separator', form);
7703 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
7705 container.appendChild(form);
7708 _addLayer: function (layer, name, overlay) {
7709 var id = L.stamp(layer);
7711 this._layers[id] = {
7717 if (this.options.autoZIndex && layer.setZIndex) {
7719 layer.setZIndex(this._lastZIndex);
7723 _update: function () {
7724 if (!this._container) {
7728 this._baseLayersList.innerHTML = '';
7729 this._overlaysList.innerHTML = '';
7731 var baseLayersPresent = false,
7732 overlaysPresent = false;
7734 for (var i in this._layers) {
7735 if (this._layers.hasOwnProperty(i)) {
7736 var obj = this._layers[i];
7738 overlaysPresent = overlaysPresent || obj.overlay;
7739 baseLayersPresent = baseLayersPresent || !obj.overlay;
7743 this._separator.style.display = (overlaysPresent && baseLayersPresent ? '' : 'none');
7746 _onLayerChange: function (e) {
7747 var id = L.stamp(e.layer);
7749 if (this._layers[id] && !this._handlingClick) {
7754 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
7755 _createRadioElement: function (name, checked) {
7757 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
7759 radioHtml += ' checked="checked"';
7763 var radioFragment = document.createElement('div');
7764 radioFragment.innerHTML = radioHtml;
7766 return radioFragment.firstChild;
7769 _addItem: function (obj) {
7770 var label = document.createElement('label'),
7772 checked = this._map.hasLayer(obj.layer);
7775 input = document.createElement('input');
7776 input.type = 'checkbox';
7777 input.className = 'leaflet-control-layers-selector';
7778 input.defaultChecked = checked;
7780 input = this._createRadioElement('leaflet-base-layers', checked);
7783 input.layerId = L.stamp(obj.layer);
7785 L.DomEvent.on(input, 'click', this._onInputClick, this);
7787 var name = document.createElement('span');
7788 name.innerHTML = ' ' + obj.name;
7790 label.appendChild(input);
7791 label.appendChild(name);
7793 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
7794 container.appendChild(label);
7799 _onInputClick: function () {
7801 inputs = this._form.getElementsByTagName('input'),
7802 inputsLen = inputs.length,
7805 this._handlingClick = true;
7807 for (i = 0; i < inputsLen; i++) {
7809 obj = this._layers[input.layerId];
7811 if (input.checked && !this._map.hasLayer(obj.layer)) {
7812 this._map.addLayer(obj.layer);
7814 baseLayer = obj.layer;
7816 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
7817 this._map.removeLayer(obj.layer);
7822 this._map.setZoom(this._map.getZoom());
7823 this._map.fire('baselayerchange', {layer: baseLayer});
7826 this._handlingClick = false;
7829 _expand: function () {
7830 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
7833 _collapse: function () {
7834 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
7838 L.control.layers = function (baseLayers, overlays, options) {
7839 return new L.Control.Layers(baseLayers, overlays, options);
7844 * L.PosAnimation is used by Leaflet internally for pan animations.
7847 L.PosAnimation = L.Class.extend({
7848 includes: L.Mixin.Events,
7850 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
7854 this._inProgress = true;
7858 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
7859 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
7861 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7862 L.DomUtil.setPosition(el, newPos);
7864 // toggle reflow, Chrome flickers for some reason if you don't do this
7865 L.Util.falseFn(el.offsetWidth);
7867 // there's no native way to track value updates of transitioned properties, so we imitate this
7868 this._stepTimer = setInterval(L.bind(this.fire, this, 'step'), 50);
7872 if (!this._inProgress) { return; }
7874 // if we just removed the transition property, the element would jump to its final position,
7875 // so we need to make it stay at the current position
7877 L.DomUtil.setPosition(this._el, this._getPos());
7878 this._onTransitionEnd();
7879 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
7882 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
7883 // we need to parse computed style (in case of transform it returns matrix string)
7885 _transformRe: /(-?[\d\.]+), (-?[\d\.]+)\)/,
7887 _getPos: function () {
7888 var left, top, matches,
7890 style = window.getComputedStyle(el);
7892 if (L.Browser.any3d) {
7893 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
7894 left = parseFloat(matches[1]);
7895 top = parseFloat(matches[2]);
7897 left = parseFloat(style.left);
7898 top = parseFloat(style.top);
7901 return new L.Point(left, top, true);
7904 _onTransitionEnd: function () {
7905 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
7907 if (!this._inProgress) { return; }
7908 this._inProgress = false;
7910 this._el.style[L.DomUtil.TRANSITION] = '';
7912 clearInterval(this._stepTimer);
7914 this.fire('step').fire('end');
7921 * Extends L.Map to handle panning animations.
7926 setView: function (center, zoom, forceReset) {
7927 zoom = this._limitZoom(zoom);
7929 var zoomChanged = (this._zoom !== zoom);
7931 if (this._loaded && !forceReset && this._layers) {
7933 if (this._panAnim) {
7934 this._panAnim.stop();
7937 var done = (zoomChanged ?
7938 this._zoomToIfClose && this._zoomToIfClose(center, zoom) :
7939 this._panByIfClose(center));
7941 // exit if animated pan or zoom started
7943 clearTimeout(this._sizeTimer);
7948 // reset the map view
7949 this._resetView(center, zoom);
7954 panBy: function (offset, duration, easeLinearity) {
7955 offset = L.point(offset);
7957 if (!(offset.x || offset.y)) {
7961 if (!this._panAnim) {
7962 this._panAnim = new L.PosAnimation();
7965 'step': this._onPanTransitionStep,
7966 'end': this._onPanTransitionEnd
7970 this.fire('movestart');
7972 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
7974 var newPos = L.DomUtil.getPosition(this._mapPane).subtract(offset)._round();
7975 this._panAnim.run(this._mapPane, newPos, duration || 0.25, easeLinearity);
7980 _onPanTransitionStep: function () {
7984 _onPanTransitionEnd: function () {
7985 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
7986 this.fire('moveend');
7989 _panByIfClose: function (center) {
7990 // difference between the new and current centers in pixels
7991 var offset = this._getCenterOffset(center)._floor();
7993 if (this._offsetIsWithinView(offset)) {
8000 _offsetIsWithinView: function (offset, multiplyFactor) {
8001 var m = multiplyFactor || 1,
8002 size = this.getSize();
8004 return (Math.abs(offset.x) <= size.x * m) &&
8005 (Math.abs(offset.y) <= size.y * m);
8011 * L.PosAnimation fallback implementation that powers Leaflet pan animations
8012 * in browsers that don't support CSS3 Transitions.
8015 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8017 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8021 this._inProgress = true;
8022 this._duration = duration || 0.25;
8023 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8025 this._startPos = L.DomUtil.getPosition(el);
8026 this._offset = newPos.subtract(this._startPos);
8027 this._startTime = +new Date();
8035 if (!this._inProgress) { return; }
8041 _animate: function () {
8043 this._animId = L.Util.requestAnimFrame(this._animate, this);
8047 _step: function () {
8048 var elapsed = (+new Date()) - this._startTime,
8049 duration = this._duration * 1000;
8051 if (elapsed < duration) {
8052 this._runFrame(this._easeOut(elapsed / duration));
8059 _runFrame: function (progress) {
8060 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8061 L.DomUtil.setPosition(this._el, pos);
8066 _complete: function () {
8067 L.Util.cancelAnimFrame(this._animId);
8069 this._inProgress = false;
8073 _easeOut: function (t) {
8074 return 1 - Math.pow(1 - t, this._easeOutPower);
8080 * Extends L.Map to handle zoom animations.
8083 L.Map.mergeOptions({
8084 zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera
8087 if (L.DomUtil.TRANSITION) {
8088 L.Map.addInitHook(function () {
8089 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8093 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8095 _zoomToIfClose: function (center, zoom) {
8097 if (this._animatingZoom) { return true; }
8099 if (!this.options.zoomAnimation) { return false; }
8101 var scale = this.getZoomScale(zoom),
8102 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
8104 // if offset does not exceed half of the view
8105 if (!this._offsetIsWithinView(offset, 1)) { return false; }
8107 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8113 this.fire('zoomanim', {
8118 var origin = this._getCenterLayerPoint().add(offset);
8120 this._prepareTileBg();
8121 this._runAnimation(center, zoom, scale, origin);
8126 _catchTransitionEnd: function () {
8127 if (this._animatingZoom) {
8128 this._onZoomTransitionEnd();
8132 _runAnimation: function (center, zoom, scale, origin, backwardsTransform) {
8133 this._animateToCenter = center;
8134 this._animateToZoom = zoom;
8135 this._animatingZoom = true;
8138 L.Draggable._disabled = true;
8141 var transform = L.DomUtil.TRANSFORM,
8142 tileBg = this._tileBg;
8144 clearTimeout(this._clearTileBgTimer);
8146 L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation
8148 var scaleStr = L.DomUtil.getScaleString(scale, origin),
8149 oldTransform = tileBg.style[transform];
8151 tileBg.style[transform] = backwardsTransform ?
8152 oldTransform + ' ' + scaleStr :
8153 scaleStr + ' ' + oldTransform;
8156 _prepareTileBg: function () {
8157 var tilePane = this._tilePane,
8158 tileBg = this._tileBg;
8160 // If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more
8161 if (tileBg && this._getLoadedTilesPercentage(tileBg) > 0.5 &&
8162 this._getLoadedTilesPercentage(tilePane) < 0.5) {
8164 tilePane.style.visibility = 'hidden';
8165 tilePane.empty = true;
8166 this._stopLoadingImages(tilePane);
8171 tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane);
8172 tileBg.style.zIndex = 1;
8175 // prepare the background pane to become the main tile pane
8176 tileBg.style[L.DomUtil.TRANSFORM] = '';
8177 tileBg.style.visibility = 'hidden';
8179 // tells tile layers to reinitialize their containers
8180 tileBg.empty = true; //new FG
8181 tilePane.empty = false; //new BG
8183 //Switch out the current layer to be the new bg layer (And vice-versa)
8184 this._tilePane = this._panes.tilePane = tileBg;
8185 var newTileBg = this._tileBg = tilePane;
8187 L.DomUtil.addClass(newTileBg, 'leaflet-zoom-animated');
8189 this._stopLoadingImages(newTileBg);
8192 _getLoadedTilesPercentage: function (container) {
8193 var tiles = container.getElementsByTagName('img'),
8196 for (i = 0, len = tiles.length; i < len; i++) {
8197 if (tiles[i].complete) {
8204 // stops loading all tiles in the background layer
8205 _stopLoadingImages: function (container) {
8206 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
8209 for (i = 0, len = tiles.length; i < len; i++) {
8212 if (!tile.complete) {
8213 tile.onload = L.Util.falseFn;
8214 tile.onerror = L.Util.falseFn;
8215 tile.src = L.Util.emptyImageUrl;
8217 tile.parentNode.removeChild(tile);
8222 _onZoomTransitionEnd: function () {
8223 this._restoreTileFront();
8225 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8226 L.Util.falseFn(this._tileBg.offsetWidth); // force reflow
8227 this._animatingZoom = false;
8228 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8231 L.Draggable._disabled = false;
8235 _restoreTileFront: function () {
8236 this._tilePane.innerHTML = '';
8237 this._tilePane.style.visibility = '';
8238 this._tilePane.style.zIndex = 2;
8239 this._tileBg.style.zIndex = 1;
8242 _clearTileBg: function () {
8243 if (!this._animatingZoom && !this.touchZoom._zooming) {
8244 this._tileBg.innerHTML = '';
8251 * Provides L.Map with convenient shortcuts for using browser geolocation features.
8255 _defaultLocateOptions: {
8261 enableHighAccuracy: false
8264 locate: function (/*Object*/ options) {
8266 options = this._locationOptions = L.extend(this._defaultLocateOptions, options);
8268 if (!navigator.geolocation) {
8269 this._handleGeolocationError({
8271 message: "Geolocation not supported."
8276 var onResponse = L.bind(this._handleGeolocationResponse, this),
8277 onError = L.bind(this._handleGeolocationError, this);
8279 if (options.watch) {
8280 this._locationWatchId =
8281 navigator.geolocation.watchPosition(onResponse, onError, options);
8283 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
8288 stopLocate: function () {
8289 if (navigator.geolocation) {
8290 navigator.geolocation.clearWatch(this._locationWatchId);
8295 _handleGeolocationError: function (error) {
8297 message = error.message ||
8298 (c === 1 ? "permission denied" :
8299 (c === 2 ? "position unavailable" : "timeout"));
8301 if (this._locationOptions.setView && !this._loaded) {
8305 this.fire('locationerror', {
8307 message: "Geolocation error: " + message + "."
8311 _handleGeolocationResponse: function (pos) {
8312 var latAccuracy = 180 * pos.coords.accuracy / 4e7,
8313 lngAccuracy = latAccuracy * 2,
8315 lat = pos.coords.latitude,
8316 lng = pos.coords.longitude,
8317 latlng = new L.LatLng(lat, lng),
8319 sw = new L.LatLng(lat - latAccuracy, lng - lngAccuracy),
8320 ne = new L.LatLng(lat + latAccuracy, lng + lngAccuracy),
8321 bounds = new L.LatLngBounds(sw, ne),
8323 options = this._locationOptions;
8325 if (options.setView) {
8326 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
8327 this.setView(latlng, zoom);
8330 this.fire('locationfound', {
8333 accuracy: pos.coords.accuracy