2 Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
3 (c) 2010-2013, Vladimir Agafonkin
4 (c) 2010-2011, CloudMade
6 (function (window, document, undefined) {
12 // define Leaflet for Node module pattern loaders, including Browserify
13 if (typeof module === 'object' && typeof module.exports === 'object') {
16 // define Leaflet as an AMD module
17 } else if (typeof define === 'function' && define.amd) {
21 // define Leaflet as a global L variable, saving the original L to restore later if needed
23 L.noConflict = function () {
32 * L.Util contains various utility functions used throughout Leaflet code.
36 extend: function (dest) { // (Object[, Object, ...]) ->
37 var sources = Array.prototype.slice.call(arguments, 1),
40 for (j = 0, len = sources.length; j < len; j++) {
41 src = sources[j] || {};
43 if (src.hasOwnProperty(i)) {
51 bind: function (fn, obj) { // (Function, Object) -> Function
52 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
54 return fn.apply(obj, args || arguments);
61 return function (obj) {
62 obj[key] = obj[key] || ++lastId;
67 invokeEach: function (obj, method, context) {
70 if (typeof obj === 'object') {
71 args = Array.prototype.slice.call(arguments, 3);
74 method.apply(context, [i, obj[i]].concat(args));
82 limitExecByInterval: function (fn, time, context) {
83 var lock, execOnUnlock;
85 return function wrapperFn() {
95 setTimeout(function () {
99 wrapperFn.apply(context, args);
100 execOnUnlock = false;
104 fn.apply(context, args);
108 falseFn: function () {
112 formatNum: function (num, digits) {
113 var pow = Math.pow(10, digits || 5);
114 return Math.round(num * pow) / pow;
117 trim: function (str) {
118 return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
121 splitWords: function (str) {
122 return L.Util.trim(str).split(/\s+/);
125 setOptions: function (obj, options) {
126 obj.options = L.extend({}, obj.options, options);
130 getParamString: function (obj, existingUrl, uppercase) {
133 params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
135 return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
137 template: function (str, data) {
138 return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
139 var value = data[key];
140 if (value === undefined) {
141 throw new Error('No value provided for variable ' + str);
142 } else if (typeof value === 'function') {
149 isArray: Array.isArray || function (obj) {
150 return (Object.prototype.toString.call(obj) === '[object Array]');
153 emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
158 // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
160 function getPrefixed(name) {
162 prefixes = ['webkit', 'moz', 'o', 'ms'];
164 for (i = 0; i < prefixes.length && !fn; i++) {
165 fn = window[prefixes[i] + name];
173 function timeoutDefer(fn) {
174 var time = +new Date(),
175 timeToCall = Math.max(0, 16 - (time - lastTime));
177 lastTime = time + timeToCall;
178 return window.setTimeout(fn, timeToCall);
181 var requestFn = window.requestAnimationFrame ||
182 getPrefixed('RequestAnimationFrame') || timeoutDefer;
184 var cancelFn = window.cancelAnimationFrame ||
185 getPrefixed('CancelAnimationFrame') ||
186 getPrefixed('CancelRequestAnimationFrame') ||
187 function (id) { window.clearTimeout(id); };
190 L.Util.requestAnimFrame = function (fn, context, immediate, element) {
191 fn = L.bind(fn, context);
193 if (immediate && requestFn === timeoutDefer) {
196 return requestFn.call(window, fn, element);
200 L.Util.cancelAnimFrame = function (id) {
202 cancelFn.call(window, id);
208 // shortcuts for most used utility functions
209 L.extend = L.Util.extend;
210 L.bind = L.Util.bind;
211 L.stamp = L.Util.stamp;
212 L.setOptions = L.Util.setOptions;
216 * L.Class powers the OOP facilities of the library.
217 * Thanks to John Resig and Dean Edwards for inspiration!
220 L.Class = function () {};
222 L.Class.extend = function (props) {
224 // extended class with the new prototype
225 var NewClass = function () {
227 // call the constructor
228 if (this.initialize) {
229 this.initialize.apply(this, arguments);
232 // call all constructor hooks
233 if (this._initHooks) {
234 this.callInitHooks();
238 // instantiate class without calling constructor
239 var F = function () {};
240 F.prototype = this.prototype;
243 proto.constructor = NewClass;
245 NewClass.prototype = proto;
247 //inherit parent's statics
248 for (var i in this) {
249 if (this.hasOwnProperty(i) && i !== 'prototype') {
250 NewClass[i] = this[i];
254 // mix static properties into the class
256 L.extend(NewClass, props.statics);
257 delete props.statics;
260 // mix includes into the prototype
261 if (props.includes) {
262 L.Util.extend.apply(null, [proto].concat(props.includes));
263 delete props.includes;
267 if (props.options && proto.options) {
268 props.options = L.extend({}, proto.options, props.options);
271 // mix given properties into the prototype
272 L.extend(proto, props);
274 proto._initHooks = [];
277 // jshint camelcase: false
278 NewClass.__super__ = parent.prototype;
280 // add method for calling all hooks
281 proto.callInitHooks = function () {
283 if (this._initHooksCalled) { return; }
285 if (parent.prototype.callInitHooks) {
286 parent.prototype.callInitHooks.call(this);
289 this._initHooksCalled = true;
291 for (var i = 0, len = proto._initHooks.length; i < len; i++) {
292 proto._initHooks[i].call(this);
300 // method for adding properties to prototype
301 L.Class.include = function (props) {
302 L.extend(this.prototype, props);
305 // merge new default options to the Class
306 L.Class.mergeOptions = function (options) {
307 L.extend(this.prototype.options, options);
310 // add a constructor hook
311 L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
312 var args = Array.prototype.slice.call(arguments, 1);
314 var init = typeof fn === 'function' ? fn : function () {
315 this[fn].apply(this, args);
318 this.prototype._initHooks = this.prototype._initHooks || [];
319 this.prototype._initHooks.push(init);
324 * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
327 var eventsKey = '_leaflet_events';
333 addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
335 // types can be a map of types/handlers
336 if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
338 var events = this[eventsKey] = this[eventsKey] || {},
339 contextId = context && context !== this && L.stamp(context),
340 i, len, event, type, indexKey, indexLenKey, typeIndex;
342 // types can be a string of space-separated words
343 types = L.Util.splitWords(types);
345 for (i = 0, len = types.length; i < len; i++) {
348 context: context || this
353 // store listeners of a particular context in a separate hash (if it has an id)
354 // gives a major performance boost when removing thousands of map layers
356 indexKey = type + '_idx';
357 indexLenKey = indexKey + '_len';
359 typeIndex = events[indexKey] = events[indexKey] || {};
361 if (!typeIndex[contextId]) {
362 typeIndex[contextId] = [];
364 // keep track of the number of keys in the index to quickly check if it's empty
365 events[indexLenKey] = (events[indexLenKey] || 0) + 1;
368 typeIndex[contextId].push(event);
372 events[type] = events[type] || [];
373 events[type].push(event);
380 hasEventListeners: function (type) { // (String) -> Boolean
381 var events = this[eventsKey];
382 return !!events && ((type in events && events[type].length > 0) ||
383 (type + '_idx' in events && events[type + '_idx_len'] > 0));
386 removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
388 if (!this[eventsKey]) {
393 return this.clearAllEventListeners();
396 if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
398 var events = this[eventsKey],
399 contextId = context && context !== this && L.stamp(context),
400 i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
402 types = L.Util.splitWords(types);
404 for (i = 0, len = types.length; i < len; i++) {
406 indexKey = type + '_idx';
407 indexLenKey = indexKey + '_len';
409 typeIndex = events[indexKey];
412 // clear all listeners for a type if function isn't specified
414 delete events[indexKey];
415 delete events[indexLenKey];
418 listeners = contextId && typeIndex ? typeIndex[contextId] : events[type];
421 for (j = listeners.length - 1; j >= 0; j--) {
422 if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
423 removed = listeners.splice(j, 1);
424 // set the old action to a no-op, because it is possible
425 // that the listener is being iterated over as part of a dispatch
426 removed[0].action = L.Util.falseFn;
430 if (context && typeIndex && (listeners.length === 0)) {
431 delete typeIndex[contextId];
432 events[indexLenKey]--;
441 clearAllEventListeners: function () {
442 delete this[eventsKey];
446 fireEvent: function (type, data) { // (String[, Object])
447 if (!this.hasEventListeners(type)) {
451 var event = L.Util.extend({}, data, { type: type, target: this });
453 var events = this[eventsKey],
454 listeners, i, len, typeIndex, contextId;
457 // make sure adding/removing listeners inside other listeners won't cause infinite loop
458 listeners = events[type].slice();
460 for (i = 0, len = listeners.length; i < len; i++) {
461 listeners[i].action.call(listeners[i].context, event);
465 // fire event for the context-indexed listeners as well
466 typeIndex = events[type + '_idx'];
468 for (contextId in typeIndex) {
469 listeners = typeIndex[contextId].slice();
472 for (i = 0, len = listeners.length; i < len; i++) {
473 listeners[i].action.call(listeners[i].context, event);
481 addOneTimeEventListener: function (types, fn, context) {
483 if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
485 var handler = L.bind(function () {
487 .removeEventListener(types, fn, context)
488 .removeEventListener(types, handler, context);
492 .addEventListener(types, fn, context)
493 .addEventListener(types, handler, context);
497 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
498 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
499 L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
500 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
504 * L.Browser handles different browser and feature detections for internal Leaflet use.
509 var ie = 'ActiveXObject' in window,
510 ielt9 = ie && !document.addEventListener,
512 // terrible browser detection to work around Safari / iOS / Android browser bugs
513 ua = navigator.userAgent.toLowerCase(),
514 webkit = ua.indexOf('webkit') !== -1,
515 chrome = ua.indexOf('chrome') !== -1,
516 phantomjs = ua.indexOf('phantom') !== -1,
517 android = ua.indexOf('android') !== -1,
518 android23 = ua.search('android [23]') !== -1,
519 gecko = ua.indexOf('gecko') !== -1,
521 mobile = typeof orientation !== undefined + '',
522 msPointer = !window.PointerEvent && window.MSPointerEvent,
523 pointer = (window.PointerEvent && window.navigator.pointerEnabled && window.navigator.maxTouchPoints) ||
525 retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
526 ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
527 window.matchMedia('(min-resolution:144dpi)').matches),
529 doc = document.documentElement,
530 ie3d = ie && ('transition' in doc.style),
531 webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23,
532 gecko3d = 'MozPerspective' in doc.style,
533 opera3d = 'OTransition' in doc.style,
534 any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
536 var touch = !window.L_NO_TOUCH && !phantomjs && (pointer || 'ontouchstart' in window ||
537 (window.DocumentTouch && document instanceof window.DocumentTouch));
543 gecko: gecko && !webkit && !window.opera && !ie,
546 android23: android23,
557 mobileWebkit: mobile && webkit,
558 mobileWebkit3d: mobile && webkit3d,
559 mobileOpera: mobile && window.opera,
562 msPointer: msPointer,
572 * L.Point represents a point with x and y coordinates.
575 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
576 this.x = (round ? Math.round(x) : x);
577 this.y = (round ? Math.round(y) : y);
580 L.Point.prototype = {
583 return new L.Point(this.x, this.y);
586 // non-destructive, returns a new point
587 add: function (point) {
588 return this.clone()._add(L.point(point));
591 // destructive, used directly for performance in situations where it's safe to modify existing point
592 _add: function (point) {
598 subtract: function (point) {
599 return this.clone()._subtract(L.point(point));
602 _subtract: function (point) {
608 divideBy: function (num) {
609 return this.clone()._divideBy(num);
612 _divideBy: function (num) {
618 multiplyBy: function (num) {
619 return this.clone()._multiplyBy(num);
622 _multiplyBy: function (num) {
629 return this.clone()._round();
632 _round: function () {
633 this.x = Math.round(this.x);
634 this.y = Math.round(this.y);
639 return this.clone()._floor();
642 _floor: function () {
643 this.x = Math.floor(this.x);
644 this.y = Math.floor(this.y);
648 distanceTo: function (point) {
649 point = L.point(point);
651 var x = point.x - this.x,
652 y = point.y - this.y;
654 return Math.sqrt(x * x + y * y);
657 equals: function (point) {
658 point = L.point(point);
660 return point.x === this.x &&
664 contains: function (point) {
665 point = L.point(point);
667 return Math.abs(point.x) <= Math.abs(this.x) &&
668 Math.abs(point.y) <= Math.abs(this.y);
671 toString: function () {
673 L.Util.formatNum(this.x) + ', ' +
674 L.Util.formatNum(this.y) + ')';
678 L.point = function (x, y, round) {
679 if (x instanceof L.Point) {
682 if (L.Util.isArray(x)) {
683 return new L.Point(x[0], x[1]);
685 if (x === undefined || x === null) {
688 return new L.Point(x, y, round);
693 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
696 L.Bounds = function (a, b) { //(Point, Point) or Point[]
699 var points = b ? [a, b] : a;
701 for (var i = 0, len = points.length; i < len; i++) {
702 this.extend(points[i]);
706 L.Bounds.prototype = {
707 // extend the bounds to contain the given point
708 extend: function (point) { // (Point)
709 point = L.point(point);
711 if (!this.min && !this.max) {
712 this.min = point.clone();
713 this.max = point.clone();
715 this.min.x = Math.min(point.x, this.min.x);
716 this.max.x = Math.max(point.x, this.max.x);
717 this.min.y = Math.min(point.y, this.min.y);
718 this.max.y = Math.max(point.y, this.max.y);
723 getCenter: function (round) { // (Boolean) -> Point
725 (this.min.x + this.max.x) / 2,
726 (this.min.y + this.max.y) / 2, round);
729 getBottomLeft: function () { // -> Point
730 return new L.Point(this.min.x, this.max.y);
733 getTopRight: function () { // -> Point
734 return new L.Point(this.max.x, this.min.y);
737 getSize: function () {
738 return this.max.subtract(this.min);
741 contains: function (obj) { // (Bounds) or (Point) -> Boolean
744 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
750 if (obj instanceof L.Bounds) {
757 return (min.x >= this.min.x) &&
758 (max.x <= this.max.x) &&
759 (min.y >= this.min.y) &&
760 (max.y <= this.max.y);
763 intersects: function (bounds) { // (Bounds) -> Boolean
764 bounds = L.bounds(bounds);
770 xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
771 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
773 return xIntersects && yIntersects;
776 isValid: function () {
777 return !!(this.min && this.max);
781 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
782 if (!a || a instanceof L.Bounds) {
785 return new L.Bounds(a, b);
790 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
793 L.Transformation = function (a, b, c, d) {
800 L.Transformation.prototype = {
801 transform: function (point, scale) { // (Point, Number) -> Point
802 return this._transform(point.clone(), scale);
805 // destructive transform (faster)
806 _transform: function (point, scale) {
808 point.x = scale * (this._a * point.x + this._b);
809 point.y = scale * (this._c * point.y + this._d);
813 untransform: function (point, scale) {
816 (point.x / scale - this._b) / this._a,
817 (point.y / scale - this._d) / this._c);
823 * L.DomUtil contains various utility functions for working with DOM.
828 return (typeof id === 'string' ? document.getElementById(id) : id);
831 getStyle: function (el, style) {
833 var value = el.style[style];
835 if (!value && el.currentStyle) {
836 value = el.currentStyle[style];
839 if ((!value || value === 'auto') && document.defaultView) {
840 var css = document.defaultView.getComputedStyle(el, null);
841 value = css ? css[style] : null;
844 return value === 'auto' ? null : value;
847 getViewportOffset: function (element) {
852 docBody = document.body,
853 docEl = document.documentElement,
857 top += el.offsetTop || 0;
858 left += el.offsetLeft || 0;
861 top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
862 left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
864 pos = L.DomUtil.getStyle(el, 'position');
866 if (el.offsetParent === docBody && pos === 'absolute') { break; }
868 if (pos === 'fixed') {
869 top += docBody.scrollTop || docEl.scrollTop || 0;
870 left += docBody.scrollLeft || docEl.scrollLeft || 0;
874 if (pos === 'relative' && !el.offsetLeft) {
875 var width = L.DomUtil.getStyle(el, 'width'),
876 maxWidth = L.DomUtil.getStyle(el, 'max-width'),
877 r = el.getBoundingClientRect();
879 if (width !== 'none' || maxWidth !== 'none') {
880 left += r.left + el.clientLeft;
883 //calculate full y offset since we're breaking out of the loop
884 top += r.top + (docBody.scrollTop || docEl.scrollTop || 0);
889 el = el.offsetParent;
896 if (el === docBody) { break; }
898 top -= el.scrollTop || 0;
899 left -= el.scrollLeft || 0;
904 return new L.Point(left, top);
907 documentIsLtr: function () {
908 if (!L.DomUtil._docIsLtrCached) {
909 L.DomUtil._docIsLtrCached = true;
910 L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
912 return L.DomUtil._docIsLtr;
915 create: function (tagName, className, container) {
917 var el = document.createElement(tagName);
918 el.className = className;
921 container.appendChild(el);
927 hasClass: function (el, name) {
928 if (el.classList !== undefined) {
929 return el.classList.contains(name);
931 var className = L.DomUtil._getClass(el);
932 return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
935 addClass: function (el, name) {
936 if (el.classList !== undefined) {
937 var classes = L.Util.splitWords(name);
938 for (var i = 0, len = classes.length; i < len; i++) {
939 el.classList.add(classes[i]);
941 } else if (!L.DomUtil.hasClass(el, name)) {
942 var className = L.DomUtil._getClass(el);
943 L.DomUtil._setClass(el, (className ? className + ' ' : '') + name);
947 removeClass: function (el, name) {
948 if (el.classList !== undefined) {
949 el.classList.remove(name);
951 L.DomUtil._setClass(el, L.Util.trim((' ' + L.DomUtil._getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
955 _setClass: function (el, name) {
956 if (el.className.baseVal === undefined) {
959 // in case of SVG element
960 el.className.baseVal = name;
964 _getClass: function (el) {
965 return el.className.baseVal === undefined ? el.className : el.className.baseVal;
968 setOpacity: function (el, value) {
970 if ('opacity' in el.style) {
971 el.style.opacity = value;
973 } else if ('filter' in el.style) {
976 filterName = 'DXImageTransform.Microsoft.Alpha';
978 // filters collection throws an error if we try to retrieve a filter that doesn't exist
980 filter = el.filters.item(filterName);
982 // don't set opacity to 1 if we haven't already set an opacity,
983 // it isn't needed and breaks transparent pngs.
984 if (value === 1) { return; }
987 value = Math.round(value * 100);
990 filter.Enabled = (value !== 100);
991 filter.Opacity = value;
993 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
998 testProp: function (props) {
1000 var style = document.documentElement.style;
1002 for (var i = 0; i < props.length; i++) {
1003 if (props[i] in style) {
1010 getTranslateString: function (point) {
1011 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
1012 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
1013 // (same speed either way), Opera 12 doesn't support translate3d
1015 var is3d = L.Browser.webkit3d,
1016 open = 'translate' + (is3d ? '3d' : '') + '(',
1017 close = (is3d ? ',0' : '') + ')';
1019 return open + point.x + 'px,' + point.y + 'px' + close;
1022 getScaleString: function (scale, origin) {
1024 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
1025 scaleStr = ' scale(' + scale + ') ';
1027 return preTranslateStr + scaleStr;
1030 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
1032 // jshint camelcase: false
1033 el._leaflet_pos = point;
1035 if (!disable3D && L.Browser.any3d) {
1036 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
1038 el.style.left = point.x + 'px';
1039 el.style.top = point.y + 'px';
1043 getPosition: function (el) {
1044 // this method is only used for elements previously positioned using setPosition,
1045 // so it's safe to cache the position for performance
1047 // jshint camelcase: false
1048 return el._leaflet_pos;
1053 // prefix style property names
1055 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
1056 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
1058 // webkitTransition comes first because some browser versions that drop vendor prefix don't do
1059 // the same for the transitionend event, in particular the Android 4.1 stock browser
1061 L.DomUtil.TRANSITION = L.DomUtil.testProp(
1062 ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
1064 L.DomUtil.TRANSITION_END =
1065 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
1066 L.DomUtil.TRANSITION + 'End' : 'transitionend';
1069 if ('onselectstart' in document) {
1070 L.extend(L.DomUtil, {
1071 disableTextSelection: function () {
1072 L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
1075 enableTextSelection: function () {
1076 L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
1080 var userSelectProperty = L.DomUtil.testProp(
1081 ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
1083 L.extend(L.DomUtil, {
1084 disableTextSelection: function () {
1085 if (userSelectProperty) {
1086 var style = document.documentElement.style;
1087 this._userSelect = style[userSelectProperty];
1088 style[userSelectProperty] = 'none';
1092 enableTextSelection: function () {
1093 if (userSelectProperty) {
1094 document.documentElement.style[userSelectProperty] = this._userSelect;
1095 delete this._userSelect;
1101 L.extend(L.DomUtil, {
1102 disableImageDrag: function () {
1103 L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
1106 enableImageDrag: function () {
1107 L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
1114 * L.LatLng represents a geographical point with latitude and longitude coordinates.
1117 L.LatLng = function (lat, lng, alt) { // (Number, Number, Number)
1118 lat = parseFloat(lat);
1119 lng = parseFloat(lng);
1121 if (isNaN(lat) || isNaN(lng)) {
1122 throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
1128 if (alt !== undefined) {
1129 this.alt = parseFloat(alt);
1133 L.extend(L.LatLng, {
1134 DEG_TO_RAD: Math.PI / 180,
1135 RAD_TO_DEG: 180 / Math.PI,
1136 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
1139 L.LatLng.prototype = {
1140 equals: function (obj) { // (LatLng) -> Boolean
1141 if (!obj) { return false; }
1143 obj = L.latLng(obj);
1145 var margin = Math.max(
1146 Math.abs(this.lat - obj.lat),
1147 Math.abs(this.lng - obj.lng));
1149 return margin <= L.LatLng.MAX_MARGIN;
1152 toString: function (precision) { // (Number) -> String
1154 L.Util.formatNum(this.lat, precision) + ', ' +
1155 L.Util.formatNum(this.lng, precision) + ')';
1158 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1159 // TODO move to projection code, LatLng shouldn't know about Earth
1160 distanceTo: function (other) { // (LatLng) -> Number
1161 other = L.latLng(other);
1163 var R = 6378137, // earth radius in meters
1164 d2r = L.LatLng.DEG_TO_RAD,
1165 dLat = (other.lat - this.lat) * d2r,
1166 dLon = (other.lng - this.lng) * d2r,
1167 lat1 = this.lat * d2r,
1168 lat2 = other.lat * d2r,
1169 sin1 = Math.sin(dLat / 2),
1170 sin2 = Math.sin(dLon / 2);
1172 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1174 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1177 wrap: function (a, b) { // (Number, Number) -> LatLng
1183 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1185 return new L.LatLng(this.lat, lng);
1189 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1190 if (a instanceof L.LatLng) {
1193 if (L.Util.isArray(a)) {
1194 if (typeof a[0] === 'number' || typeof a[0] === 'string') {
1195 return new L.LatLng(a[0], a[1], a[2]);
1200 if (a === undefined || a === null) {
1203 if (typeof a === 'object' && 'lat' in a) {
1204 return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
1206 if (b === undefined) {
1209 return new L.LatLng(a, b);
1215 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1218 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1219 if (!southWest) { return; }
1221 var latlngs = northEast ? [southWest, northEast] : southWest;
1223 for (var i = 0, len = latlngs.length; i < len; i++) {
1224 this.extend(latlngs[i]);
1228 L.LatLngBounds.prototype = {
1229 // extend the bounds to contain the given point or bounds
1230 extend: function (obj) { // (LatLng) or (LatLngBounds)
1231 if (!obj) { return this; }
1233 var latLng = L.latLng(obj);
1234 if (latLng !== null) {
1237 obj = L.latLngBounds(obj);
1240 if (obj instanceof L.LatLng) {
1241 if (!this._southWest && !this._northEast) {
1242 this._southWest = new L.LatLng(obj.lat, obj.lng);
1243 this._northEast = new L.LatLng(obj.lat, obj.lng);
1245 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1246 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1248 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1249 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1251 } else if (obj instanceof L.LatLngBounds) {
1252 this.extend(obj._southWest);
1253 this.extend(obj._northEast);
1258 // extend the bounds by a percentage
1259 pad: function (bufferRatio) { // (Number) -> LatLngBounds
1260 var sw = this._southWest,
1261 ne = this._northEast,
1262 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1263 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1265 return new L.LatLngBounds(
1266 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1267 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1270 getCenter: function () { // -> LatLng
1271 return new L.LatLng(
1272 (this._southWest.lat + this._northEast.lat) / 2,
1273 (this._southWest.lng + this._northEast.lng) / 2);
1276 getSouthWest: function () {
1277 return this._southWest;
1280 getNorthEast: function () {
1281 return this._northEast;
1284 getNorthWest: function () {
1285 return new L.LatLng(this.getNorth(), this.getWest());
1288 getSouthEast: function () {
1289 return new L.LatLng(this.getSouth(), this.getEast());
1292 getWest: function () {
1293 return this._southWest.lng;
1296 getSouth: function () {
1297 return this._southWest.lat;
1300 getEast: function () {
1301 return this._northEast.lng;
1304 getNorth: function () {
1305 return this._northEast.lat;
1308 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1309 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1310 obj = L.latLng(obj);
1312 obj = L.latLngBounds(obj);
1315 var sw = this._southWest,
1316 ne = this._northEast,
1319 if (obj instanceof L.LatLngBounds) {
1320 sw2 = obj.getSouthWest();
1321 ne2 = obj.getNorthEast();
1326 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1327 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1330 intersects: function (bounds) { // (LatLngBounds)
1331 bounds = L.latLngBounds(bounds);
1333 var sw = this._southWest,
1334 ne = this._northEast,
1335 sw2 = bounds.getSouthWest(),
1336 ne2 = bounds.getNorthEast(),
1338 latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1339 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1341 return latIntersects && lngIntersects;
1344 toBBoxString: function () {
1345 return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
1348 equals: function (bounds) { // (LatLngBounds)
1349 if (!bounds) { return false; }
1351 bounds = L.latLngBounds(bounds);
1353 return this._southWest.equals(bounds.getSouthWest()) &&
1354 this._northEast.equals(bounds.getNorthEast());
1357 isValid: function () {
1358 return !!(this._southWest && this._northEast);
1362 //TODO International date line?
1364 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1365 if (!a || a instanceof L.LatLngBounds) {
1368 return new L.LatLngBounds(a, b);
1373 * L.Projection contains various geographical projections used by CRS classes.
1380 * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1383 L.Projection.SphericalMercator = {
1384 MAX_LATITUDE: 85.0511287798,
1386 project: function (latlng) { // (LatLng) -> Point
1387 var d = L.LatLng.DEG_TO_RAD,
1388 max = this.MAX_LATITUDE,
1389 lat = Math.max(Math.min(max, latlng.lat), -max),
1393 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1395 return new L.Point(x, y);
1398 unproject: function (point) { // (Point, Boolean) -> LatLng
1399 var d = L.LatLng.RAD_TO_DEG,
1401 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1403 return new L.LatLng(lat, lng);
1409 * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1412 L.Projection.LonLat = {
1413 project: function (latlng) {
1414 return new L.Point(latlng.lng, latlng.lat);
1417 unproject: function (point) {
1418 return new L.LatLng(point.y, point.x);
1424 * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1428 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1429 var projectedPoint = this.projection.project(latlng),
1430 scale = this.scale(zoom);
1432 return this.transformation._transform(projectedPoint, scale);
1435 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1436 var scale = this.scale(zoom),
1437 untransformedPoint = this.transformation.untransform(point, scale);
1439 return this.projection.unproject(untransformedPoint);
1442 project: function (latlng) {
1443 return this.projection.project(latlng);
1446 scale: function (zoom) {
1447 return 256 * Math.pow(2, zoom);
1450 getSize: function (zoom) {
1451 var s = this.scale(zoom);
1452 return L.point(s, s);
1458 * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1461 L.CRS.Simple = L.extend({}, L.CRS, {
1462 projection: L.Projection.LonLat,
1463 transformation: new L.Transformation(1, 0, -1, 0),
1465 scale: function (zoom) {
1466 return Math.pow(2, zoom);
1472 * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1473 * and is used by Leaflet by default.
1476 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1479 projection: L.Projection.SphericalMercator,
1480 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1482 project: function (latlng) { // (LatLng) -> Point
1483 var projectedPoint = this.projection.project(latlng),
1484 earthRadius = 6378137;
1485 return projectedPoint.multiplyBy(earthRadius);
1489 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1495 * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1498 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1501 projection: L.Projection.LonLat,
1502 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1507 * L.Map is the central class of the API - it is used to create a map.
1510 L.Map = L.Class.extend({
1512 includes: L.Mixin.Events,
1515 crs: L.CRS.EPSG3857,
1523 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1525 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1528 initialize: function (id, options) { // (HTMLElement or String, Object)
1529 options = L.setOptions(this, options);
1532 this._initContainer(id);
1535 // hack for https://github.com/Leaflet/Leaflet/issues/1980
1536 this._onResize = L.bind(this._onResize, this);
1540 if (options.maxBounds) {
1541 this.setMaxBounds(options.maxBounds);
1544 if (options.center && options.zoom !== undefined) {
1545 this.setView(L.latLng(options.center), options.zoom, {reset: true});
1548 this._handlers = [];
1551 this._zoomBoundLayers = {};
1552 this._tileLayersNum = 0;
1554 this.callInitHooks();
1556 this._addLayers(options.layers);
1560 // public methods that modify map state
1562 // replaced by animation-powered implementation in Map.PanAnimation.js
1563 setView: function (center, zoom) {
1564 zoom = zoom === undefined ? this.getZoom() : zoom;
1565 this._resetView(L.latLng(center), this._limitZoom(zoom));
1569 setZoom: function (zoom, options) {
1570 if (!this._loaded) {
1571 this._zoom = this._limitZoom(zoom);
1574 return this.setView(this.getCenter(), zoom, {zoom: options});
1577 zoomIn: function (delta, options) {
1578 return this.setZoom(this._zoom + (delta || 1), options);
1581 zoomOut: function (delta, options) {
1582 return this.setZoom(this._zoom - (delta || 1), options);
1585 setZoomAround: function (latlng, zoom, options) {
1586 var scale = this.getZoomScale(zoom),
1587 viewHalf = this.getSize().divideBy(2),
1588 containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
1590 centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
1591 newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
1593 return this.setView(newCenter, zoom, {zoom: options});
1596 fitBounds: function (bounds, options) {
1598 options = options || {};
1599 bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
1601 var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
1602 paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
1604 zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
1606 zoom = (options.maxZoom) ? Math.min(options.maxZoom, zoom) : zoom;
1608 var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
1610 swPoint = this.project(bounds.getSouthWest(), zoom),
1611 nePoint = this.project(bounds.getNorthEast(), zoom),
1612 center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
1614 return this.setView(center, zoom, options);
1617 fitWorld: function (options) {
1618 return this.fitBounds([[-90, -180], [90, 180]], options);
1621 panTo: function (center, options) { // (LatLng)
1622 return this.setView(center, this._zoom, {pan: options});
1625 panBy: function (offset) { // (Point)
1626 // replaced with animated panBy in Map.PanAnimation.js
1627 this.fire('movestart');
1629 this._rawPanBy(L.point(offset));
1632 return this.fire('moveend');
1635 setMaxBounds: function (bounds) {
1636 bounds = L.latLngBounds(bounds);
1638 this.options.maxBounds = bounds;
1641 return this.off('moveend', this._panInsideMaxBounds, this);
1645 this._panInsideMaxBounds();
1648 return this.on('moveend', this._panInsideMaxBounds, this);
1651 panInsideBounds: function (bounds, options) {
1652 var center = this.getCenter(),
1653 newCenter = this._limitCenter(center, this._zoom, bounds);
1655 if (center.equals(newCenter)) { return this; }
1657 return this.panTo(newCenter, options);
1660 addLayer: function (layer) {
1661 // TODO method is too big, refactor
1663 var id = L.stamp(layer);
1665 if (this._layers[id]) { return this; }
1667 this._layers[id] = layer;
1669 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1670 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1671 this._zoomBoundLayers[id] = layer;
1672 this._updateZoomLevels();
1675 // TODO looks ugly, refactor!!!
1676 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1677 this._tileLayersNum++;
1678 this._tileLayersToLoad++;
1679 layer.on('load', this._onTileLayerLoad, this);
1683 this._layerAdd(layer);
1689 removeLayer: function (layer) {
1690 var id = L.stamp(layer);
1692 if (!this._layers[id]) { return this; }
1695 layer.onRemove(this);
1698 delete this._layers[id];
1701 this.fire('layerremove', {layer: layer});
1704 if (this._zoomBoundLayers[id]) {
1705 delete this._zoomBoundLayers[id];
1706 this._updateZoomLevels();
1709 // TODO looks ugly, refactor
1710 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1711 this._tileLayersNum--;
1712 this._tileLayersToLoad--;
1713 layer.off('load', this._onTileLayerLoad, this);
1719 hasLayer: function (layer) {
1720 if (!layer) { return false; }
1722 return (L.stamp(layer) in this._layers);
1725 eachLayer: function (method, context) {
1726 for (var i in this._layers) {
1727 method.call(context, this._layers[i]);
1732 invalidateSize: function (options) {
1733 if (!this._loaded) { return this; }
1735 options = L.extend({
1738 }, options === true ? {animate: true} : options);
1740 var oldSize = this.getSize();
1741 this._sizeChanged = true;
1742 this._initialCenter = null;
1744 var newSize = this.getSize(),
1745 oldCenter = oldSize.divideBy(2).round(),
1746 newCenter = newSize.divideBy(2).round(),
1747 offset = oldCenter.subtract(newCenter);
1749 if (!offset.x && !offset.y) { return this; }
1751 if (options.animate && options.pan) {
1756 this._rawPanBy(offset);
1761 if (options.debounceMoveend) {
1762 clearTimeout(this._sizeTimer);
1763 this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1765 this.fire('moveend');
1769 return this.fire('resize', {
1775 // TODO handler.addTo
1776 addHandler: function (name, HandlerClass) {
1777 if (!HandlerClass) { return this; }
1779 var handler = this[name] = new HandlerClass(this);
1781 this._handlers.push(handler);
1783 if (this.options[name]) {
1790 remove: function () {
1792 this.fire('unload');
1795 this._initEvents('off');
1798 // throws error in IE6-8
1799 delete this._container._leaflet;
1801 this._container._leaflet = undefined;
1805 if (this._clearControlPos) {
1806 this._clearControlPos();
1809 this._clearHandlers();
1815 // public methods for getting map state
1817 getCenter: function () { // (Boolean) -> LatLng
1818 this._checkIfLoaded();
1820 if (this._initialCenter && !this._moved()) {
1821 return this._initialCenter;
1823 return this.layerPointToLatLng(this._getCenterLayerPoint());
1826 getZoom: function () {
1830 getBounds: function () {
1831 var bounds = this.getPixelBounds(),
1832 sw = this.unproject(bounds.getBottomLeft()),
1833 ne = this.unproject(bounds.getTopRight());
1835 return new L.LatLngBounds(sw, ne);
1838 getMinZoom: function () {
1839 return this.options.minZoom === undefined ?
1840 (this._layersMinZoom === undefined ? 0 : this._layersMinZoom) :
1841 this.options.minZoom;
1844 getMaxZoom: function () {
1845 return this.options.maxZoom === undefined ?
1846 (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
1847 this.options.maxZoom;
1850 getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1851 bounds = L.latLngBounds(bounds);
1853 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1854 maxZoom = this.getMaxZoom(),
1855 size = this.getSize(),
1857 nw = bounds.getNorthWest(),
1858 se = bounds.getSouthEast(),
1860 zoomNotFound = true,
1863 padding = L.point(padding || [0, 0]);
1867 boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1868 zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1870 } while (zoomNotFound && zoom <= maxZoom);
1872 if (zoomNotFound && inside) {
1876 return inside ? zoom : zoom - 1;
1879 getSize: function () {
1880 if (!this._size || this._sizeChanged) {
1881 this._size = new L.Point(
1882 this._container.clientWidth,
1883 this._container.clientHeight);
1885 this._sizeChanged = false;
1887 return this._size.clone();
1890 getPixelBounds: function () {
1891 var topLeftPoint = this._getTopLeftPoint();
1892 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1895 getPixelOrigin: function () {
1896 this._checkIfLoaded();
1897 return this._initialTopLeftPoint;
1900 getPanes: function () {
1904 getContainer: function () {
1905 return this._container;
1909 // TODO replace with universal implementation after refactoring projections
1911 getZoomScale: function (toZoom) {
1912 var crs = this.options.crs;
1913 return crs.scale(toZoom) / crs.scale(this._zoom);
1916 getScaleZoom: function (scale) {
1917 return this._zoom + (Math.log(scale) / Math.LN2);
1921 // conversion methods
1923 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1924 zoom = zoom === undefined ? this._zoom : zoom;
1925 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1928 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1929 zoom = zoom === undefined ? this._zoom : zoom;
1930 return this.options.crs.pointToLatLng(L.point(point), zoom);
1933 layerPointToLatLng: function (point) { // (Point)
1934 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1935 return this.unproject(projectedPoint);
1938 latLngToLayerPoint: function (latlng) { // (LatLng)
1939 var projectedPoint = this.project(L.latLng(latlng))._round();
1940 return projectedPoint._subtract(this.getPixelOrigin());
1943 containerPointToLayerPoint: function (point) { // (Point)
1944 return L.point(point).subtract(this._getMapPanePos());
1947 layerPointToContainerPoint: function (point) { // (Point)
1948 return L.point(point).add(this._getMapPanePos());
1951 containerPointToLatLng: function (point) {
1952 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1953 return this.layerPointToLatLng(layerPoint);
1956 latLngToContainerPoint: function (latlng) {
1957 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
1960 mouseEventToContainerPoint: function (e) { // (MouseEvent)
1961 return L.DomEvent.getMousePosition(e, this._container);
1964 mouseEventToLayerPoint: function (e) { // (MouseEvent)
1965 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
1968 mouseEventToLatLng: function (e) { // (MouseEvent)
1969 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
1973 // map initialization methods
1975 _initContainer: function (id) {
1976 var container = this._container = L.DomUtil.get(id);
1979 throw new Error('Map container not found.');
1980 } else if (container._leaflet) {
1981 throw new Error('Map container is already initialized.');
1984 container._leaflet = true;
1987 _initLayout: function () {
1988 var container = this._container;
1990 L.DomUtil.addClass(container, 'leaflet-container' +
1991 (L.Browser.touch ? ' leaflet-touch' : '') +
1992 (L.Browser.retina ? ' leaflet-retina' : '') +
1993 (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
1994 (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
1996 var position = L.DomUtil.getStyle(container, 'position');
1998 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
1999 container.style.position = 'relative';
2004 if (this._initControlPos) {
2005 this._initControlPos();
2009 _initPanes: function () {
2010 var panes = this._panes = {};
2012 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2014 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2015 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2016 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2017 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2018 panes.markerPane = this._createPane('leaflet-marker-pane');
2019 panes.popupPane = this._createPane('leaflet-popup-pane');
2021 var zoomHide = ' leaflet-zoom-hide';
2023 if (!this.options.markerZoomAnimation) {
2024 L.DomUtil.addClass(panes.markerPane, zoomHide);
2025 L.DomUtil.addClass(panes.shadowPane, zoomHide);
2026 L.DomUtil.addClass(panes.popupPane, zoomHide);
2030 _createPane: function (className, container) {
2031 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2034 _clearPanes: function () {
2035 this._container.removeChild(this._mapPane);
2038 _addLayers: function (layers) {
2039 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2041 for (var i = 0, len = layers.length; i < len; i++) {
2042 this.addLayer(layers[i]);
2047 // private methods that modify map state
2049 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2051 var zoomChanged = (this._zoom !== zoom);
2053 if (!afterZoomAnim) {
2054 this.fire('movestart');
2057 this.fire('zoomstart');
2062 this._initialCenter = center;
2064 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2066 if (!preserveMapOffset) {
2067 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2069 this._initialTopLeftPoint._add(this._getMapPanePos());
2072 this._tileLayersToLoad = this._tileLayersNum;
2074 var loading = !this._loaded;
2075 this._loaded = true;
2077 this.fire('viewreset', {hard: !preserveMapOffset});
2081 this.eachLayer(this._layerAdd, this);
2086 if (zoomChanged || afterZoomAnim) {
2087 this.fire('zoomend');
2090 this.fire('moveend', {hard: !preserveMapOffset});
2093 _rawPanBy: function (offset) {
2094 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2097 _getZoomSpan: function () {
2098 return this.getMaxZoom() - this.getMinZoom();
2101 _updateZoomLevels: function () {
2104 maxZoom = -Infinity,
2105 oldZoomSpan = this._getZoomSpan();
2107 for (i in this._zoomBoundLayers) {
2108 var layer = this._zoomBoundLayers[i];
2109 if (!isNaN(layer.options.minZoom)) {
2110 minZoom = Math.min(minZoom, layer.options.minZoom);
2112 if (!isNaN(layer.options.maxZoom)) {
2113 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2117 if (i === undefined) { // we have no tilelayers
2118 this._layersMaxZoom = this._layersMinZoom = undefined;
2120 this._layersMaxZoom = maxZoom;
2121 this._layersMinZoom = minZoom;
2124 if (oldZoomSpan !== this._getZoomSpan()) {
2125 this.fire('zoomlevelschange');
2129 _panInsideMaxBounds: function () {
2130 this.panInsideBounds(this.options.maxBounds);
2133 _checkIfLoaded: function () {
2134 if (!this._loaded) {
2135 throw new Error('Set map center and zoom first.');
2141 _initEvents: function (onOff) {
2142 if (!L.DomEvent) { return; }
2144 onOff = onOff || 'on';
2146 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2148 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2149 'mouseleave', 'mousemove', 'contextmenu'],
2152 for (i = 0, len = events.length; i < len; i++) {
2153 L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2156 if (this.options.trackResize) {
2157 L.DomEvent[onOff](window, 'resize', this._onResize, this);
2161 _onResize: function () {
2162 L.Util.cancelAnimFrame(this._resizeRequest);
2163 this._resizeRequest = L.Util.requestAnimFrame(
2164 function () { this.invalidateSize({debounceMoveend: true}); }, this, false, this._container);
2167 _onMouseClick: function (e) {
2168 if (!this._loaded || (!e._simulated &&
2169 ((this.dragging && this.dragging.moved()) ||
2170 (this.boxZoom && this.boxZoom.moved()))) ||
2171 L.DomEvent._skipped(e)) { return; }
2173 this.fire('preclick');
2174 this._fireMouseEvent(e);
2177 _fireMouseEvent: function (e) {
2178 if (!this._loaded || L.DomEvent._skipped(e)) { return; }
2182 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2184 if (!this.hasEventListeners(type)) { return; }
2186 if (type === 'contextmenu') {
2187 L.DomEvent.preventDefault(e);
2190 var containerPoint = this.mouseEventToContainerPoint(e),
2191 layerPoint = this.containerPointToLayerPoint(containerPoint),
2192 latlng = this.layerPointToLatLng(layerPoint);
2196 layerPoint: layerPoint,
2197 containerPoint: containerPoint,
2202 _onTileLayerLoad: function () {
2203 this._tileLayersToLoad--;
2204 if (this._tileLayersNum && !this._tileLayersToLoad) {
2205 this.fire('tilelayersload');
2209 _clearHandlers: function () {
2210 for (var i = 0, len = this._handlers.length; i < len; i++) {
2211 this._handlers[i].disable();
2215 whenReady: function (callback, context) {
2217 callback.call(context || this, this);
2219 this.on('load', callback, context);
2224 _layerAdd: function (layer) {
2226 this.fire('layeradd', {layer: layer});
2230 // private methods for getting map state
2232 _getMapPanePos: function () {
2233 return L.DomUtil.getPosition(this._mapPane);
2236 _moved: function () {
2237 var pos = this._getMapPanePos();
2238 return pos && !pos.equals([0, 0]);
2241 _getTopLeftPoint: function () {
2242 return this.getPixelOrigin().subtract(this._getMapPanePos());
2245 _getNewTopLeftPoint: function (center, zoom) {
2246 var viewHalf = this.getSize()._divideBy(2);
2247 // TODO round on display, not calculation to increase precision?
2248 return this.project(center, zoom)._subtract(viewHalf)._round();
2251 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2252 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2253 return this.project(latlng, newZoom)._subtract(topLeft);
2256 // layer point of the current center
2257 _getCenterLayerPoint: function () {
2258 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2261 // offset of the specified place to the current center in pixels
2262 _getCenterOffset: function (latlng) {
2263 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2266 // adjust center for view to get inside bounds
2267 _limitCenter: function (center, zoom, bounds) {
2269 if (!bounds) { return center; }
2271 var centerPoint = this.project(center, zoom),
2272 viewHalf = this.getSize().divideBy(2),
2273 viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
2274 offset = this._getBoundsOffset(viewBounds, bounds, zoom);
2276 return this.unproject(centerPoint.add(offset), zoom);
2279 // adjust offset for view to get inside bounds
2280 _limitOffset: function (offset, bounds) {
2281 if (!bounds) { return offset; }
2283 var viewBounds = this.getPixelBounds(),
2284 newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
2286 return offset.add(this._getBoundsOffset(newBounds, bounds));
2289 // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
2290 _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
2291 var nwOffset = this.project(maxBounds.getNorthWest(), zoom).subtract(pxBounds.min),
2292 seOffset = this.project(maxBounds.getSouthEast(), zoom).subtract(pxBounds.max),
2294 dx = this._rebound(nwOffset.x, -seOffset.x),
2295 dy = this._rebound(nwOffset.y, -seOffset.y);
2297 return new L.Point(dx, dy);
2300 _rebound: function (left, right) {
2301 return left + right > 0 ?
2302 Math.round(left - right) / 2 :
2303 Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
2306 _limitZoom: function (zoom) {
2307 var min = this.getMinZoom(),
2308 max = this.getMaxZoom();
2310 return Math.max(min, Math.min(max, zoom));
2314 L.map = function (id, options) {
2315 return new L.Map(id, options);
2320 * Mercator projection that takes into account that the Earth is not a perfect sphere.
2321 * Less popular than spherical mercator; used by projections like EPSG:3395.
2324 L.Projection.Mercator = {
2325 MAX_LATITUDE: 85.0840591556,
2327 R_MINOR: 6356752.314245179,
2330 project: function (latlng) { // (LatLng) -> Point
2331 var d = L.LatLng.DEG_TO_RAD,
2332 max = this.MAX_LATITUDE,
2333 lat = Math.max(Math.min(max, latlng.lat), -max),
2336 x = latlng.lng * d * r,
2339 eccent = Math.sqrt(1.0 - tmp * tmp),
2340 con = eccent * Math.sin(y);
2342 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2344 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2345 y = -r * Math.log(ts);
2347 return new L.Point(x, y);
2350 unproject: function (point) { // (Point, Boolean) -> LatLng
2351 var d = L.LatLng.RAD_TO_DEG,
2354 lng = point.x * d / r,
2356 eccent = Math.sqrt(1 - (tmp * tmp)),
2357 ts = Math.exp(- point.y / r),
2358 phi = (Math.PI / 2) - 2 * Math.atan(ts),
2365 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2366 con = eccent * Math.sin(phi);
2367 dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2368 Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2372 return new L.LatLng(phi * d, lng);
2378 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2381 projection: L.Projection.Mercator,
2383 transformation: (function () {
2384 var m = L.Projection.Mercator,
2386 scale = 0.5 / (Math.PI * r);
2388 return new L.Transformation(scale, 0.5, -scale, 0.5);
2394 * L.TileLayer is used for standard xyz-numbered tile layers.
2397 L.TileLayer = L.Class.extend({
2398 includes: L.Mixin.Events,
2410 maxNativeZoom: null,
2413 continuousWorld: false,
2416 detectRetina: false,
2420 unloadInvisibleTiles: L.Browser.mobile,
2421 updateWhenIdle: L.Browser.mobile
2424 initialize: function (url, options) {
2425 options = L.setOptions(this, options);
2427 // detecting retina displays, adjusting tileSize and zoom levels
2428 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2430 options.tileSize = Math.floor(options.tileSize / 2);
2431 options.zoomOffset++;
2433 if (options.minZoom > 0) {
2436 this.options.maxZoom--;
2439 if (options.bounds) {
2440 options.bounds = L.latLngBounds(options.bounds);
2445 var subdomains = this.options.subdomains;
2447 if (typeof subdomains === 'string') {
2448 this.options.subdomains = subdomains.split('');
2452 onAdd: function (map) {
2454 this._animated = map._zoomAnimated;
2456 // create a container div for tiles
2457 this._initContainer();
2461 'viewreset': this._reset,
2462 'moveend': this._update
2465 if (this._animated) {
2467 'zoomanim': this._animateZoom,
2468 'zoomend': this._endZoomAnim
2472 if (!this.options.updateWhenIdle) {
2473 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2474 map.on('move', this._limitedUpdate, this);
2481 addTo: function (map) {
2486 onRemove: function (map) {
2487 this._container.parentNode.removeChild(this._container);
2490 'viewreset': this._reset,
2491 'moveend': this._update
2494 if (this._animated) {
2496 'zoomanim': this._animateZoom,
2497 'zoomend': this._endZoomAnim
2501 if (!this.options.updateWhenIdle) {
2502 map.off('move', this._limitedUpdate, this);
2505 this._container = null;
2509 bringToFront: function () {
2510 var pane = this._map._panes.tilePane;
2512 if (this._container) {
2513 pane.appendChild(this._container);
2514 this._setAutoZIndex(pane, Math.max);
2520 bringToBack: function () {
2521 var pane = this._map._panes.tilePane;
2523 if (this._container) {
2524 pane.insertBefore(this._container, pane.firstChild);
2525 this._setAutoZIndex(pane, Math.min);
2531 getAttribution: function () {
2532 return this.options.attribution;
2535 getContainer: function () {
2536 return this._container;
2539 setOpacity: function (opacity) {
2540 this.options.opacity = opacity;
2543 this._updateOpacity();
2549 setZIndex: function (zIndex) {
2550 this.options.zIndex = zIndex;
2551 this._updateZIndex();
2556 setUrl: function (url, noRedraw) {
2566 redraw: function () {
2568 this._reset({hard: true});
2574 _updateZIndex: function () {
2575 if (this._container && this.options.zIndex !== undefined) {
2576 this._container.style.zIndex = this.options.zIndex;
2580 _setAutoZIndex: function (pane, compare) {
2582 var layers = pane.children,
2583 edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2586 for (i = 0, len = layers.length; i < len; i++) {
2588 if (layers[i] !== this._container) {
2589 zIndex = parseInt(layers[i].style.zIndex, 10);
2591 if (!isNaN(zIndex)) {
2592 edgeZIndex = compare(edgeZIndex, zIndex);
2597 this.options.zIndex = this._container.style.zIndex =
2598 (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2601 _updateOpacity: function () {
2603 tiles = this._tiles;
2605 if (L.Browser.ielt9) {
2607 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2610 L.DomUtil.setOpacity(this._container, this.options.opacity);
2614 _initContainer: function () {
2615 var tilePane = this._map._panes.tilePane;
2617 if (!this._container) {
2618 this._container = L.DomUtil.create('div', 'leaflet-layer');
2620 this._updateZIndex();
2622 if (this._animated) {
2623 var className = 'leaflet-tile-container';
2625 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2626 this._tileContainer = L.DomUtil.create('div', className, this._container);
2629 this._tileContainer = this._container;
2632 tilePane.appendChild(this._container);
2634 if (this.options.opacity < 1) {
2635 this._updateOpacity();
2640 _reset: function (e) {
2641 for (var key in this._tiles) {
2642 this.fire('tileunload', {tile: this._tiles[key]});
2646 this._tilesToLoad = 0;
2648 if (this.options.reuseTiles) {
2649 this._unusedTiles = [];
2652 this._tileContainer.innerHTML = '';
2654 if (this._animated && e && e.hard) {
2655 this._clearBgBuffer();
2658 this._initContainer();
2661 _getTileSize: function () {
2662 var map = this._map,
2663 zoom = map.getZoom() + this.options.zoomOffset,
2664 zoomN = this.options.maxNativeZoom,
2665 tileSize = this.options.tileSize;
2667 if (zoomN && zoom > zoomN) {
2668 tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize);
2674 _update: function () {
2676 if (!this._map) { return; }
2678 var map = this._map,
2679 bounds = map.getPixelBounds(),
2680 zoom = map.getZoom(),
2681 tileSize = this._getTileSize();
2683 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2687 var tileBounds = L.bounds(
2688 bounds.min.divideBy(tileSize)._floor(),
2689 bounds.max.divideBy(tileSize)._floor());
2691 this._addTilesFromCenterOut(tileBounds);
2693 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2694 this._removeOtherTiles(tileBounds);
2698 _addTilesFromCenterOut: function (bounds) {
2700 center = bounds.getCenter();
2704 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2705 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2706 point = new L.Point(i, j);
2708 if (this._tileShouldBeLoaded(point)) {
2714 var tilesToLoad = queue.length;
2716 if (tilesToLoad === 0) { return; }
2718 // load tiles in order of their distance to center
2719 queue.sort(function (a, b) {
2720 return a.distanceTo(center) - b.distanceTo(center);
2723 var fragment = document.createDocumentFragment();
2725 // if its the first batch of tiles to load
2726 if (!this._tilesToLoad) {
2727 this.fire('loading');
2730 this._tilesToLoad += tilesToLoad;
2732 for (i = 0; i < tilesToLoad; i++) {
2733 this._addTile(queue[i], fragment);
2736 this._tileContainer.appendChild(fragment);
2739 _tileShouldBeLoaded: function (tilePoint) {
2740 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2741 return false; // already loaded
2744 var options = this.options;
2746 if (!options.continuousWorld) {
2747 var limit = this._getWrapTileNum();
2749 // don't load if exceeds world bounds
2750 if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) ||
2751 tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; }
2754 if (options.bounds) {
2755 var tileSize = this._getTileSize(),
2756 nwPoint = tilePoint.multiplyBy(tileSize),
2757 sePoint = nwPoint.add([tileSize, tileSize]),
2758 nw = this._map.unproject(nwPoint),
2759 se = this._map.unproject(sePoint);
2761 // TODO temporary hack, will be removed after refactoring projections
2762 // https://github.com/Leaflet/Leaflet/issues/1618
2763 if (!options.continuousWorld && !options.noWrap) {
2768 if (!options.bounds.intersects([nw, se])) { return false; }
2774 _removeOtherTiles: function (bounds) {
2775 var kArr, x, y, key;
2777 for (key in this._tiles) {
2778 kArr = key.split(':');
2779 x = parseInt(kArr[0], 10);
2780 y = parseInt(kArr[1], 10);
2782 // remove tile if it's out of bounds
2783 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2784 this._removeTile(key);
2789 _removeTile: function (key) {
2790 var tile = this._tiles[key];
2792 this.fire('tileunload', {tile: tile, url: tile.src});
2794 if (this.options.reuseTiles) {
2795 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2796 this._unusedTiles.push(tile);
2798 } else if (tile.parentNode === this._tileContainer) {
2799 this._tileContainer.removeChild(tile);
2802 // for https://github.com/CloudMade/Leaflet/issues/137
2803 if (!L.Browser.android) {
2805 tile.src = L.Util.emptyImageUrl;
2808 delete this._tiles[key];
2811 _addTile: function (tilePoint, container) {
2812 var tilePos = this._getTilePos(tilePoint);
2814 // get unused tile - or create a new tile
2815 var tile = this._getTile();
2818 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2819 Android 4 browser has display issues with top/left and requires transform instead
2820 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2822 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome);
2824 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2826 this._loadTile(tile, tilePoint);
2828 if (tile.parentNode !== this._tileContainer) {
2829 container.appendChild(tile);
2833 _getZoomForUrl: function () {
2835 var options = this.options,
2836 zoom = this._map.getZoom();
2838 if (options.zoomReverse) {
2839 zoom = options.maxZoom - zoom;
2842 zoom += options.zoomOffset;
2844 return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom;
2847 _getTilePos: function (tilePoint) {
2848 var origin = this._map.getPixelOrigin(),
2849 tileSize = this._getTileSize();
2851 return tilePoint.multiplyBy(tileSize).subtract(origin);
2854 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2856 getTileUrl: function (tilePoint) {
2857 return L.Util.template(this._url, L.extend({
2858 s: this._getSubdomain(tilePoint),
2865 _getWrapTileNum: function () {
2866 var crs = this._map.options.crs,
2867 size = crs.getSize(this._map.getZoom());
2868 return size.divideBy(this._getTileSize())._floor();
2871 _adjustTilePoint: function (tilePoint) {
2873 var limit = this._getWrapTileNum();
2875 // wrap tile coordinates
2876 if (!this.options.continuousWorld && !this.options.noWrap) {
2877 tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x;
2880 if (this.options.tms) {
2881 tilePoint.y = limit.y - tilePoint.y - 1;
2884 tilePoint.z = this._getZoomForUrl();
2887 _getSubdomain: function (tilePoint) {
2888 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2889 return this.options.subdomains[index];
2892 _getTile: function () {
2893 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2894 var tile = this._unusedTiles.pop();
2895 this._resetTile(tile);
2898 return this._createTile();
2901 // Override if data stored on a tile needs to be cleaned up before reuse
2902 _resetTile: function (/*tile*/) {},
2904 _createTile: function () {
2905 var tile = L.DomUtil.create('img', 'leaflet-tile');
2906 tile.style.width = tile.style.height = this._getTileSize() + 'px';
2907 tile.galleryimg = 'no';
2909 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2911 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2912 L.DomUtil.setOpacity(tile, this.options.opacity);
2914 // without this hack, tiles disappear after zoom on Chrome for Android
2915 // https://github.com/Leaflet/Leaflet/issues/2078
2916 if (L.Browser.mobileWebkit3d) {
2917 tile.style.WebkitBackfaceVisibility = 'hidden';
2922 _loadTile: function (tile, tilePoint) {
2924 tile.onload = this._tileOnLoad;
2925 tile.onerror = this._tileOnError;
2927 this._adjustTilePoint(tilePoint);
2928 tile.src = this.getTileUrl(tilePoint);
2930 this.fire('tileloadstart', {
2936 _tileLoaded: function () {
2937 this._tilesToLoad--;
2939 if (this._animated) {
2940 L.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated');
2943 if (!this._tilesToLoad) {
2946 if (this._animated) {
2947 // clear scaled tiles after all new tiles are loaded (for performance)
2948 clearTimeout(this._clearBgBufferTimer);
2949 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2954 _tileOnLoad: function () {
2955 var layer = this._layer;
2957 //Only if we are loading an actual image
2958 if (this.src !== L.Util.emptyImageUrl) {
2959 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
2961 layer.fire('tileload', {
2967 layer._tileLoaded();
2970 _tileOnError: function () {
2971 var layer = this._layer;
2973 layer.fire('tileerror', {
2978 var newUrl = layer.options.errorTileUrl;
2983 layer._tileLoaded();
2987 L.tileLayer = function (url, options) {
2988 return new L.TileLayer(url, options);
2993 * L.TileLayer.WMS is used for putting WMS tile layers on the map.
2996 L.TileLayer.WMS = L.TileLayer.extend({
3004 format: 'image/jpeg',
3008 initialize: function (url, options) { // (String, Object)
3012 var wmsParams = L.extend({}, this.defaultWmsParams),
3013 tileSize = options.tileSize || this.options.tileSize;
3015 if (options.detectRetina && L.Browser.retina) {
3016 wmsParams.width = wmsParams.height = tileSize * 2;
3018 wmsParams.width = wmsParams.height = tileSize;
3021 for (var i in options) {
3022 // all keys that are not TileLayer options go to WMS params
3023 if (!this.options.hasOwnProperty(i) && i !== 'crs') {
3024 wmsParams[i] = options[i];
3028 this.wmsParams = wmsParams;
3030 L.setOptions(this, options);
3033 onAdd: function (map) {
3035 this._crs = this.options.crs || map.options.crs;
3037 this._wmsVersion = parseFloat(this.wmsParams.version);
3039 var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
3040 this.wmsParams[projectionKey] = this._crs.code;
3042 L.TileLayer.prototype.onAdd.call(this, map);
3045 getTileUrl: function (tilePoint) { // (Point, Number) -> String
3047 var map = this._map,
3048 tileSize = this.options.tileSize,
3050 nwPoint = tilePoint.multiplyBy(tileSize),
3051 sePoint = nwPoint.add([tileSize, tileSize]),
3053 nw = this._crs.project(map.unproject(nwPoint, tilePoint.z)),
3054 se = this._crs.project(map.unproject(sePoint, tilePoint.z)),
3055 bbox = this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
3056 [se.y, nw.x, nw.y, se.x].join(',') :
3057 [nw.x, se.y, se.x, nw.y].join(','),
3059 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
3061 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
3064 setParams: function (params, noRedraw) {
3066 L.extend(this.wmsParams, params);
3076 L.tileLayer.wms = function (url, options) {
3077 return new L.TileLayer.WMS(url, options);
3082 * L.TileLayer.Canvas is a class that you can use as a base for creating
3083 * dynamically drawn Canvas-based tile layers.
3086 L.TileLayer.Canvas = L.TileLayer.extend({
3091 initialize: function (options) {
3092 L.setOptions(this, options);
3095 redraw: function () {
3097 this._reset({hard: true});
3101 for (var i in this._tiles) {
3102 this._redrawTile(this._tiles[i]);
3107 _redrawTile: function (tile) {
3108 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3111 _createTile: function () {
3112 var tile = L.DomUtil.create('canvas', 'leaflet-tile');
3113 tile.width = tile.height = this.options.tileSize;
3114 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3118 _loadTile: function (tile, tilePoint) {
3120 tile._tilePoint = tilePoint;
3122 this._redrawTile(tile);
3124 if (!this.options.async) {
3125 this.tileDrawn(tile);
3129 drawTile: function (/*tile, tilePoint*/) {
3130 // override with rendering code
3133 tileDrawn: function (tile) {
3134 this._tileOnLoad.call(tile);
3139 L.tileLayer.canvas = function (options) {
3140 return new L.TileLayer.Canvas(options);
3145 * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3148 L.ImageOverlay = L.Class.extend({
3149 includes: L.Mixin.Events,
3155 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3157 this._bounds = L.latLngBounds(bounds);
3159 L.setOptions(this, options);
3162 onAdd: function (map) {
3169 map._panes.overlayPane.appendChild(this._image);
3171 map.on('viewreset', this._reset, this);
3173 if (map.options.zoomAnimation && L.Browser.any3d) {
3174 map.on('zoomanim', this._animateZoom, this);
3180 onRemove: function (map) {
3181 map.getPanes().overlayPane.removeChild(this._image);
3183 map.off('viewreset', this._reset, this);
3185 if (map.options.zoomAnimation) {
3186 map.off('zoomanim', this._animateZoom, this);
3190 addTo: function (map) {
3195 setOpacity: function (opacity) {
3196 this.options.opacity = opacity;
3197 this._updateOpacity();
3201 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3202 bringToFront: function () {
3204 this._map._panes.overlayPane.appendChild(this._image);
3209 bringToBack: function () {
3210 var pane = this._map._panes.overlayPane;
3212 pane.insertBefore(this._image, pane.firstChild);
3217 setUrl: function (url) {
3219 this._image.src = this._url;
3222 getAttribution: function () {
3223 return this.options.attribution;
3226 _initImage: function () {
3227 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3229 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3230 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3232 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3235 this._updateOpacity();
3237 //TODO createImage util method to remove duplication
3238 L.extend(this._image, {
3240 onselectstart: L.Util.falseFn,
3241 onmousemove: L.Util.falseFn,
3242 onload: L.bind(this._onImageLoad, this),
3247 _animateZoom: function (e) {
3248 var map = this._map,
3249 image = this._image,
3250 scale = map.getZoomScale(e.zoom),
3251 nw = this._bounds.getNorthWest(),
3252 se = this._bounds.getSouthEast(),
3254 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3255 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3256 origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3258 image.style[L.DomUtil.TRANSFORM] =
3259 L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3262 _reset: function () {
3263 var image = this._image,
3264 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3265 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3267 L.DomUtil.setPosition(image, topLeft);
3269 image.style.width = size.x + 'px';
3270 image.style.height = size.y + 'px';
3273 _onImageLoad: function () {
3277 _updateOpacity: function () {
3278 L.DomUtil.setOpacity(this._image, this.options.opacity);
3282 L.imageOverlay = function (url, bounds, options) {
3283 return new L.ImageOverlay(url, bounds, options);
3288 * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3291 L.Icon = L.Class.extend({
3294 iconUrl: (String) (required)
3295 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3296 iconSize: (Point) (can be set through CSS)
3297 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3298 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3299 shadowUrl: (String) (no shadow by default)
3300 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3302 shadowAnchor: (Point)
3307 initialize: function (options) {
3308 L.setOptions(this, options);
3311 createIcon: function (oldIcon) {
3312 return this._createIcon('icon', oldIcon);
3315 createShadow: function (oldIcon) {
3316 return this._createIcon('shadow', oldIcon);
3319 _createIcon: function (name, oldIcon) {
3320 var src = this._getIconUrl(name);
3323 if (name === 'icon') {
3324 throw new Error('iconUrl not set in Icon options (see the docs).');
3330 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3331 img = this._createImg(src);
3333 img = this._createImg(src, oldIcon);
3335 this._setIconStyles(img, name);
3340 _setIconStyles: function (img, name) {
3341 var options = this.options,
3342 size = L.point(options[name + 'Size']),
3345 if (name === 'shadow') {
3346 anchor = L.point(options.shadowAnchor || options.iconAnchor);
3348 anchor = L.point(options.iconAnchor);
3351 if (!anchor && size) {
3352 anchor = size.divideBy(2, true);
3355 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3358 img.style.marginLeft = (-anchor.x) + 'px';
3359 img.style.marginTop = (-anchor.y) + 'px';
3363 img.style.width = size.x + 'px';
3364 img.style.height = size.y + 'px';
3368 _createImg: function (src, el) {
3369 el = el || document.createElement('img');
3374 _getIconUrl: function (name) {
3375 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3376 return this.options[name + 'RetinaUrl'];
3378 return this.options[name + 'Url'];
3382 L.icon = function (options) {
3383 return new L.Icon(options);
3388 * L.Icon.Default is the blue marker icon used by default in Leaflet.
3391 L.Icon.Default = L.Icon.extend({
3395 iconAnchor: [12, 41],
3396 popupAnchor: [1, -34],
3398 shadowSize: [41, 41]
3401 _getIconUrl: function (name) {
3402 var key = name + 'Url';
3404 if (this.options[key]) {
3405 return this.options[key];
3408 if (L.Browser.retina && name === 'icon') {
3412 var path = L.Icon.Default.imagePath;
3415 throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3418 return path + '/marker-' + name + '.png';
3422 L.Icon.Default.imagePath = (function () {
3423 var scripts = document.getElementsByTagName('script'),
3424 leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3426 var i, len, src, matches, path;
3428 for (i = 0, len = scripts.length; i < len; i++) {
3429 src = scripts[i].src;
3430 matches = src.match(leafletRe);
3433 path = src.split(leafletRe)[0];
3434 return (path ? path + '/' : '') + 'images';
3441 * L.Marker is used to display clickable/draggable icons on the map.
3444 L.Marker = L.Class.extend({
3446 includes: L.Mixin.Events,
3449 icon: new L.Icon.Default(),
3461 initialize: function (latlng, options) {
3462 L.setOptions(this, options);
3463 this._latlng = L.latLng(latlng);
3466 onAdd: function (map) {
3469 map.on('viewreset', this.update, this);
3475 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3476 map.on('zoomanim', this._animateZoom, this);
3480 addTo: function (map) {
3485 onRemove: function (map) {
3486 if (this.dragging) {
3487 this.dragging.disable();
3491 this._removeShadow();
3493 this.fire('remove');
3496 'viewreset': this.update,
3497 'zoomanim': this._animateZoom
3503 getLatLng: function () {
3504 return this._latlng;
3507 setLatLng: function (latlng) {
3508 this._latlng = L.latLng(latlng);
3512 return this.fire('move', { latlng: this._latlng });
3515 setZIndexOffset: function (offset) {
3516 this.options.zIndexOffset = offset;
3522 setIcon: function (icon) {
3524 this.options.icon = icon;
3532 this.bindPopup(this._popup);
3538 update: function () {
3540 var pos = this._map.latLngToLayerPoint(this._latlng).round();
3541 L.Util.requestAnimFrame(function () {
3549 _initIcon: function () {
3550 var options = this.options,
3552 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3553 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3555 var icon = options.icon.createIcon(this._icon),
3558 // if we're not reusing the icon, remove the old one and init new one
3559 if (icon !== this._icon) {
3565 if (options.title) {
3566 icon.title = options.title;
3570 icon.alt = options.alt;
3574 L.DomUtil.addClass(icon, classToAdd);
3576 if (options.keyboard) {
3577 icon.tabIndex = '0';
3582 this._initInteraction();
3584 if (options.riseOnHover) {
3586 .on(icon, 'mouseover', this._bringToFront, this)
3587 .on(icon, 'mouseout', this._resetZIndex, this);
3590 var newShadow = options.icon.createShadow(this._shadow),
3593 if (newShadow !== this._shadow) {
3594 this._removeShadow();
3599 L.DomUtil.addClass(newShadow, classToAdd);
3601 this._shadow = newShadow;
3604 if (options.opacity < 1) {
3605 this._updateOpacity();
3609 var panes = this._map._panes;
3612 panes.markerPane.appendChild(this._icon);
3615 if (newShadow && addShadow) {
3616 panes.shadowPane.appendChild(this._shadow);
3620 _removeIcon: function () {
3621 if (this.options.riseOnHover) {
3623 .off(this._icon, 'mouseover', this._bringToFront)
3624 .off(this._icon, 'mouseout', this._resetZIndex);
3627 this._map._panes.markerPane.removeChild(this._icon);
3632 _removeShadow: function () {
3634 this._map._panes.shadowPane.removeChild(this._shadow);
3636 this._shadow = null;
3639 _setPos: function (pos) {
3640 L.DomUtil.setPosition(this._icon, pos);
3643 L.DomUtil.setPosition(this._shadow, pos);
3646 this._zIndex = pos.y + this.options.zIndexOffset;
3648 this._resetZIndex();
3651 _updateZIndex: function (offset) {
3652 this._icon.style.zIndex = this._zIndex + offset;
3655 _animateZoom: function (opt) {
3656 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
3661 _initInteraction: function () {
3663 if (!this.options.clickable) { return; }
3665 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3667 var icon = this._icon,
3668 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3670 L.DomUtil.addClass(icon, 'leaflet-clickable');
3671 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3672 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3674 for (var i = 0; i < events.length; i++) {
3675 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3678 if (L.Handler.MarkerDrag) {
3679 this.dragging = new L.Handler.MarkerDrag(this);
3681 if (this.options.draggable) {
3682 this.dragging.enable();
3687 _onMouseClick: function (e) {
3688 var wasDragged = this.dragging && this.dragging.moved();
3690 if (this.hasEventListeners(e.type) || wasDragged) {
3691 L.DomEvent.stopPropagation(e);
3694 if (wasDragged) { return; }
3696 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3700 latlng: this._latlng
3704 _onKeyPress: function (e) {
3705 if (e.keyCode === 13) {
3706 this.fire('click', {
3708 latlng: this._latlng
3713 _fireMouseEvent: function (e) {
3717 latlng: this._latlng
3720 // TODO proper custom event propagation
3721 // this line will always be called if marker is in a FeatureGroup
3722 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3723 L.DomEvent.preventDefault(e);
3725 if (e.type !== 'mousedown') {
3726 L.DomEvent.stopPropagation(e);
3728 L.DomEvent.preventDefault(e);
3732 setOpacity: function (opacity) {
3733 this.options.opacity = opacity;
3735 this._updateOpacity();
3741 _updateOpacity: function () {
3742 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3744 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3748 _bringToFront: function () {
3749 this._updateZIndex(this.options.riseOffset);
3752 _resetZIndex: function () {
3753 this._updateZIndex(0);
3757 L.marker = function (latlng, options) {
3758 return new L.Marker(latlng, options);
3763 * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3764 * to use with L.Marker.
3767 L.DivIcon = L.Icon.extend({
3769 iconSize: [12, 12], // also can be set through CSS
3772 popupAnchor: (Point)
3776 className: 'leaflet-div-icon',
3780 createIcon: function (oldIcon) {
3781 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3782 options = this.options;
3784 if (options.html !== false) {
3785 div.innerHTML = options.html;
3790 if (options.bgPos) {
3791 div.style.backgroundPosition =
3792 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3795 this._setIconStyles(div, 'icon');
3799 createShadow: function () {
3804 L.divIcon = function (options) {
3805 return new L.DivIcon(options);
3810 * L.Popup is used for displaying popups on the map.
3813 L.Map.mergeOptions({
3814 closePopupOnClick: true
3817 L.Popup = L.Class.extend({
3818 includes: L.Mixin.Events,
3827 autoPanPadding: [5, 5],
3828 // autoPanPaddingTopLeft: null,
3829 // autoPanPaddingBottomRight: null,
3835 initialize: function (options, source) {
3836 L.setOptions(this, options);
3838 this._source = source;
3839 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3840 this._isOpen = false;
3843 onAdd: function (map) {
3846 if (!this._container) {
3850 var animFade = map.options.fadeAnimation;
3853 L.DomUtil.setOpacity(this._container, 0);
3855 map._panes.popupPane.appendChild(this._container);
3857 map.on(this._getEvents(), this);
3862 L.DomUtil.setOpacity(this._container, 1);
3867 map.fire('popupopen', {popup: this});
3870 this._source.fire('popupopen', {popup: this});
3874 addTo: function (map) {
3879 openOn: function (map) {
3880 map.openPopup(this);
3884 onRemove: function (map) {
3885 map._panes.popupPane.removeChild(this._container);
3887 L.Util.falseFn(this._container.offsetWidth); // force reflow
3889 map.off(this._getEvents(), this);
3891 if (map.options.fadeAnimation) {
3892 L.DomUtil.setOpacity(this._container, 0);
3899 map.fire('popupclose', {popup: this});
3902 this._source.fire('popupclose', {popup: this});
3906 getLatLng: function () {
3907 return this._latlng;
3910 setLatLng: function (latlng) {
3911 this._latlng = L.latLng(latlng);
3913 this._updatePosition();
3919 getContent: function () {
3920 return this._content;
3923 setContent: function (content) {
3924 this._content = content;
3929 update: function () {
3930 if (!this._map) { return; }
3932 this._container.style.visibility = 'hidden';
3934 this._updateContent();
3935 this._updateLayout();
3936 this._updatePosition();
3938 this._container.style.visibility = '';
3943 _getEvents: function () {
3945 viewreset: this._updatePosition
3948 if (this._animated) {
3949 events.zoomanim = this._zoomAnimation;
3951 if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
3952 events.preclick = this._close;
3954 if (this.options.keepInView) {
3955 events.moveend = this._adjustPan;
3961 _close: function () {
3963 this._map.closePopup(this);
3967 _initLayout: function () {
3968 var prefix = 'leaflet-popup',
3969 containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
3970 (this._animated ? 'animated' : 'hide'),
3971 container = this._container = L.DomUtil.create('div', containerClass),
3974 if (this.options.closeButton) {
3975 closeButton = this._closeButton =
3976 L.DomUtil.create('a', prefix + '-close-button', container);
3977 closeButton.href = '#close';
3978 closeButton.innerHTML = '×';
3979 L.DomEvent.disableClickPropagation(closeButton);
3981 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
3984 var wrapper = this._wrapper =
3985 L.DomUtil.create('div', prefix + '-content-wrapper', container);
3986 L.DomEvent.disableClickPropagation(wrapper);
3988 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
3990 L.DomEvent.disableScrollPropagation(this._contentNode);
3991 L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
3993 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
3994 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
3997 _updateContent: function () {
3998 if (!this._content) { return; }
4000 if (typeof this._content === 'string') {
4001 this._contentNode.innerHTML = this._content;
4003 while (this._contentNode.hasChildNodes()) {
4004 this._contentNode.removeChild(this._contentNode.firstChild);
4006 this._contentNode.appendChild(this._content);
4008 this.fire('contentupdate');
4011 _updateLayout: function () {
4012 var container = this._contentNode,
4013 style = container.style;
4016 style.whiteSpace = 'nowrap';
4018 var width = container.offsetWidth;
4019 width = Math.min(width, this.options.maxWidth);
4020 width = Math.max(width, this.options.minWidth);
4022 style.width = (width + 1) + 'px';
4023 style.whiteSpace = '';
4027 var height = container.offsetHeight,
4028 maxHeight = this.options.maxHeight,
4029 scrolledClass = 'leaflet-popup-scrolled';
4031 if (maxHeight && height > maxHeight) {
4032 style.height = maxHeight + 'px';
4033 L.DomUtil.addClass(container, scrolledClass);
4035 L.DomUtil.removeClass(container, scrolledClass);
4038 this._containerWidth = this._container.offsetWidth;
4041 _updatePosition: function () {
4042 if (!this._map) { return; }
4044 var pos = this._map.latLngToLayerPoint(this._latlng),
4045 animated = this._animated,
4046 offset = L.point(this.options.offset);
4049 L.DomUtil.setPosition(this._container, pos);
4052 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
4053 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
4055 // bottom position the popup in case the height of the popup changes (images loading etc)
4056 this._container.style.bottom = this._containerBottom + 'px';
4057 this._container.style.left = this._containerLeft + 'px';
4060 _zoomAnimation: function (opt) {
4061 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
4063 L.DomUtil.setPosition(this._container, pos);
4066 _adjustPan: function () {
4067 if (!this.options.autoPan) { return; }
4069 var map = this._map,
4070 containerHeight = this._container.offsetHeight,
4071 containerWidth = this._containerWidth,
4073 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
4075 if (this._animated) {
4076 layerPos._add(L.DomUtil.getPosition(this._container));
4079 var containerPos = map.layerPointToContainerPoint(layerPos),
4080 padding = L.point(this.options.autoPanPadding),
4081 paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding),
4082 paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding),
4083 size = map.getSize(),
4087 if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
4088 dx = containerPos.x + containerWidth - size.x + paddingBR.x;
4090 if (containerPos.x - dx - paddingTL.x < 0) { // left
4091 dx = containerPos.x - paddingTL.x;
4093 if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
4094 dy = containerPos.y + containerHeight - size.y + paddingBR.y;
4096 if (containerPos.y - dy - paddingTL.y < 0) { // top
4097 dy = containerPos.y - paddingTL.y;
4102 .fire('autopanstart')
4107 _onCloseButtonClick: function (e) {
4113 L.popup = function (options, source) {
4114 return new L.Popup(options, source);
4119 openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
4122 if (!(popup instanceof L.Popup)) {
4123 var content = popup;
4125 popup = new L.Popup(options)
4127 .setContent(content);
4129 popup._isOpen = true;
4131 this._popup = popup;
4132 return this.addLayer(popup);
4135 closePopup: function (popup) {
4136 if (!popup || popup === this._popup) {
4137 popup = this._popup;
4141 this.removeLayer(popup);
4142 popup._isOpen = false;
4150 * Popup extension to L.Marker, adding popup-related methods.
4154 openPopup: function () {
4155 if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
4156 this._popup.setLatLng(this._latlng);
4157 this._map.openPopup(this._popup);
4163 closePopup: function () {
4165 this._popup._close();
4170 togglePopup: function () {
4172 if (this._popup._isOpen) {
4181 bindPopup: function (content, options) {
4182 var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
4184 anchor = anchor.add(L.Popup.prototype.options.offset);
4186 if (options && options.offset) {
4187 anchor = anchor.add(options.offset);
4190 options = L.extend({offset: anchor}, options);
4192 if (!this._popupHandlersAdded) {
4194 .on('click', this.togglePopup, this)
4195 .on('remove', this.closePopup, this)
4196 .on('move', this._movePopup, this);
4197 this._popupHandlersAdded = true;
4200 if (content instanceof L.Popup) {
4201 L.setOptions(content, options);
4202 this._popup = content;
4203 content._source = this;
4205 this._popup = new L.Popup(options, this)
4206 .setContent(content);
4212 setPopupContent: function (content) {
4214 this._popup.setContent(content);
4219 unbindPopup: function () {
4223 .off('click', this.togglePopup, this)
4224 .off('remove', this.closePopup, this)
4225 .off('move', this._movePopup, this);
4226 this._popupHandlersAdded = false;
4231 getPopup: function () {
4235 _movePopup: function (e) {
4236 this._popup.setLatLng(e.latlng);
4242 * L.LayerGroup is a class to combine several layers into one so that
4243 * you can manipulate the group (e.g. add/remove it) as one layer.
4246 L.LayerGroup = L.Class.extend({
4247 initialize: function (layers) {
4253 for (i = 0, len = layers.length; i < len; i++) {
4254 this.addLayer(layers[i]);
4259 addLayer: function (layer) {
4260 var id = this.getLayerId(layer);
4262 this._layers[id] = layer;
4265 this._map.addLayer(layer);
4271 removeLayer: function (layer) {
4272 var id = layer in this._layers ? layer : this.getLayerId(layer);
4274 if (this._map && this._layers[id]) {
4275 this._map.removeLayer(this._layers[id]);
4278 delete this._layers[id];
4283 hasLayer: function (layer) {
4284 if (!layer) { return false; }
4286 return (layer in this._layers || this.getLayerId(layer) in this._layers);
4289 clearLayers: function () {
4290 this.eachLayer(this.removeLayer, this);
4294 invoke: function (methodName) {
4295 var args = Array.prototype.slice.call(arguments, 1),
4298 for (i in this._layers) {
4299 layer = this._layers[i];
4301 if (layer[methodName]) {
4302 layer[methodName].apply(layer, args);
4309 onAdd: function (map) {
4311 this.eachLayer(map.addLayer, map);
4314 onRemove: function (map) {
4315 this.eachLayer(map.removeLayer, map);
4319 addTo: function (map) {
4324 eachLayer: function (method, context) {
4325 for (var i in this._layers) {
4326 method.call(context, this._layers[i]);
4331 getLayer: function (id) {
4332 return this._layers[id];
4335 getLayers: function () {
4338 for (var i in this._layers) {
4339 layers.push(this._layers[i]);
4344 setZIndex: function (zIndex) {
4345 return this.invoke('setZIndex', zIndex);
4348 getLayerId: function (layer) {
4349 return L.stamp(layer);
4353 L.layerGroup = function (layers) {
4354 return new L.LayerGroup(layers);
4359 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
4360 * shared between a group of interactive layers (like vectors or markers).
4363 L.FeatureGroup = L.LayerGroup.extend({
4364 includes: L.Mixin.Events,
4367 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
4370 addLayer: function (layer) {
4371 if (this.hasLayer(layer)) {
4375 if ('on' in layer) {
4376 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4379 L.LayerGroup.prototype.addLayer.call(this, layer);
4381 if (this._popupContent && layer.bindPopup) {
4382 layer.bindPopup(this._popupContent, this._popupOptions);
4385 return this.fire('layeradd', {layer: layer});
4388 removeLayer: function (layer) {
4389 if (!this.hasLayer(layer)) {
4392 if (layer in this._layers) {
4393 layer = this._layers[layer];
4396 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4398 L.LayerGroup.prototype.removeLayer.call(this, layer);
4400 if (this._popupContent) {
4401 this.invoke('unbindPopup');
4404 return this.fire('layerremove', {layer: layer});
4407 bindPopup: function (content, options) {
4408 this._popupContent = content;
4409 this._popupOptions = options;
4410 return this.invoke('bindPopup', content, options);
4413 openPopup: function (latlng) {
4414 // open popup on the first layer
4415 for (var id in this._layers) {
4416 this._layers[id].openPopup(latlng);
4422 setStyle: function (style) {
4423 return this.invoke('setStyle', style);
4426 bringToFront: function () {
4427 return this.invoke('bringToFront');
4430 bringToBack: function () {
4431 return this.invoke('bringToBack');
4434 getBounds: function () {
4435 var bounds = new L.LatLngBounds();
4437 this.eachLayer(function (layer) {
4438 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
4444 _propagateEvent: function (e) {
4449 this.fire(e.type, e);
4453 L.featureGroup = function (layers) {
4454 return new L.FeatureGroup(layers);
4459 * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
4462 L.Path = L.Class.extend({
4463 includes: [L.Mixin.Events],
4466 // how much to extend the clip area around the map view
4467 // (relative to its size, e.g. 0.5 is half the screen in each direction)
4468 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
4469 CLIP_PADDING: (function () {
4470 var max = L.Browser.mobile ? 1280 : 2000,
4471 target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
4472 return Math.max(0, Math.min(0.5, target));
4486 fillColor: null, //same as color by default
4492 initialize: function (options) {
4493 L.setOptions(this, options);
4496 onAdd: function (map) {
4499 if (!this._container) {
4500 this._initElements();
4504 this.projectLatlngs();
4507 if (this._container) {
4508 this._map._pathRoot.appendChild(this._container);
4514 'viewreset': this.projectLatlngs,
4515 'moveend': this._updatePath
4519 addTo: function (map) {
4524 onRemove: function (map) {
4525 map._pathRoot.removeChild(this._container);
4527 // Need to fire remove event before we set _map to null as the event hooks might need the object
4528 this.fire('remove');
4531 if (L.Browser.vml) {
4532 this._container = null;
4533 this._stroke = null;
4538 'viewreset': this.projectLatlngs,
4539 'moveend': this._updatePath
4543 projectLatlngs: function () {
4544 // do all projection stuff here
4547 setStyle: function (style) {
4548 L.setOptions(this, style);
4550 if (this._container) {
4551 this._updateStyle();
4557 redraw: function () {
4559 this.projectLatlngs();
4567 _updatePathViewport: function () {
4568 var p = L.Path.CLIP_PADDING,
4569 size = this.getSize(),
4570 panePos = L.DomUtil.getPosition(this._mapPane),
4571 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4572 max = min.add(size.multiplyBy(1 + p * 2)._round());
4574 this._pathViewport = new L.Bounds(min, max);
4580 * Extends L.Path with SVG-specific rendering code.
4583 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4585 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4587 L.Path = L.Path.extend({
4592 bringToFront: function () {
4593 var root = this._map._pathRoot,
4594 path = this._container;
4596 if (path && root.lastChild !== path) {
4597 root.appendChild(path);
4602 bringToBack: function () {
4603 var root = this._map._pathRoot,
4604 path = this._container,
4605 first = root.firstChild;
4607 if (path && first !== path) {
4608 root.insertBefore(path, first);
4613 getPathString: function () {
4614 // form path string here
4617 _createElement: function (name) {
4618 return document.createElementNS(L.Path.SVG_NS, name);
4621 _initElements: function () {
4622 this._map._initPathRoot();
4627 _initPath: function () {
4628 this._container = this._createElement('g');
4630 this._path = this._createElement('path');
4632 if (this.options.className) {
4633 L.DomUtil.addClass(this._path, this.options.className);
4636 this._container.appendChild(this._path);
4639 _initStyle: function () {
4640 if (this.options.stroke) {
4641 this._path.setAttribute('stroke-linejoin', 'round');
4642 this._path.setAttribute('stroke-linecap', 'round');
4644 if (this.options.fill) {
4645 this._path.setAttribute('fill-rule', 'evenodd');
4647 if (this.options.pointerEvents) {
4648 this._path.setAttribute('pointer-events', this.options.pointerEvents);
4650 if (!this.options.clickable && !this.options.pointerEvents) {
4651 this._path.setAttribute('pointer-events', 'none');
4653 this._updateStyle();
4656 _updateStyle: function () {
4657 if (this.options.stroke) {
4658 this._path.setAttribute('stroke', this.options.color);
4659 this._path.setAttribute('stroke-opacity', this.options.opacity);
4660 this._path.setAttribute('stroke-width', this.options.weight);
4661 if (this.options.dashArray) {
4662 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4664 this._path.removeAttribute('stroke-dasharray');
4666 if (this.options.lineCap) {
4667 this._path.setAttribute('stroke-linecap', this.options.lineCap);
4669 if (this.options.lineJoin) {
4670 this._path.setAttribute('stroke-linejoin', this.options.lineJoin);
4673 this._path.setAttribute('stroke', 'none');
4675 if (this.options.fill) {
4676 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4677 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4679 this._path.setAttribute('fill', 'none');
4683 _updatePath: function () {
4684 var str = this.getPathString();
4686 // fix webkit empty string parsing bug
4689 this._path.setAttribute('d', str);
4692 // TODO remove duplication with L.Map
4693 _initEvents: function () {
4694 if (this.options.clickable) {
4695 if (L.Browser.svg || !L.Browser.vml) {
4696 L.DomUtil.addClass(this._path, 'leaflet-clickable');
4699 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4701 var events = ['dblclick', 'mousedown', 'mouseover',
4702 'mouseout', 'mousemove', 'contextmenu'];
4703 for (var i = 0; i < events.length; i++) {
4704 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4709 _onMouseClick: function (e) {
4710 if (this._map.dragging && this._map.dragging.moved()) { return; }
4712 this._fireMouseEvent(e);
4715 _fireMouseEvent: function (e) {
4716 if (!this.hasEventListeners(e.type)) { return; }
4718 var map = this._map,
4719 containerPoint = map.mouseEventToContainerPoint(e),
4720 layerPoint = map.containerPointToLayerPoint(containerPoint),
4721 latlng = map.layerPointToLatLng(layerPoint);
4725 layerPoint: layerPoint,
4726 containerPoint: containerPoint,
4730 if (e.type === 'contextmenu') {
4731 L.DomEvent.preventDefault(e);
4733 if (e.type !== 'mousemove') {
4734 L.DomEvent.stopPropagation(e);
4740 _initPathRoot: function () {
4741 if (!this._pathRoot) {
4742 this._pathRoot = L.Path.prototype._createElement('svg');
4743 this._panes.overlayPane.appendChild(this._pathRoot);
4745 if (this.options.zoomAnimation && L.Browser.any3d) {
4746 L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-animated');
4749 'zoomanim': this._animatePathZoom,
4750 'zoomend': this._endPathZoom
4753 L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-hide');
4756 this.on('moveend', this._updateSvgViewport);
4757 this._updateSvgViewport();
4761 _animatePathZoom: function (e) {
4762 var scale = this.getZoomScale(e.zoom),
4763 offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4765 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4766 L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4768 this._pathZooming = true;
4771 _endPathZoom: function () {
4772 this._pathZooming = false;
4775 _updateSvgViewport: function () {
4777 if (this._pathZooming) {
4778 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4779 // When the zoom animation ends we will be updated again anyway
4780 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4784 this._updatePathViewport();
4786 var vp = this._pathViewport,
4789 width = max.x - min.x,
4790 height = max.y - min.y,
4791 root = this._pathRoot,
4792 pane = this._panes.overlayPane;
4794 // Hack to make flicker on drag end on mobile webkit less irritating
4795 if (L.Browser.mobileWebkit) {
4796 pane.removeChild(root);
4799 L.DomUtil.setPosition(root, min);
4800 root.setAttribute('width', width);
4801 root.setAttribute('height', height);
4802 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4804 if (L.Browser.mobileWebkit) {
4805 pane.appendChild(root);
4812 * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4817 bindPopup: function (content, options) {
4819 if (content instanceof L.Popup) {
4820 this._popup = content;
4822 if (!this._popup || options) {
4823 this._popup = new L.Popup(options, this);
4825 this._popup.setContent(content);
4828 if (!this._popupHandlersAdded) {
4830 .on('click', this._openPopup, this)
4831 .on('remove', this.closePopup, this);
4833 this._popupHandlersAdded = true;
4839 unbindPopup: function () {
4843 .off('click', this._openPopup)
4844 .off('remove', this.closePopup);
4846 this._popupHandlersAdded = false;
4851 openPopup: function (latlng) {
4854 // open the popup from one of the path's points if not specified
4855 latlng = latlng || this._latlng ||
4856 this._latlngs[Math.floor(this._latlngs.length / 2)];
4858 this._openPopup({latlng: latlng});
4864 closePopup: function () {
4866 this._popup._close();
4871 _openPopup: function (e) {
4872 this._popup.setLatLng(e.latlng);
4873 this._map.openPopup(this._popup);
4879 * Vector rendering for IE6-8 through VML.
4880 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4883 L.Browser.vml = !L.Browser.svg && (function () {
4885 var div = document.createElement('div');
4886 div.innerHTML = '<v:shape adj="1"/>';
4888 var shape = div.firstChild;
4889 shape.style.behavior = 'url(#default#VML)';
4891 return shape && (typeof shape.adj === 'object');
4898 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4904 _createElement: (function () {
4906 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4907 return function (name) {
4908 return document.createElement('<lvml:' + name + ' class="lvml">');
4911 return function (name) {
4912 return document.createElement(
4913 '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4918 _initPath: function () {
4919 var container = this._container = this._createElement('shape');
4921 L.DomUtil.addClass(container, 'leaflet-vml-shape' +
4922 (this.options.className ? ' ' + this.options.className : ''));
4924 if (this.options.clickable) {
4925 L.DomUtil.addClass(container, 'leaflet-clickable');
4928 container.coordsize = '1 1';
4930 this._path = this._createElement('path');
4931 container.appendChild(this._path);
4933 this._map._pathRoot.appendChild(container);
4936 _initStyle: function () {
4937 this._updateStyle();
4940 _updateStyle: function () {
4941 var stroke = this._stroke,
4943 options = this.options,
4944 container = this._container;
4946 container.stroked = options.stroke;
4947 container.filled = options.fill;
4949 if (options.stroke) {
4951 stroke = this._stroke = this._createElement('stroke');
4952 stroke.endcap = 'round';
4953 container.appendChild(stroke);
4955 stroke.weight = options.weight + 'px';
4956 stroke.color = options.color;
4957 stroke.opacity = options.opacity;
4959 if (options.dashArray) {
4960 stroke.dashStyle = L.Util.isArray(options.dashArray) ?
4961 options.dashArray.join(' ') :
4962 options.dashArray.replace(/( *, *)/g, ' ');
4964 stroke.dashStyle = '';
4966 if (options.lineCap) {
4967 stroke.endcap = options.lineCap.replace('butt', 'flat');
4969 if (options.lineJoin) {
4970 stroke.joinstyle = options.lineJoin;
4973 } else if (stroke) {
4974 container.removeChild(stroke);
4975 this._stroke = null;
4980 fill = this._fill = this._createElement('fill');
4981 container.appendChild(fill);
4983 fill.color = options.fillColor || options.color;
4984 fill.opacity = options.fillOpacity;
4987 container.removeChild(fill);
4992 _updatePath: function () {
4993 var style = this._container.style;
4995 style.display = 'none';
4996 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
5001 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
5002 _initPathRoot: function () {
5003 if (this._pathRoot) { return; }
5005 var root = this._pathRoot = document.createElement('div');
5006 root.className = 'leaflet-vml-container';
5007 this._panes.overlayPane.appendChild(root);
5009 this.on('moveend', this._updatePathViewport);
5010 this._updatePathViewport();
5016 * Vector rendering for all browsers that support canvas.
5019 L.Browser.canvas = (function () {
5020 return !!document.createElement('canvas').getContext;
5023 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
5025 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
5030 redraw: function () {
5032 this.projectLatlngs();
5033 this._requestUpdate();
5038 setStyle: function (style) {
5039 L.setOptions(this, style);
5042 this._updateStyle();
5043 this._requestUpdate();
5048 onRemove: function (map) {
5050 .off('viewreset', this.projectLatlngs, this)
5051 .off('moveend', this._updatePath, this);
5053 if (this.options.clickable) {
5054 this._map.off('click', this._onClick, this);
5055 this._map.off('mousemove', this._onMouseMove, this);
5058 this._requestUpdate();
5060 this.fire('remove');
5064 _requestUpdate: function () {
5065 if (this._map && !L.Path._updateRequest) {
5066 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
5070 _fireMapMoveEnd: function () {
5071 L.Path._updateRequest = null;
5072 this.fire('moveend');
5075 _initElements: function () {
5076 this._map._initPathRoot();
5077 this._ctx = this._map._canvasCtx;
5080 _updateStyle: function () {
5081 var options = this.options;
5083 if (options.stroke) {
5084 this._ctx.lineWidth = options.weight;
5085 this._ctx.strokeStyle = options.color;
5088 this._ctx.fillStyle = options.fillColor || options.color;
5091 if (options.lineCap) {
5092 this._ctx.lineCap = options.lineCap;
5094 if (options.lineJoin) {
5095 this._ctx.lineJoin = options.lineJoin;
5099 _drawPath: function () {
5100 var i, j, len, len2, point, drawMethod;
5102 this._ctx.beginPath();
5104 for (i = 0, len = this._parts.length; i < len; i++) {
5105 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
5106 point = this._parts[i][j];
5107 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
5109 this._ctx[drawMethod](point.x, point.y);
5111 // TODO refactor ugly hack
5112 if (this instanceof L.Polygon) {
5113 this._ctx.closePath();
5118 _checkIfEmpty: function () {
5119 return !this._parts.length;
5122 _updatePath: function () {
5123 if (this._checkIfEmpty()) { return; }
5125 var ctx = this._ctx,
5126 options = this.options;
5130 this._updateStyle();
5133 ctx.globalAlpha = options.fillOpacity;
5134 ctx.fill(options.fillRule || 'evenodd');
5137 if (options.stroke) {
5138 ctx.globalAlpha = options.opacity;
5144 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
5147 _initEvents: function () {
5148 if (this.options.clickable) {
5149 this._map.on('mousemove', this._onMouseMove, this);
5150 this._map.on('click dblclick contextmenu', this._fireMouseEvent, this);
5154 _fireMouseEvent: function (e) {
5155 if (this._containsPoint(e.layerPoint)) {
5156 this.fire(e.type, e);
5160 _onMouseMove: function (e) {
5161 if (!this._map || this._map._animatingZoom) { return; }
5163 // TODO don't do on each move
5164 if (this._containsPoint(e.layerPoint)) {
5165 this._ctx.canvas.style.cursor = 'pointer';
5166 this._mouseInside = true;
5167 this.fire('mouseover', e);
5169 } else if (this._mouseInside) {
5170 this._ctx.canvas.style.cursor = '';
5171 this._mouseInside = false;
5172 this.fire('mouseout', e);
5177 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
5178 _initPathRoot: function () {
5179 var root = this._pathRoot,
5183 root = this._pathRoot = document.createElement('canvas');
5184 root.style.position = 'absolute';
5185 ctx = this._canvasCtx = root.getContext('2d');
5187 ctx.lineCap = 'round';
5188 ctx.lineJoin = 'round';
5190 this._panes.overlayPane.appendChild(root);
5192 if (this.options.zoomAnimation) {
5193 this._pathRoot.className = 'leaflet-zoom-animated';
5194 this.on('zoomanim', this._animatePathZoom);
5195 this.on('zoomend', this._endPathZoom);
5197 this.on('moveend', this._updateCanvasViewport);
5198 this._updateCanvasViewport();
5202 _updateCanvasViewport: function () {
5203 // don't redraw while zooming. See _updateSvgViewport for more details
5204 if (this._pathZooming) { return; }
5205 this._updatePathViewport();
5207 var vp = this._pathViewport,
5209 size = vp.max.subtract(min),
5210 root = this._pathRoot;
5212 //TODO check if this works properly on mobile webkit
5213 L.DomUtil.setPosition(root, min);
5214 root.width = size.x;
5215 root.height = size.y;
5216 root.getContext('2d').translate(-min.x, -min.y);
5222 * L.LineUtil contains different utility functions for line segments
5223 * and polylines (clipping, simplification, distances, etc.)
5226 /*jshint bitwise:false */ // allow bitwise operations for this file
5230 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
5231 // Improves rendering performance dramatically by lessening the number of points to draw.
5233 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
5234 if (!tolerance || !points.length) {
5235 return points.slice();
5238 var sqTolerance = tolerance * tolerance;
5240 // stage 1: vertex reduction
5241 points = this._reducePoints(points, sqTolerance);
5243 // stage 2: Douglas-Peucker simplification
5244 points = this._simplifyDP(points, sqTolerance);
5249 // distance from a point to a segment between two points
5250 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5251 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
5254 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5255 return this._sqClosestPointOnSegment(p, p1, p2);
5258 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
5259 _simplifyDP: function (points, sqTolerance) {
5261 var len = points.length,
5262 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
5263 markers = new ArrayConstructor(len);
5265 markers[0] = markers[len - 1] = 1;
5267 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
5272 for (i = 0; i < len; i++) {
5274 newPoints.push(points[i]);
5281 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
5286 for (i = first + 1; i <= last - 1; i++) {
5287 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
5289 if (sqDist > maxSqDist) {
5295 if (maxSqDist > sqTolerance) {
5298 this._simplifyDPStep(points, markers, sqTolerance, first, index);
5299 this._simplifyDPStep(points, markers, sqTolerance, index, last);
5303 // reduce points that are too close to each other to a single point
5304 _reducePoints: function (points, sqTolerance) {
5305 var reducedPoints = [points[0]];
5307 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
5308 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
5309 reducedPoints.push(points[i]);
5313 if (prev < len - 1) {
5314 reducedPoints.push(points[len - 1]);
5316 return reducedPoints;
5319 // Cohen-Sutherland line clipping algorithm.
5320 // Used to avoid rendering parts of a polyline that are not currently visible.
5322 clipSegment: function (a, b, bounds, useLastCode) {
5323 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
5324 codeB = this._getBitCode(b, bounds),
5326 codeOut, p, newCode;
5328 // save 2nd code to avoid calculating it on the next segment
5329 this._lastCode = codeB;
5332 // if a,b is inside the clip window (trivial accept)
5333 if (!(codeA | codeB)) {
5335 // if a,b is outside the clip window (trivial reject)
5336 } else if (codeA & codeB) {
5340 codeOut = codeA || codeB;
5341 p = this._getEdgeIntersection(a, b, codeOut, bounds);
5342 newCode = this._getBitCode(p, bounds);
5344 if (codeOut === codeA) {
5355 _getEdgeIntersection: function (a, b, code, bounds) {
5361 if (code & 8) { // top
5362 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
5363 } else if (code & 4) { // bottom
5364 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
5365 } else if (code & 2) { // right
5366 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
5367 } else if (code & 1) { // left
5368 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
5372 _getBitCode: function (/*Point*/ p, bounds) {
5375 if (p.x < bounds.min.x) { // left
5377 } else if (p.x > bounds.max.x) { // right
5380 if (p.y < bounds.min.y) { // bottom
5382 } else if (p.y > bounds.max.y) { // top
5389 // square distance (to avoid unnecessary Math.sqrt calls)
5390 _sqDist: function (p1, p2) {
5391 var dx = p2.x - p1.x,
5393 return dx * dx + dy * dy;
5396 // return closest point on segment or distance to that point
5397 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
5402 dot = dx * dx + dy * dy,
5406 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
5420 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
5426 * L.Polyline is used to display polylines on a map.
5429 L.Polyline = L.Path.extend({
5430 initialize: function (latlngs, options) {
5431 L.Path.prototype.initialize.call(this, options);
5433 this._latlngs = this._convertLatLngs(latlngs);
5437 // how much to simplify the polyline on each zoom level
5438 // more = better performance and smoother look, less = more accurate
5443 projectLatlngs: function () {
5444 this._originalPoints = [];
5446 for (var i = 0, len = this._latlngs.length; i < len; i++) {
5447 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
5451 getPathString: function () {
5452 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
5453 str += this._getPathPartStr(this._parts[i]);
5458 getLatLngs: function () {
5459 return this._latlngs;
5462 setLatLngs: function (latlngs) {
5463 this._latlngs = this._convertLatLngs(latlngs);
5464 return this.redraw();
5467 addLatLng: function (latlng) {
5468 this._latlngs.push(L.latLng(latlng));
5469 return this.redraw();
5472 spliceLatLngs: function () { // (Number index, Number howMany)
5473 var removed = [].splice.apply(this._latlngs, arguments);
5474 this._convertLatLngs(this._latlngs, true);
5479 closestLayerPoint: function (p) {
5480 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
5482 for (var j = 0, jLen = parts.length; j < jLen; j++) {
5483 var points = parts[j];
5484 for (var i = 1, len = points.length; i < len; i++) {
5487 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
5488 if (sqDist < minDistance) {
5489 minDistance = sqDist;
5490 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
5495 minPoint.distance = Math.sqrt(minDistance);
5500 getBounds: function () {
5501 return new L.LatLngBounds(this.getLatLngs());
5504 _convertLatLngs: function (latlngs, overwrite) {
5505 var i, len, target = overwrite ? latlngs : [];
5507 for (i = 0, len = latlngs.length; i < len; i++) {
5508 if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
5511 target[i] = L.latLng(latlngs[i]);
5516 _initEvents: function () {
5517 L.Path.prototype._initEvents.call(this);
5520 _getPathPartStr: function (points) {
5521 var round = L.Path.VML;
5523 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
5528 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
5533 _clipPoints: function () {
5534 var points = this._originalPoints,
5535 len = points.length,
5538 if (this.options.noClip) {
5539 this._parts = [points];
5545 var parts = this._parts,
5546 vp = this._map._pathViewport,
5549 for (i = 0, k = 0; i < len - 1; i++) {
5550 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
5555 parts[k] = parts[k] || [];
5556 parts[k].push(segment[0]);
5558 // if segment goes out of screen, or it's the last one, it's the end of the line part
5559 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
5560 parts[k].push(segment[1]);
5566 // simplify each clipped part of the polyline
5567 _simplifyPoints: function () {
5568 var parts = this._parts,
5571 for (var i = 0, len = parts.length; i < len; i++) {
5572 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
5576 _updatePath: function () {
5577 if (!this._map) { return; }
5580 this._simplifyPoints();
5582 L.Path.prototype._updatePath.call(this);
5586 L.polyline = function (latlngs, options) {
5587 return new L.Polyline(latlngs, options);
5592 * L.PolyUtil contains utility functions for polygons (clipping, etc.).
5595 /*jshint bitwise:false */ // allow bitwise operations here
5600 * Sutherland-Hodgeman polygon clipping algorithm.
5601 * Used to avoid rendering parts of a polygon that are not currently visible.
5603 L.PolyUtil.clipPolygon = function (points, bounds) {
5605 edges = [1, 4, 2, 8],
5611 for (i = 0, len = points.length; i < len; i++) {
5612 points[i]._code = lu._getBitCode(points[i], bounds);
5615 // for each edge (left, bottom, right, top)
5616 for (k = 0; k < 4; k++) {
5620 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5624 // if a is inside the clip window
5625 if (!(a._code & edge)) {
5626 // if b is outside the clip window (a->b goes out of screen)
5627 if (b._code & edge) {
5628 p = lu._getEdgeIntersection(b, a, edge, bounds);
5629 p._code = lu._getBitCode(p, bounds);
5630 clippedPoints.push(p);
5632 clippedPoints.push(a);
5634 // else if b is inside the clip window (a->b enters the screen)
5635 } else if (!(b._code & edge)) {
5636 p = lu._getEdgeIntersection(b, a, edge, bounds);
5637 p._code = lu._getBitCode(p, bounds);
5638 clippedPoints.push(p);
5641 points = clippedPoints;
5649 * L.Polygon is used to display polygons on a map.
5652 L.Polygon = L.Polyline.extend({
5657 initialize: function (latlngs, options) {
5658 L.Polyline.prototype.initialize.call(this, latlngs, options);
5659 this._initWithHoles(latlngs);
5662 _initWithHoles: function (latlngs) {
5664 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5665 this._latlngs = this._convertLatLngs(latlngs[0]);
5666 this._holes = latlngs.slice(1);
5668 for (i = 0, len = this._holes.length; i < len; i++) {
5669 hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
5670 if (hole[0].equals(hole[hole.length - 1])) {
5676 // filter out last point if its equal to the first one
5677 latlngs = this._latlngs;
5679 if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
5684 projectLatlngs: function () {
5685 L.Polyline.prototype.projectLatlngs.call(this);
5687 // project polygon holes points
5688 // TODO move this logic to Polyline to get rid of duplication
5689 this._holePoints = [];
5691 if (!this._holes) { return; }
5693 var i, j, len, len2;
5695 for (i = 0, len = this._holes.length; i < len; i++) {
5696 this._holePoints[i] = [];
5698 for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5699 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5704 setLatLngs: function (latlngs) {
5705 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5706 this._initWithHoles(latlngs);
5707 return this.redraw();
5709 return L.Polyline.prototype.setLatLngs.call(this, latlngs);
5713 _clipPoints: function () {
5714 var points = this._originalPoints,
5717 this._parts = [points].concat(this._holePoints);
5719 if (this.options.noClip) { return; }
5721 for (var i = 0, len = this._parts.length; i < len; i++) {
5722 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5723 if (clipped.length) {
5724 newParts.push(clipped);
5728 this._parts = newParts;
5731 _getPathPartStr: function (points) {
5732 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5733 return str + (L.Browser.svg ? 'z' : 'x');
5737 L.polygon = function (latlngs, options) {
5738 return new L.Polygon(latlngs, options);
5743 * Contains L.MultiPolyline and L.MultiPolygon layers.
5747 function createMulti(Klass) {
5749 return L.FeatureGroup.extend({
5751 initialize: function (latlngs, options) {
5753 this._options = options;
5754 this.setLatLngs(latlngs);
5757 setLatLngs: function (latlngs) {
5759 len = latlngs.length;
5761 this.eachLayer(function (layer) {
5763 layer.setLatLngs(latlngs[i++]);
5765 this.removeLayer(layer);
5770 this.addLayer(new Klass(latlngs[i++], this._options));
5776 getLatLngs: function () {
5779 this.eachLayer(function (layer) {
5780 latlngs.push(layer.getLatLngs());
5788 L.MultiPolyline = createMulti(L.Polyline);
5789 L.MultiPolygon = createMulti(L.Polygon);
5791 L.multiPolyline = function (latlngs, options) {
5792 return new L.MultiPolyline(latlngs, options);
5795 L.multiPolygon = function (latlngs, options) {
5796 return new L.MultiPolygon(latlngs, options);
5802 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5805 L.Rectangle = L.Polygon.extend({
5806 initialize: function (latLngBounds, options) {
5807 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5810 setBounds: function (latLngBounds) {
5811 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5814 _boundsToLatLngs: function (latLngBounds) {
5815 latLngBounds = L.latLngBounds(latLngBounds);
5817 latLngBounds.getSouthWest(),
5818 latLngBounds.getNorthWest(),
5819 latLngBounds.getNorthEast(),
5820 latLngBounds.getSouthEast()
5825 L.rectangle = function (latLngBounds, options) {
5826 return new L.Rectangle(latLngBounds, options);
5831 * L.Circle is a circle overlay (with a certain radius in meters).
5834 L.Circle = L.Path.extend({
5835 initialize: function (latlng, radius, options) {
5836 L.Path.prototype.initialize.call(this, options);
5838 this._latlng = L.latLng(latlng);
5839 this._mRadius = radius;
5846 setLatLng: function (latlng) {
5847 this._latlng = L.latLng(latlng);
5848 return this.redraw();
5851 setRadius: function (radius) {
5852 this._mRadius = radius;
5853 return this.redraw();
5856 projectLatlngs: function () {
5857 var lngRadius = this._getLngRadius(),
5858 latlng = this._latlng,
5859 pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
5861 this._point = this._map.latLngToLayerPoint(latlng);
5862 this._radius = Math.max(this._point.x - pointLeft.x, 1);
5865 getBounds: function () {
5866 var lngRadius = this._getLngRadius(),
5867 latRadius = (this._mRadius / 40075017) * 360,
5868 latlng = this._latlng;
5870 return new L.LatLngBounds(
5871 [latlng.lat - latRadius, latlng.lng - lngRadius],
5872 [latlng.lat + latRadius, latlng.lng + lngRadius]);
5875 getLatLng: function () {
5876 return this._latlng;
5879 getPathString: function () {
5880 var p = this._point,
5883 if (this._checkIfEmpty()) {
5887 if (L.Browser.svg) {
5888 return 'M' + p.x + ',' + (p.y - r) +
5889 'A' + r + ',' + r + ',0,1,1,' +
5890 (p.x - 0.1) + ',' + (p.y - r) + ' z';
5894 return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
5898 getRadius: function () {
5899 return this._mRadius;
5902 // TODO Earth hardcoded, move into projection code!
5904 _getLatRadius: function () {
5905 return (this._mRadius / 40075017) * 360;
5908 _getLngRadius: function () {
5909 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5912 _checkIfEmpty: function () {
5916 var vp = this._map._pathViewport,
5920 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5921 p.x + r < vp.min.x || p.y + r < vp.min.y;
5925 L.circle = function (latlng, radius, options) {
5926 return new L.Circle(latlng, radius, options);
5931 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5934 L.CircleMarker = L.Circle.extend({
5940 initialize: function (latlng, options) {
5941 L.Circle.prototype.initialize.call(this, latlng, null, options);
5942 this._radius = this.options.radius;
5945 projectLatlngs: function () {
5946 this._point = this._map.latLngToLayerPoint(this._latlng);
5949 _updateStyle : function () {
5950 L.Circle.prototype._updateStyle.call(this);
5951 this.setRadius(this.options.radius);
5954 setLatLng: function (latlng) {
5955 L.Circle.prototype.setLatLng.call(this, latlng);
5956 if (this._popup && this._popup._isOpen) {
5957 this._popup.setLatLng(latlng);
5962 setRadius: function (radius) {
5963 this.options.radius = this._radius = radius;
5964 return this.redraw();
5967 getRadius: function () {
5968 return this._radius;
5972 L.circleMarker = function (latlng, options) {
5973 return new L.CircleMarker(latlng, options);
5978 * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
5981 L.Polyline.include(!L.Path.CANVAS ? {} : {
5982 _containsPoint: function (p, closed) {
5983 var i, j, k, len, len2, dist, part,
5984 w = this.options.weight / 2;
5986 if (L.Browser.touch) {
5987 w += 10; // polyline click tolerance on touch devices
5990 for (i = 0, len = this._parts.length; i < len; i++) {
5991 part = this._parts[i];
5992 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
5993 if (!closed && (j === 0)) {
5997 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
6010 * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
6013 L.Polygon.include(!L.Path.CANVAS ? {} : {
6014 _containsPoint: function (p) {
6020 // TODO optimization: check if within bounds first
6022 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
6023 // click on polygon border
6027 // ray casting algorithm for detecting if point is in polygon
6029 for (i = 0, len = this._parts.length; i < len; i++) {
6030 part = this._parts[i];
6032 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
6036 if (((p1.y > p.y) !== (p2.y > p.y)) &&
6037 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
6049 * Extends L.Circle with Canvas-specific code.
6052 L.Circle.include(!L.Path.CANVAS ? {} : {
6053 _drawPath: function () {
6054 var p = this._point;
6055 this._ctx.beginPath();
6056 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
6059 _containsPoint: function (p) {
6060 var center = this._point,
6061 w2 = this.options.stroke ? this.options.weight / 2 : 0;
6063 return (p.distanceTo(center) <= this._radius + w2);
6069 * CircleMarker canvas specific drawing parts.
6072 L.CircleMarker.include(!L.Path.CANVAS ? {} : {
6073 _updateStyle: function () {
6074 L.Path.prototype._updateStyle.call(this);
6080 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
6083 L.GeoJSON = L.FeatureGroup.extend({
6085 initialize: function (geojson, options) {
6086 L.setOptions(this, options);
6091 this.addData(geojson);
6095 addData: function (geojson) {
6096 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
6100 for (i = 0, len = features.length; i < len; i++) {
6101 // Only add this if geometry or geometries are set and not null
6102 feature = features[i];
6103 if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
6104 this.addData(features[i]);
6110 var options = this.options;
6112 if (options.filter && !options.filter(geojson)) { return; }
6114 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng, options);
6115 layer.feature = L.GeoJSON.asFeature(geojson);
6117 layer.defaultOptions = layer.options;
6118 this.resetStyle(layer);
6120 if (options.onEachFeature) {
6121 options.onEachFeature(geojson, layer);
6124 return this.addLayer(layer);
6127 resetStyle: function (layer) {
6128 var style = this.options.style;
6130 // reset any custom styles
6131 L.Util.extend(layer.options, layer.defaultOptions);
6133 this._setLayerStyle(layer, style);
6137 setStyle: function (style) {
6138 this.eachLayer(function (layer) {
6139 this._setLayerStyle(layer, style);
6143 _setLayerStyle: function (layer, style) {
6144 if (typeof style === 'function') {
6145 style = style(layer.feature);
6147 if (layer.setStyle) {
6148 layer.setStyle(style);
6153 L.extend(L.GeoJSON, {
6154 geometryToLayer: function (geojson, pointToLayer, coordsToLatLng, vectorOptions) {
6155 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
6156 coords = geometry.coordinates,
6158 latlng, latlngs, i, len;
6160 coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
6162 switch (geometry.type) {
6164 latlng = coordsToLatLng(coords);
6165 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6168 for (i = 0, len = coords.length; i < len; i++) {
6169 latlng = coordsToLatLng(coords[i]);
6170 layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng));
6172 return new L.FeatureGroup(layers);
6175 latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
6176 return new L.Polyline(latlngs, vectorOptions);
6179 if (coords.length === 2 && !coords[1].length) {
6180 throw new Error('Invalid GeoJSON object.');
6182 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6183 return new L.Polygon(latlngs, vectorOptions);
6185 case 'MultiLineString':
6186 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6187 return new L.MultiPolyline(latlngs, vectorOptions);
6189 case 'MultiPolygon':
6190 latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
6191 return new L.MultiPolygon(latlngs, vectorOptions);
6193 case 'GeometryCollection':
6194 for (i = 0, len = geometry.geometries.length; i < len; i++) {
6196 layers.push(this.geometryToLayer({
6197 geometry: geometry.geometries[i],
6199 properties: geojson.properties
6200 }, pointToLayer, coordsToLatLng, vectorOptions));
6202 return new L.FeatureGroup(layers);
6205 throw new Error('Invalid GeoJSON object.');
6209 coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
6210 return new L.LatLng(coords[1], coords[0], coords[2]);
6213 coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
6217 for (i = 0, len = coords.length; i < len; i++) {
6218 latlng = levelsDeep ?
6219 this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
6220 (coordsToLatLng || this.coordsToLatLng)(coords[i]);
6222 latlngs.push(latlng);
6228 latLngToCoords: function (latlng) {
6229 var coords = [latlng.lng, latlng.lat];
6231 if (latlng.alt !== undefined) {
6232 coords.push(latlng.alt);
6237 latLngsToCoords: function (latLngs) {
6240 for (var i = 0, len = latLngs.length; i < len; i++) {
6241 coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
6247 getFeature: function (layer, newGeometry) {
6248 return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
6251 asFeature: function (geoJSON) {
6252 if (geoJSON.type === 'Feature') {
6264 var PointToGeoJSON = {
6265 toGeoJSON: function () {
6266 return L.GeoJSON.getFeature(this, {
6268 coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
6273 L.Marker.include(PointToGeoJSON);
6274 L.Circle.include(PointToGeoJSON);
6275 L.CircleMarker.include(PointToGeoJSON);
6277 L.Polyline.include({
6278 toGeoJSON: function () {
6279 return L.GeoJSON.getFeature(this, {
6281 coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
6287 toGeoJSON: function () {
6288 var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
6291 coords[0].push(coords[0][0]);
6294 for (i = 0, len = this._holes.length; i < len; i++) {
6295 hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
6301 return L.GeoJSON.getFeature(this, {
6309 function multiToGeoJSON(type) {
6310 return function () {
6313 this.eachLayer(function (layer) {
6314 coords.push(layer.toGeoJSON().geometry.coordinates);
6317 return L.GeoJSON.getFeature(this, {
6324 L.MultiPolyline.include({toGeoJSON: multiToGeoJSON('MultiLineString')});
6325 L.MultiPolygon.include({toGeoJSON: multiToGeoJSON('MultiPolygon')});
6327 L.LayerGroup.include({
6328 toGeoJSON: function () {
6330 var geometry = this.feature && this.feature.geometry,
6334 if (geometry && geometry.type === 'MultiPoint') {
6335 return multiToGeoJSON('MultiPoint').call(this);
6338 var isGeometryCollection = geometry && geometry.type === 'GeometryCollection';
6340 this.eachLayer(function (layer) {
6341 if (layer.toGeoJSON) {
6342 json = layer.toGeoJSON();
6343 jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
6347 if (isGeometryCollection) {
6348 return L.GeoJSON.getFeature(this, {
6350 type: 'GeometryCollection'
6355 type: 'FeatureCollection',
6362 L.geoJson = function (geojson, options) {
6363 return new L.GeoJSON(geojson, options);
6368 * L.DomEvent contains functions for working with DOM events.
6372 /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
6373 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
6375 var id = L.stamp(fn),
6376 key = '_leaflet_' + type + id,
6377 handler, originalHandler, newType;
6379 if (obj[key]) { return this; }
6381 handler = function (e) {
6382 return fn.call(context || obj, e || L.DomEvent._getEvent());
6385 if (L.Browser.pointer && type.indexOf('touch') === 0) {
6386 return this.addPointerListener(obj, type, handler, id);
6388 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
6389 this.addDoubleTapListener(obj, handler, id);
6392 if ('addEventListener' in obj) {
6394 if (type === 'mousewheel') {
6395 obj.addEventListener('DOMMouseScroll', handler, false);
6396 obj.addEventListener(type, handler, false);
6398 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6400 originalHandler = handler;
6401 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
6403 handler = function (e) {
6404 if (!L.DomEvent._checkMouse(obj, e)) { return; }
6405 return originalHandler(e);
6408 obj.addEventListener(newType, handler, false);
6410 } else if (type === 'click' && L.Browser.android) {
6411 originalHandler = handler;
6412 handler = function (e) {
6413 return L.DomEvent._filterClick(e, originalHandler);
6416 obj.addEventListener(type, handler, false);
6418 obj.addEventListener(type, handler, false);
6421 } else if ('attachEvent' in obj) {
6422 obj.attachEvent('on' + type, handler);
6430 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
6432 var id = L.stamp(fn),
6433 key = '_leaflet_' + type + id,
6436 if (!handler) { return this; }
6438 if (L.Browser.pointer && type.indexOf('touch') === 0) {
6439 this.removePointerListener(obj, type, id);
6440 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
6441 this.removeDoubleTapListener(obj, id);
6443 } else if ('removeEventListener' in obj) {
6445 if (type === 'mousewheel') {
6446 obj.removeEventListener('DOMMouseScroll', handler, false);
6447 obj.removeEventListener(type, handler, false);
6449 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6450 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
6452 obj.removeEventListener(type, handler, false);
6454 } else if ('detachEvent' in obj) {
6455 obj.detachEvent('on' + type, handler);
6463 stopPropagation: function (e) {
6465 if (e.stopPropagation) {
6466 e.stopPropagation();
6468 e.cancelBubble = true;
6470 L.DomEvent._skipped(e);
6475 disableScrollPropagation: function (el) {
6476 var stop = L.DomEvent.stopPropagation;
6479 .on(el, 'mousewheel', stop)
6480 .on(el, 'MozMousePixelScroll', stop);
6483 disableClickPropagation: function (el) {
6484 var stop = L.DomEvent.stopPropagation;
6486 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6487 L.DomEvent.on(el, L.Draggable.START[i], stop);
6491 .on(el, 'click', L.DomEvent._fakeStop)
6492 .on(el, 'dblclick', stop);
6495 preventDefault: function (e) {
6497 if (e.preventDefault) {
6500 e.returnValue = false;
6505 stop: function (e) {
6508 .stopPropagation(e);
6511 getMousePosition: function (e, container) {
6513 return new L.Point(e.clientX, e.clientY);
6516 var rect = container.getBoundingClientRect();
6519 e.clientX - rect.left - container.clientLeft,
6520 e.clientY - rect.top - container.clientTop);
6523 getWheelDelta: function (e) {
6528 delta = e.wheelDelta / 120;
6531 delta = -e.detail / 3;
6538 _fakeStop: function (e) {
6539 // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
6540 L.DomEvent._skipEvents[e.type] = true;
6543 _skipped: function (e) {
6544 var skipped = this._skipEvents[e.type];
6545 // reset when checking, as it's only used in map container and propagates outside of the map
6546 this._skipEvents[e.type] = false;
6550 // check if element really left/entered the event target (for mouseenter/mouseleave)
6551 _checkMouse: function (el, e) {
6553 var related = e.relatedTarget;
6555 if (!related) { return true; }
6558 while (related && (related !== el)) {
6559 related = related.parentNode;
6564 return (related !== el);
6567 _getEvent: function () { // evil magic for IE
6568 /*jshint noarg:false */
6569 var e = window.event;
6571 var caller = arguments.callee.caller;
6573 e = caller['arguments'][0];
6574 if (e && window.Event === e.constructor) {
6577 caller = caller.caller;
6583 // this is a horrible workaround for a bug in Android where a single touch triggers two click events
6584 _filterClick: function (e, handler) {
6585 var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
6586 elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
6588 // are they closer together than 500ms yet more than 100ms?
6589 // Android typically triggers them ~300ms apart while multiple listeners
6590 // on the same event should be triggered far faster;
6591 // or check if click is simulated on the element, and if it is, reject any non-simulated events
6593 if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
6597 L.DomEvent._lastClick = timeStamp;
6603 L.DomEvent.on = L.DomEvent.addListener;
6604 L.DomEvent.off = L.DomEvent.removeListener;
6608 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
6611 L.Draggable = L.Class.extend({
6612 includes: L.Mixin.Events,
6615 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
6617 mousedown: 'mouseup',
6618 touchstart: 'touchend',
6619 pointerdown: 'touchend',
6620 MSPointerDown: 'touchend'
6623 mousedown: 'mousemove',
6624 touchstart: 'touchmove',
6625 pointerdown: 'touchmove',
6626 MSPointerDown: 'touchmove'
6630 initialize: function (element, dragStartTarget) {
6631 this._element = element;
6632 this._dragStartTarget = dragStartTarget || element;
6635 enable: function () {
6636 if (this._enabled) { return; }
6638 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6639 L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6642 this._enabled = true;
6645 disable: function () {
6646 if (!this._enabled) { return; }
6648 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6649 L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6652 this._enabled = false;
6653 this._moved = false;
6656 _onDown: function (e) {
6657 this._moved = false;
6659 if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
6661 L.DomEvent.stopPropagation(e);
6663 if (L.Draggable._disabled) { return; }
6665 L.DomUtil.disableImageDrag();
6666 L.DomUtil.disableTextSelection();
6668 if (this._moving) { return; }
6670 var first = e.touches ? e.touches[0] : e;
6672 this._startPoint = new L.Point(first.clientX, first.clientY);
6673 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
6676 .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
6677 .on(document, L.Draggable.END[e.type], this._onUp, this);
6680 _onMove: function (e) {
6681 if (e.touches && e.touches.length > 1) {
6686 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
6687 newPoint = new L.Point(first.clientX, first.clientY),
6688 offset = newPoint.subtract(this._startPoint);
6690 if (!offset.x && !offset.y) { return; }
6691 if (L.Browser.touch && Math.abs(offset.x) + Math.abs(offset.y) < 3) { return; }
6693 L.DomEvent.preventDefault(e);
6696 this.fire('dragstart');
6699 this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
6701 L.DomUtil.addClass(document.body, 'leaflet-dragging');
6702 this._lastTarget = e.target || e.srcElement;
6703 L.DomUtil.addClass(this._lastTarget, 'leaflet-drag-target');
6706 this._newPos = this._startPos.add(offset);
6707 this._moving = true;
6709 L.Util.cancelAnimFrame(this._animRequest);
6710 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
6713 _updatePosition: function () {
6714 this.fire('predrag');
6715 L.DomUtil.setPosition(this._element, this._newPos);
6719 _onUp: function () {
6720 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
6722 if (this._lastTarget) {
6723 L.DomUtil.removeClass(this._lastTarget, 'leaflet-drag-target');
6724 this._lastTarget = null;
6727 for (var i in L.Draggable.MOVE) {
6729 .off(document, L.Draggable.MOVE[i], this._onMove)
6730 .off(document, L.Draggable.END[i], this._onUp);
6733 L.DomUtil.enableImageDrag();
6734 L.DomUtil.enableTextSelection();
6736 if (this._moved && this._moving) {
6737 // ensure drag is not fired after dragend
6738 L.Util.cancelAnimFrame(this._animRequest);
6740 this.fire('dragend', {
6741 distance: this._newPos.distanceTo(this._startPos)
6745 this._moving = false;
6751 L.Handler is a base class for handler classes that are used internally to inject
6752 interaction features like dragging to classes like Map and Marker.
6755 L.Handler = L.Class.extend({
6756 initialize: function (map) {
6760 enable: function () {
6761 if (this._enabled) { return; }
6763 this._enabled = true;
6767 disable: function () {
6768 if (!this._enabled) { return; }
6770 this._enabled = false;
6774 enabled: function () {
6775 return !!this._enabled;
6781 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
6784 L.Map.mergeOptions({
6787 inertia: !L.Browser.android23,
6788 inertiaDeceleration: 3400, // px/s^2
6789 inertiaMaxSpeed: Infinity, // px/s
6790 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
6791 easeLinearity: 0.25,
6793 // TODO refactor, move to CRS
6794 worldCopyJump: false
6797 L.Map.Drag = L.Handler.extend({
6798 addHooks: function () {
6799 if (!this._draggable) {
6800 var map = this._map;
6802 this._draggable = new L.Draggable(map._mapPane, map._container);
6804 this._draggable.on({
6805 'dragstart': this._onDragStart,
6806 'drag': this._onDrag,
6807 'dragend': this._onDragEnd
6810 if (map.options.worldCopyJump) {
6811 this._draggable.on('predrag', this._onPreDrag, this);
6812 map.on('viewreset', this._onViewReset, this);
6814 map.whenReady(this._onViewReset, this);
6817 this._draggable.enable();
6820 removeHooks: function () {
6821 this._draggable.disable();
6824 moved: function () {
6825 return this._draggable && this._draggable._moved;
6828 _onDragStart: function () {
6829 var map = this._map;
6832 map._panAnim.stop();
6839 if (map.options.inertia) {
6840 this._positions = [];
6845 _onDrag: function () {
6846 if (this._map.options.inertia) {
6847 var time = this._lastTime = +new Date(),
6848 pos = this._lastPos = this._draggable._newPos;
6850 this._positions.push(pos);
6851 this._times.push(time);
6853 if (time - this._times[0] > 200) {
6854 this._positions.shift();
6855 this._times.shift();
6864 _onViewReset: function () {
6865 // TODO fix hardcoded Earth values
6866 var pxCenter = this._map.getSize()._divideBy(2),
6867 pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
6869 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6870 this._worldWidth = this._map.project([0, 180]).x;
6873 _onPreDrag: function () {
6874 // TODO refactor to be able to adjust map pane position after zoom
6875 var worldWidth = this._worldWidth,
6876 halfWidth = Math.round(worldWidth / 2),
6877 dx = this._initialWorldOffset,
6878 x = this._draggable._newPos.x,
6879 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6880 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6881 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6883 this._draggable._newPos.x = newX;
6886 _onDragEnd: function (e) {
6887 var map = this._map,
6888 options = map.options,
6889 delay = +new Date() - this._lastTime,
6891 noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6893 map.fire('dragend', e);
6896 map.fire('moveend');
6900 var direction = this._lastPos.subtract(this._positions[0]),
6901 duration = (this._lastTime + delay - this._times[0]) / 1000,
6902 ease = options.easeLinearity,
6904 speedVector = direction.multiplyBy(ease / duration),
6905 speed = speedVector.distanceTo([0, 0]),
6907 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6908 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6910 decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6911 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6913 if (!offset.x || !offset.y) {
6914 map.fire('moveend');
6917 offset = map._limitOffset(offset, map.options.maxBounds);
6919 L.Util.requestAnimFrame(function () {
6921 duration: decelerationDuration,
6922 easeLinearity: ease,
6931 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6935 * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6938 L.Map.mergeOptions({
6939 doubleClickZoom: true
6942 L.Map.DoubleClickZoom = L.Handler.extend({
6943 addHooks: function () {
6944 this._map.on('dblclick', this._onDoubleClick, this);
6947 removeHooks: function () {
6948 this._map.off('dblclick', this._onDoubleClick, this);
6951 _onDoubleClick: function (e) {
6952 var map = this._map,
6953 zoom = map.getZoom() + (e.originalEvent.shiftKey ? -1 : 1);
6955 if (map.options.doubleClickZoom === 'center') {
6958 map.setZoomAround(e.containerPoint, zoom);
6963 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
6967 * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
6970 L.Map.mergeOptions({
6971 scrollWheelZoom: true
6974 L.Map.ScrollWheelZoom = L.Handler.extend({
6975 addHooks: function () {
6976 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
6977 L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6981 removeHooks: function () {
6982 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
6983 L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
6986 _onWheelScroll: function (e) {
6987 var delta = L.DomEvent.getWheelDelta(e);
6989 this._delta += delta;
6990 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
6992 if (!this._startTime) {
6993 this._startTime = +new Date();
6996 var left = Math.max(40 - (+new Date() - this._startTime), 0);
6998 clearTimeout(this._timer);
6999 this._timer = setTimeout(L.bind(this._performZoom, this), left);
7001 L.DomEvent.preventDefault(e);
7002 L.DomEvent.stopPropagation(e);
7005 _performZoom: function () {
7006 var map = this._map,
7007 delta = this._delta,
7008 zoom = map.getZoom();
7010 delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
7011 delta = Math.max(Math.min(delta, 4), -4);
7012 delta = map._limitZoom(zoom + delta) - zoom;
7015 this._startTime = null;
7017 if (!delta) { return; }
7019 if (map.options.scrollWheelZoom === 'center') {
7020 map.setZoom(zoom + delta);
7022 map.setZoomAround(this._lastMousePos, zoom + delta);
7027 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
7031 * Extends the event handling code with double tap support for mobile browsers.
7034 L.extend(L.DomEvent, {
7036 _touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart',
7037 _touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend',
7039 // inspired by Zepto touch code by Thomas Fuchs
7040 addDoubleTapListener: function (obj, handler, id) {
7046 touchstart = this._touchstart,
7047 touchend = this._touchend,
7048 trackedTouches = [];
7050 function onTouchStart(e) {
7053 if (L.Browser.pointer) {
7054 trackedTouches.push(e.pointerId);
7055 count = trackedTouches.length;
7057 count = e.touches.length;
7063 var now = Date.now(),
7064 delta = now - (last || now);
7066 touch = e.touches ? e.touches[0] : e;
7067 doubleTap = (delta > 0 && delta <= delay);
7071 function onTouchEnd(e) {
7072 if (L.Browser.pointer) {
7073 var idx = trackedTouches.indexOf(e.pointerId);
7077 trackedTouches.splice(idx, 1);
7081 if (L.Browser.pointer) {
7082 // work around .type being readonly with MSPointer* events
7086 // jshint forin:false
7087 for (var i in touch) {
7089 if (typeof prop === 'function') {
7090 newTouch[i] = prop.bind(touch);
7097 touch.type = 'dblclick';
7102 obj[pre + touchstart + id] = onTouchStart;
7103 obj[pre + touchend + id] = onTouchEnd;
7105 // on pointer we need to listen on the document, otherwise a drag starting on the map and moving off screen
7106 // will not come through to us, so we will lose track of how many touches are ongoing
7107 var endElement = L.Browser.pointer ? document.documentElement : obj;
7109 obj.addEventListener(touchstart, onTouchStart, false);
7110 endElement.addEventListener(touchend, onTouchEnd, false);
7112 if (L.Browser.pointer) {
7113 endElement.addEventListener(L.DomEvent.POINTER_CANCEL, onTouchEnd, false);
7119 removeDoubleTapListener: function (obj, id) {
7120 var pre = '_leaflet_';
7122 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
7123 (L.Browser.pointer ? document.documentElement : obj).removeEventListener(
7124 this._touchend, obj[pre + this._touchend + id], false);
7126 if (L.Browser.pointer) {
7127 document.documentElement.removeEventListener(L.DomEvent.POINTER_CANCEL, obj[pre + this._touchend + id],
7137 * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
7140 L.extend(L.DomEvent, {
7143 POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown',
7144 POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove',
7145 POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup',
7146 POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel',
7149 _pointerDocumentListener: false,
7151 // Provides a touch events wrapper for (ms)pointer events.
7152 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
7153 //ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
7155 addPointerListener: function (obj, type, handler, id) {
7159 return this.addPointerListenerStart(obj, type, handler, id);
7161 return this.addPointerListenerEnd(obj, type, handler, id);
7163 return this.addPointerListenerMove(obj, type, handler, id);
7165 throw 'Unknown touch event type';
7169 addPointerListenerStart: function (obj, type, handler, id) {
7170 var pre = '_leaflet_',
7171 pointers = this._pointers;
7173 var cb = function (e) {
7175 L.DomEvent.preventDefault(e);
7177 var alreadyInArray = false;
7178 for (var i = 0; i < pointers.length; i++) {
7179 if (pointers[i].pointerId === e.pointerId) {
7180 alreadyInArray = true;
7184 if (!alreadyInArray) {
7188 e.touches = pointers.slice();
7189 e.changedTouches = [e];
7194 obj[pre + 'touchstart' + id] = cb;
7195 obj.addEventListener(this.POINTER_DOWN, cb, false);
7197 // need to also listen for end events to keep the _pointers list accurate
7198 // this needs to be on the body and never go away
7199 if (!this._pointerDocumentListener) {
7200 var internalCb = function (e) {
7201 for (var i = 0; i < pointers.length; i++) {
7202 if (pointers[i].pointerId === e.pointerId) {
7203 pointers.splice(i, 1);
7208 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
7209 document.documentElement.addEventListener(this.POINTER_UP, internalCb, false);
7210 document.documentElement.addEventListener(this.POINTER_CANCEL, internalCb, false);
7212 this._pointerDocumentListener = true;
7218 addPointerListenerMove: function (obj, type, handler, id) {
7219 var pre = '_leaflet_',
7220 touches = this._pointers;
7224 // don't fire touch moves when mouse isn't down
7225 if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
7227 for (var i = 0; i < touches.length; i++) {
7228 if (touches[i].pointerId === e.pointerId) {
7234 e.touches = touches.slice();
7235 e.changedTouches = [e];
7240 obj[pre + 'touchmove' + id] = cb;
7241 obj.addEventListener(this.POINTER_MOVE, cb, false);
7246 addPointerListenerEnd: function (obj, type, handler, id) {
7247 var pre = '_leaflet_',
7248 touches = this._pointers;
7250 var cb = function (e) {
7251 for (var i = 0; i < touches.length; i++) {
7252 if (touches[i].pointerId === e.pointerId) {
7253 touches.splice(i, 1);
7258 e.touches = touches.slice();
7259 e.changedTouches = [e];
7264 obj[pre + 'touchend' + id] = cb;
7265 obj.addEventListener(this.POINTER_UP, cb, false);
7266 obj.addEventListener(this.POINTER_CANCEL, cb, false);
7271 removePointerListener: function (obj, type, id) {
7272 var pre = '_leaflet_',
7273 cb = obj[pre + type + id];
7277 obj.removeEventListener(this.POINTER_DOWN, cb, false);
7280 obj.removeEventListener(this.POINTER_MOVE, cb, false);
7283 obj.removeEventListener(this.POINTER_UP, cb, false);
7284 obj.removeEventListener(this.POINTER_CANCEL, cb, false);
7294 * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
7297 L.Map.mergeOptions({
7298 touchZoom: L.Browser.touch && !L.Browser.android23,
7299 bounceAtZoomLimits: true
7302 L.Map.TouchZoom = L.Handler.extend({
7303 addHooks: function () {
7304 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
7307 removeHooks: function () {
7308 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
7311 _onTouchStart: function (e) {
7312 var map = this._map;
7314 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
7316 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7317 p2 = map.mouseEventToLayerPoint(e.touches[1]),
7318 viewCenter = map._getCenterLayerPoint();
7320 this._startCenter = p1.add(p2)._divideBy(2);
7321 this._startDist = p1.distanceTo(p2);
7323 this._moved = false;
7324 this._zooming = true;
7326 this._centerOffset = viewCenter.subtract(this._startCenter);
7329 map._panAnim.stop();
7333 .on(document, 'touchmove', this._onTouchMove, this)
7334 .on(document, 'touchend', this._onTouchEnd, this);
7336 L.DomEvent.preventDefault(e);
7339 _onTouchMove: function (e) {
7340 var map = this._map;
7342 if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
7344 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7345 p2 = map.mouseEventToLayerPoint(e.touches[1]);
7347 this._scale = p1.distanceTo(p2) / this._startDist;
7348 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
7350 if (this._scale === 1) { return; }
7352 if (!map.options.bounceAtZoomLimits) {
7353 if ((map.getZoom() === map.getMinZoom() && this._scale < 1) ||
7354 (map.getZoom() === map.getMaxZoom() && this._scale > 1)) { return; }
7358 L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
7367 L.Util.cancelAnimFrame(this._animRequest);
7368 this._animRequest = L.Util.requestAnimFrame(
7369 this._updateOnMove, this, true, this._map._container);
7371 L.DomEvent.preventDefault(e);
7374 _updateOnMove: function () {
7375 var map = this._map,
7376 origin = this._getScaleOrigin(),
7377 center = map.layerPointToLatLng(origin),
7378 zoom = map.getScaleZoom(this._scale);
7380 map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta, false, true);
7383 _onTouchEnd: function () {
7384 if (!this._moved || !this._zooming) {
7385 this._zooming = false;
7389 var map = this._map;
7391 this._zooming = false;
7392 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
7393 L.Util.cancelAnimFrame(this._animRequest);
7396 .off(document, 'touchmove', this._onTouchMove)
7397 .off(document, 'touchend', this._onTouchEnd);
7399 var origin = this._getScaleOrigin(),
7400 center = map.layerPointToLatLng(origin),
7402 oldZoom = map.getZoom(),
7403 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
7404 roundZoomDelta = (floatZoomDelta > 0 ?
7405 Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
7407 zoom = map._limitZoom(oldZoom + roundZoomDelta),
7408 scale = map.getZoomScale(zoom) / this._scale;
7410 map._animateZoom(center, zoom, origin, scale);
7413 _getScaleOrigin: function () {
7414 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
7415 return this._startCenter.add(centerOffset);
7419 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
7423 * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
7426 L.Map.mergeOptions({
7431 L.Map.Tap = L.Handler.extend({
7432 addHooks: function () {
7433 L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
7436 removeHooks: function () {
7437 L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
7440 _onDown: function (e) {
7441 if (!e.touches) { return; }
7443 L.DomEvent.preventDefault(e);
7445 this._fireClick = true;
7447 // don't simulate click or track longpress if more than 1 touch
7448 if (e.touches.length > 1) {
7449 this._fireClick = false;
7450 clearTimeout(this._holdTimeout);
7454 var first = e.touches[0],
7457 this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
7459 // if touching a link, highlight it
7460 if (el.tagName && el.tagName.toLowerCase() === 'a') {
7461 L.DomUtil.addClass(el, 'leaflet-active');
7464 // simulate long hold but setting a timeout
7465 this._holdTimeout = setTimeout(L.bind(function () {
7466 if (this._isTapValid()) {
7467 this._fireClick = false;
7469 this._simulateEvent('contextmenu', first);
7474 .on(document, 'touchmove', this._onMove, this)
7475 .on(document, 'touchend', this._onUp, this);
7478 _onUp: function (e) {
7479 clearTimeout(this._holdTimeout);
7482 .off(document, 'touchmove', this._onMove, this)
7483 .off(document, 'touchend', this._onUp, this);
7485 if (this._fireClick && e && e.changedTouches) {
7487 var first = e.changedTouches[0],
7490 if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
7491 L.DomUtil.removeClass(el, 'leaflet-active');
7494 // simulate click if the touch didn't move too much
7495 if (this._isTapValid()) {
7496 this._simulateEvent('click', first);
7501 _isTapValid: function () {
7502 return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
7505 _onMove: function (e) {
7506 var first = e.touches[0];
7507 this._newPos = new L.Point(first.clientX, first.clientY);
7510 _simulateEvent: function (type, e) {
7511 var simulatedEvent = document.createEvent('MouseEvents');
7513 simulatedEvent._simulated = true;
7514 e.target._simulatedClick = true;
7516 simulatedEvent.initMouseEvent(
7517 type, true, true, window, 1,
7518 e.screenX, e.screenY,
7519 e.clientX, e.clientY,
7520 false, false, false, false, 0, null);
7522 e.target.dispatchEvent(simulatedEvent);
7526 if (L.Browser.touch && !L.Browser.pointer) {
7527 L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
7532 * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
7533 * (zoom to a selected bounding box), enabled by default.
7536 L.Map.mergeOptions({
7540 L.Map.BoxZoom = L.Handler.extend({
7541 initialize: function (map) {
7543 this._container = map._container;
7544 this._pane = map._panes.overlayPane;
7545 this._moved = false;
7548 addHooks: function () {
7549 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
7552 removeHooks: function () {
7553 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
7554 this._moved = false;
7557 moved: function () {
7561 _onMouseDown: function (e) {
7562 this._moved = false;
7564 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
7566 L.DomUtil.disableTextSelection();
7567 L.DomUtil.disableImageDrag();
7569 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
7572 .on(document, 'mousemove', this._onMouseMove, this)
7573 .on(document, 'mouseup', this._onMouseUp, this)
7574 .on(document, 'keydown', this._onKeyDown, this);
7577 _onMouseMove: function (e) {
7579 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
7580 L.DomUtil.setPosition(this._box, this._startLayerPoint);
7582 //TODO refactor: move cursor to styles
7583 this._container.style.cursor = 'crosshair';
7584 this._map.fire('boxzoomstart');
7587 var startPoint = this._startLayerPoint,
7590 layerPoint = this._map.mouseEventToLayerPoint(e),
7591 offset = layerPoint.subtract(startPoint),
7593 newPos = new L.Point(
7594 Math.min(layerPoint.x, startPoint.x),
7595 Math.min(layerPoint.y, startPoint.y));
7597 L.DomUtil.setPosition(box, newPos);
7601 // TODO refactor: remove hardcoded 4 pixels
7602 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
7603 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
7606 _finish: function () {
7608 this._pane.removeChild(this._box);
7609 this._container.style.cursor = '';
7612 L.DomUtil.enableTextSelection();
7613 L.DomUtil.enableImageDrag();
7616 .off(document, 'mousemove', this._onMouseMove)
7617 .off(document, 'mouseup', this._onMouseUp)
7618 .off(document, 'keydown', this._onKeyDown);
7621 _onMouseUp: function (e) {
7625 var map = this._map,
7626 layerPoint = map.mouseEventToLayerPoint(e);
7628 if (this._startLayerPoint.equals(layerPoint)) { return; }
7630 var bounds = new L.LatLngBounds(
7631 map.layerPointToLatLng(this._startLayerPoint),
7632 map.layerPointToLatLng(layerPoint));
7634 map.fitBounds(bounds);
7636 map.fire('boxzoomend', {
7637 boxZoomBounds: bounds
7641 _onKeyDown: function (e) {
7642 if (e.keyCode === 27) {
7648 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
7652 * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
7655 L.Map.mergeOptions({
7657 keyboardPanOffset: 80,
7658 keyboardZoomOffset: 1
7661 L.Map.Keyboard = L.Handler.extend({
7668 zoomIn: [187, 107, 61, 171],
7669 zoomOut: [189, 109, 173]
7672 initialize: function (map) {
7675 this._setPanOffset(map.options.keyboardPanOffset);
7676 this._setZoomOffset(map.options.keyboardZoomOffset);
7679 addHooks: function () {
7680 var container = this._map._container;
7682 // make the container focusable by tabbing
7683 if (container.tabIndex === -1) {
7684 container.tabIndex = '0';
7688 .on(container, 'focus', this._onFocus, this)
7689 .on(container, 'blur', this._onBlur, this)
7690 .on(container, 'mousedown', this._onMouseDown, this);
7693 .on('focus', this._addHooks, this)
7694 .on('blur', this._removeHooks, this);
7697 removeHooks: function () {
7698 this._removeHooks();
7700 var container = this._map._container;
7703 .off(container, 'focus', this._onFocus, this)
7704 .off(container, 'blur', this._onBlur, this)
7705 .off(container, 'mousedown', this._onMouseDown, this);
7708 .off('focus', this._addHooks, this)
7709 .off('blur', this._removeHooks, this);
7712 _onMouseDown: function () {
7713 if (this._focused) { return; }
7715 var body = document.body,
7716 docEl = document.documentElement,
7717 top = body.scrollTop || docEl.scrollTop,
7718 left = body.scrollLeft || docEl.scrollLeft;
7720 this._map._container.focus();
7722 window.scrollTo(left, top);
7725 _onFocus: function () {
7726 this._focused = true;
7727 this._map.fire('focus');
7730 _onBlur: function () {
7731 this._focused = false;
7732 this._map.fire('blur');
7735 _setPanOffset: function (pan) {
7736 var keys = this._panKeys = {},
7737 codes = this.keyCodes,
7740 for (i = 0, len = codes.left.length; i < len; i++) {
7741 keys[codes.left[i]] = [-1 * pan, 0];
7743 for (i = 0, len = codes.right.length; i < len; i++) {
7744 keys[codes.right[i]] = [pan, 0];
7746 for (i = 0, len = codes.down.length; i < len; i++) {
7747 keys[codes.down[i]] = [0, pan];
7749 for (i = 0, len = codes.up.length; i < len; i++) {
7750 keys[codes.up[i]] = [0, -1 * pan];
7754 _setZoomOffset: function (zoom) {
7755 var keys = this._zoomKeys = {},
7756 codes = this.keyCodes,
7759 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
7760 keys[codes.zoomIn[i]] = zoom;
7762 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
7763 keys[codes.zoomOut[i]] = -zoom;
7767 _addHooks: function () {
7768 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
7771 _removeHooks: function () {
7772 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
7775 _onKeyDown: function (e) {
7776 var key = e.keyCode,
7779 if (key in this._panKeys) {
7781 if (map._panAnim && map._panAnim._inProgress) { return; }
7783 map.panBy(this._panKeys[key]);
7785 if (map.options.maxBounds) {
7786 map.panInsideBounds(map.options.maxBounds);
7789 } else if (key in this._zoomKeys) {
7790 map.setZoom(map.getZoom() + this._zoomKeys[key]);
7800 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
7804 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
7807 L.Handler.MarkerDrag = L.Handler.extend({
7808 initialize: function (marker) {
7809 this._marker = marker;
7812 addHooks: function () {
7813 var icon = this._marker._icon;
7814 if (!this._draggable) {
7815 this._draggable = new L.Draggable(icon, icon);
7819 .on('dragstart', this._onDragStart, this)
7820 .on('drag', this._onDrag, this)
7821 .on('dragend', this._onDragEnd, this);
7822 this._draggable.enable();
7823 L.DomUtil.addClass(this._marker._icon, 'leaflet-marker-draggable');
7826 removeHooks: function () {
7828 .off('dragstart', this._onDragStart, this)
7829 .off('drag', this._onDrag, this)
7830 .off('dragend', this._onDragEnd, this);
7832 this._draggable.disable();
7833 L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');
7836 moved: function () {
7837 return this._draggable && this._draggable._moved;
7840 _onDragStart: function () {
7847 _onDrag: function () {
7848 var marker = this._marker,
7849 shadow = marker._shadow,
7850 iconPos = L.DomUtil.getPosition(marker._icon),
7851 latlng = marker._map.layerPointToLatLng(iconPos);
7853 // update shadow position
7855 L.DomUtil.setPosition(shadow, iconPos);
7858 marker._latlng = latlng;
7861 .fire('move', {latlng: latlng})
7865 _onDragEnd: function (e) {
7868 .fire('dragend', e);
7874 * L.Control is a base class for implementing map controls. Handles positioning.
7875 * All other controls extend from this class.
7878 L.Control = L.Class.extend({
7880 position: 'topright'
7883 initialize: function (options) {
7884 L.setOptions(this, options);
7887 getPosition: function () {
7888 return this.options.position;
7891 setPosition: function (position) {
7892 var map = this._map;
7895 map.removeControl(this);
7898 this.options.position = position;
7901 map.addControl(this);
7907 getContainer: function () {
7908 return this._container;
7911 addTo: function (map) {
7914 var container = this._container = this.onAdd(map),
7915 pos = this.getPosition(),
7916 corner = map._controlCorners[pos];
7918 L.DomUtil.addClass(container, 'leaflet-control');
7920 if (pos.indexOf('bottom') !== -1) {
7921 corner.insertBefore(container, corner.firstChild);
7923 corner.appendChild(container);
7929 removeFrom: function (map) {
7930 var pos = this.getPosition(),
7931 corner = map._controlCorners[pos];
7933 corner.removeChild(this._container);
7936 if (this.onRemove) {
7943 _refocusOnMap: function () {
7945 this._map.getContainer().focus();
7950 L.control = function (options) {
7951 return new L.Control(options);
7955 // adds control-related methods to L.Map
7958 addControl: function (control) {
7959 control.addTo(this);
7963 removeControl: function (control) {
7964 control.removeFrom(this);
7968 _initControlPos: function () {
7969 var corners = this._controlCorners = {},
7971 container = this._controlContainer =
7972 L.DomUtil.create('div', l + 'control-container', this._container);
7974 function createCorner(vSide, hSide) {
7975 var className = l + vSide + ' ' + l + hSide;
7977 corners[vSide + hSide] = L.DomUtil.create('div', className, container);
7980 createCorner('top', 'left');
7981 createCorner('top', 'right');
7982 createCorner('bottom', 'left');
7983 createCorner('bottom', 'right');
7986 _clearControlPos: function () {
7987 this._container.removeChild(this._controlContainer);
7993 * L.Control.Zoom is used for the default zoom buttons on the map.
7996 L.Control.Zoom = L.Control.extend({
7998 position: 'topleft',
8000 zoomInTitle: 'Zoom in',
8002 zoomOutTitle: 'Zoom out'
8005 onAdd: function (map) {
8006 var zoomName = 'leaflet-control-zoom',
8007 container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
8011 this._zoomInButton = this._createButton(
8012 this.options.zoomInText, this.options.zoomInTitle,
8013 zoomName + '-in', container, this._zoomIn, this);
8014 this._zoomOutButton = this._createButton(
8015 this.options.zoomOutText, this.options.zoomOutTitle,
8016 zoomName + '-out', container, this._zoomOut, this);
8018 this._updateDisabled();
8019 map.on('zoomend zoomlevelschange', this._updateDisabled, this);
8024 onRemove: function (map) {
8025 map.off('zoomend zoomlevelschange', this._updateDisabled, this);
8028 _zoomIn: function (e) {
8029 this._map.zoomIn(e.shiftKey ? 3 : 1);
8032 _zoomOut: function (e) {
8033 this._map.zoomOut(e.shiftKey ? 3 : 1);
8036 _createButton: function (html, title, className, container, fn, context) {
8037 var link = L.DomUtil.create('a', className, container);
8038 link.innerHTML = html;
8042 var stop = L.DomEvent.stopPropagation;
8045 .on(link, 'click', stop)
8046 .on(link, 'mousedown', stop)
8047 .on(link, 'dblclick', stop)
8048 .on(link, 'click', L.DomEvent.preventDefault)
8049 .on(link, 'click', fn, context)
8050 .on(link, 'click', this._refocusOnMap, context);
8055 _updateDisabled: function () {
8056 var map = this._map,
8057 className = 'leaflet-disabled';
8059 L.DomUtil.removeClass(this._zoomInButton, className);
8060 L.DomUtil.removeClass(this._zoomOutButton, className);
8062 if (map._zoom === map.getMinZoom()) {
8063 L.DomUtil.addClass(this._zoomOutButton, className);
8065 if (map._zoom === map.getMaxZoom()) {
8066 L.DomUtil.addClass(this._zoomInButton, className);
8071 L.Map.mergeOptions({
8075 L.Map.addInitHook(function () {
8076 if (this.options.zoomControl) {
8077 this.zoomControl = new L.Control.Zoom();
8078 this.addControl(this.zoomControl);
8082 L.control.zoom = function (options) {
8083 return new L.Control.Zoom(options);
8089 * L.Control.Attribution is used for displaying attribution on the map (added by default).
8092 L.Control.Attribution = L.Control.extend({
8094 position: 'bottomright',
8095 prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
8098 initialize: function (options) {
8099 L.setOptions(this, options);
8101 this._attributions = {};
8104 onAdd: function (map) {
8105 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
8106 L.DomEvent.disableClickPropagation(this._container);
8108 for (var i in map._layers) {
8109 if (map._layers[i].getAttribution) {
8110 this.addAttribution(map._layers[i].getAttribution());
8115 .on('layeradd', this._onLayerAdd, this)
8116 .on('layerremove', this._onLayerRemove, this);
8120 return this._container;
8123 onRemove: function (map) {
8125 .off('layeradd', this._onLayerAdd)
8126 .off('layerremove', this._onLayerRemove);
8130 setPrefix: function (prefix) {
8131 this.options.prefix = prefix;
8136 addAttribution: function (text) {
8137 if (!text) { return; }
8139 if (!this._attributions[text]) {
8140 this._attributions[text] = 0;
8142 this._attributions[text]++;
8149 removeAttribution: function (text) {
8150 if (!text) { return; }
8152 if (this._attributions[text]) {
8153 this._attributions[text]--;
8160 _update: function () {
8161 if (!this._map) { return; }
8165 for (var i in this._attributions) {
8166 if (this._attributions[i]) {
8171 var prefixAndAttribs = [];
8173 if (this.options.prefix) {
8174 prefixAndAttribs.push(this.options.prefix);
8176 if (attribs.length) {
8177 prefixAndAttribs.push(attribs.join(', '));
8180 this._container.innerHTML = prefixAndAttribs.join(' | ');
8183 _onLayerAdd: function (e) {
8184 if (e.layer.getAttribution) {
8185 this.addAttribution(e.layer.getAttribution());
8189 _onLayerRemove: function (e) {
8190 if (e.layer.getAttribution) {
8191 this.removeAttribution(e.layer.getAttribution());
8196 L.Map.mergeOptions({
8197 attributionControl: true
8200 L.Map.addInitHook(function () {
8201 if (this.options.attributionControl) {
8202 this.attributionControl = (new L.Control.Attribution()).addTo(this);
8206 L.control.attribution = function (options) {
8207 return new L.Control.Attribution(options);
8212 * L.Control.Scale is used for displaying metric/imperial scale on the map.
8215 L.Control.Scale = L.Control.extend({
8217 position: 'bottomleft',
8221 updateWhenIdle: false
8224 onAdd: function (map) {
8227 var className = 'leaflet-control-scale',
8228 container = L.DomUtil.create('div', className),
8229 options = this.options;
8231 this._addScales(options, className, container);
8233 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8234 map.whenReady(this._update, this);
8239 onRemove: function (map) {
8240 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8243 _addScales: function (options, className, container) {
8244 if (options.metric) {
8245 this._mScale = L.DomUtil.create('div', className + '-line', container);
8247 if (options.imperial) {
8248 this._iScale = L.DomUtil.create('div', className + '-line', container);
8252 _update: function () {
8253 var bounds = this._map.getBounds(),
8254 centerLat = bounds.getCenter().lat,
8255 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
8256 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
8258 size = this._map.getSize(),
8259 options = this.options,
8263 maxMeters = dist * (options.maxWidth / size.x);
8266 this._updateScales(options, maxMeters);
8269 _updateScales: function (options, maxMeters) {
8270 if (options.metric && maxMeters) {
8271 this._updateMetric(maxMeters);
8274 if (options.imperial && maxMeters) {
8275 this._updateImperial(maxMeters);
8279 _updateMetric: function (maxMeters) {
8280 var meters = this._getRoundNum(maxMeters);
8282 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
8283 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
8286 _updateImperial: function (maxMeters) {
8287 var maxFeet = maxMeters * 3.2808399,
8288 scale = this._iScale,
8289 maxMiles, miles, feet;
8291 if (maxFeet > 5280) {
8292 maxMiles = maxFeet / 5280;
8293 miles = this._getRoundNum(maxMiles);
8295 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
8296 scale.innerHTML = miles + ' mi';
8299 feet = this._getRoundNum(maxFeet);
8301 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
8302 scale.innerHTML = feet + ' ft';
8306 _getScaleWidth: function (ratio) {
8307 return Math.round(this.options.maxWidth * ratio) - 10;
8310 _getRoundNum: function (num) {
8311 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
8314 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
8320 L.control.scale = function (options) {
8321 return new L.Control.Scale(options);
8326 * L.Control.Layers is a control to allow users to switch between different layers on the map.
8329 L.Control.Layers = L.Control.extend({
8332 position: 'topright',
8336 initialize: function (baseLayers, overlays, options) {
8337 L.setOptions(this, options);
8340 this._lastZIndex = 0;
8341 this._handlingClick = false;
8343 for (var i in baseLayers) {
8344 this._addLayer(baseLayers[i], i);
8347 for (i in overlays) {
8348 this._addLayer(overlays[i], i, true);
8352 onAdd: function (map) {
8357 .on('layeradd', this._onLayerChange, this)
8358 .on('layerremove', this._onLayerChange, this);
8360 return this._container;
8363 onRemove: function (map) {
8365 .off('layeradd', this._onLayerChange, this)
8366 .off('layerremove', this._onLayerChange, this);
8369 addBaseLayer: function (layer, name) {
8370 this._addLayer(layer, name);
8375 addOverlay: function (layer, name) {
8376 this._addLayer(layer, name, true);
8381 removeLayer: function (layer) {
8382 var id = L.stamp(layer);
8383 delete this._layers[id];
8388 _initLayout: function () {
8389 var className = 'leaflet-control-layers',
8390 container = this._container = L.DomUtil.create('div', className);
8392 //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
8393 container.setAttribute('aria-haspopup', true);
8395 if (!L.Browser.touch) {
8397 .disableClickPropagation(container)
8398 .disableScrollPropagation(container);
8400 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
8403 var form = this._form = L.DomUtil.create('form', className + '-list');
8405 if (this.options.collapsed) {
8406 if (!L.Browser.android) {
8408 .on(container, 'mouseover', this._expand, this)
8409 .on(container, 'mouseout', this._collapse, this);
8411 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
8413 link.title = 'Layers';
8415 if (L.Browser.touch) {
8417 .on(link, 'click', L.DomEvent.stop)
8418 .on(link, 'click', this._expand, this);
8421 L.DomEvent.on(link, 'focus', this._expand, this);
8423 //Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033
8424 L.DomEvent.on(form, 'click', function () {
8425 setTimeout(L.bind(this._onInputClick, this), 0);
8428 this._map.on('click', this._collapse, this);
8429 // TODO keyboard accessibility
8434 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
8435 this._separator = L.DomUtil.create('div', className + '-separator', form);
8436 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
8438 container.appendChild(form);
8441 _addLayer: function (layer, name, overlay) {
8442 var id = L.stamp(layer);
8444 this._layers[id] = {
8450 if (this.options.autoZIndex && layer.setZIndex) {
8452 layer.setZIndex(this._lastZIndex);
8456 _update: function () {
8457 if (!this._container) {
8461 this._baseLayersList.innerHTML = '';
8462 this._overlaysList.innerHTML = '';
8464 var baseLayersPresent = false,
8465 overlaysPresent = false,
8468 for (i in this._layers) {
8469 obj = this._layers[i];
8471 overlaysPresent = overlaysPresent || obj.overlay;
8472 baseLayersPresent = baseLayersPresent || !obj.overlay;
8475 this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
8478 _onLayerChange: function (e) {
8479 var obj = this._layers[L.stamp(e.layer)];
8481 if (!obj) { return; }
8483 if (!this._handlingClick) {
8487 var type = obj.overlay ?
8488 (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
8489 (e.type === 'layeradd' ? 'baselayerchange' : null);
8492 this._map.fire(type, obj);
8496 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
8497 _createRadioElement: function (name, checked) {
8499 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
8501 radioHtml += ' checked="checked"';
8505 var radioFragment = document.createElement('div');
8506 radioFragment.innerHTML = radioHtml;
8508 return radioFragment.firstChild;
8511 _addItem: function (obj) {
8512 var label = document.createElement('label'),
8514 checked = this._map.hasLayer(obj.layer);
8517 input = document.createElement('input');
8518 input.type = 'checkbox';
8519 input.className = 'leaflet-control-layers-selector';
8520 input.defaultChecked = checked;
8522 input = this._createRadioElement('leaflet-base-layers', checked);
8525 input.layerId = L.stamp(obj.layer);
8527 L.DomEvent.on(input, 'click', this._onInputClick, this);
8529 var name = document.createElement('span');
8530 name.innerHTML = ' ' + obj.name;
8532 label.appendChild(input);
8533 label.appendChild(name);
8535 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
8536 container.appendChild(label);
8541 _onInputClick: function () {
8543 inputs = this._form.getElementsByTagName('input'),
8544 inputsLen = inputs.length;
8546 this._handlingClick = true;
8548 for (i = 0; i < inputsLen; i++) {
8550 obj = this._layers[input.layerId];
8552 if (input.checked && !this._map.hasLayer(obj.layer)) {
8553 this._map.addLayer(obj.layer);
8555 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
8556 this._map.removeLayer(obj.layer);
8560 this._handlingClick = false;
8562 this._refocusOnMap();
8565 _expand: function () {
8566 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
8569 _collapse: function () {
8570 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
8574 L.control.layers = function (baseLayers, overlays, options) {
8575 return new L.Control.Layers(baseLayers, overlays, options);
8580 * L.PosAnimation is used by Leaflet internally for pan animations.
8583 L.PosAnimation = L.Class.extend({
8584 includes: L.Mixin.Events,
8586 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8590 this._inProgress = true;
8591 this._newPos = newPos;
8595 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
8596 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
8598 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8599 L.DomUtil.setPosition(el, newPos);
8601 // toggle reflow, Chrome flickers for some reason if you don't do this
8602 L.Util.falseFn(el.offsetWidth);
8604 // there's no native way to track value updates of transitioned properties, so we imitate this
8605 this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
8609 if (!this._inProgress) { return; }
8611 // if we just removed the transition property, the element would jump to its final position,
8612 // so we need to make it stay at the current position
8614 L.DomUtil.setPosition(this._el, this._getPos());
8615 this._onTransitionEnd();
8616 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
8619 _onStep: function () {
8620 var stepPos = this._getPos();
8622 this._onTransitionEnd();
8625 // jshint camelcase: false
8626 // make L.DomUtil.getPosition return intermediate position value during animation
8627 this._el._leaflet_pos = stepPos;
8632 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
8633 // we need to parse computed style (in case of transform it returns matrix string)
8635 _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
8637 _getPos: function () {
8638 var left, top, matches,
8640 style = window.getComputedStyle(el);
8642 if (L.Browser.any3d) {
8643 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
8644 if (!matches) { return; }
8645 left = parseFloat(matches[1]);
8646 top = parseFloat(matches[2]);
8648 left = parseFloat(style.left);
8649 top = parseFloat(style.top);
8652 return new L.Point(left, top, true);
8655 _onTransitionEnd: function () {
8656 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8658 if (!this._inProgress) { return; }
8659 this._inProgress = false;
8661 this._el.style[L.DomUtil.TRANSITION] = '';
8663 // jshint camelcase: false
8664 // make sure L.DomUtil.getPosition returns the final position value after animation
8665 this._el._leaflet_pos = this._newPos;
8667 clearInterval(this._stepTimer);
8669 this.fire('step').fire('end');
8676 * Extends L.Map to handle panning animations.
8681 setView: function (center, zoom, options) {
8683 zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
8684 center = this._limitCenter(L.latLng(center), zoom, this.options.maxBounds);
8685 options = options || {};
8687 if (this._panAnim) {
8688 this._panAnim.stop();
8691 if (this._loaded && !options.reset && options !== true) {
8693 if (options.animate !== undefined) {
8694 options.zoom = L.extend({animate: options.animate}, options.zoom);
8695 options.pan = L.extend({animate: options.animate}, options.pan);
8698 // try animating pan or zoom
8699 var animated = (this._zoom !== zoom) ?
8700 this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
8701 this._tryAnimatedPan(center, options.pan);
8704 // prevent resize handler call, the view will refresh after animation anyway
8705 clearTimeout(this._sizeTimer);
8710 // animation didn't start, just reset the map view
8711 this._resetView(center, zoom);
8716 panBy: function (offset, options) {
8717 offset = L.point(offset).round();
8718 options = options || {};
8720 if (!offset.x && !offset.y) {
8724 if (!this._panAnim) {
8725 this._panAnim = new L.PosAnimation();
8728 'step': this._onPanTransitionStep,
8729 'end': this._onPanTransitionEnd
8733 // don't fire movestart if animating inertia
8734 if (!options.noMoveStart) {
8735 this.fire('movestart');
8738 // animate pan unless animate: false specified
8739 if (options.animate !== false) {
8740 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
8742 var newPos = this._getMapPanePos().subtract(offset);
8743 this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
8745 this._rawPanBy(offset);
8746 this.fire('move').fire('moveend');
8752 _onPanTransitionStep: function () {
8756 _onPanTransitionEnd: function () {
8757 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
8758 this.fire('moveend');
8761 _tryAnimatedPan: function (center, options) {
8762 // difference between the new and current centers in pixels
8763 var offset = this._getCenterOffset(center)._floor();
8765 // don't animate too far unless animate: true specified in options
8766 if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
8768 this.panBy(offset, options);
8776 * L.PosAnimation fallback implementation that powers Leaflet pan animations
8777 * in browsers that don't support CSS3 Transitions.
8780 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8782 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8786 this._inProgress = true;
8787 this._duration = duration || 0.25;
8788 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8790 this._startPos = L.DomUtil.getPosition(el);
8791 this._offset = newPos.subtract(this._startPos);
8792 this._startTime = +new Date();
8800 if (!this._inProgress) { return; }
8806 _animate: function () {
8808 this._animId = L.Util.requestAnimFrame(this._animate, this);
8812 _step: function () {
8813 var elapsed = (+new Date()) - this._startTime,
8814 duration = this._duration * 1000;
8816 if (elapsed < duration) {
8817 this._runFrame(this._easeOut(elapsed / duration));
8824 _runFrame: function (progress) {
8825 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8826 L.DomUtil.setPosition(this._el, pos);
8831 _complete: function () {
8832 L.Util.cancelAnimFrame(this._animId);
8834 this._inProgress = false;
8838 _easeOut: function (t) {
8839 return 1 - Math.pow(1 - t, this._easeOutPower);
8845 * Extends L.Map to handle zoom animations.
8848 L.Map.mergeOptions({
8849 zoomAnimation: true,
8850 zoomAnimationThreshold: 4
8853 if (L.DomUtil.TRANSITION) {
8855 L.Map.addInitHook(function () {
8856 // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
8857 this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
8858 L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
8860 // zoom transitions run with the same duration for all layers, so if one of transitionend events
8861 // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
8862 if (this._zoomAnimated) {
8863 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8868 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8870 _catchTransitionEnd: function (e) {
8871 if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
8872 this._onZoomTransitionEnd();
8876 _nothingToAnimate: function () {
8877 return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
8880 _tryAnimatedZoom: function (center, zoom, options) {
8882 if (this._animatingZoom) { return true; }
8884 options = options || {};
8886 // don't animate if disabled, not supported or zoom difference is too large
8887 if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
8888 Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
8890 // offset is the pixel coords of the zoom origin relative to the current center
8891 var scale = this.getZoomScale(zoom),
8892 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
8893 origin = this._getCenterLayerPoint()._add(offset);
8895 // don't animate if the zoom origin isn't within one screen from the current center, unless forced
8896 if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
8902 this._animateZoom(center, zoom, origin, scale, null, true);
8907 _animateZoom: function (center, zoom, origin, scale, delta, backwards, forTouchZoom) {
8909 if (!forTouchZoom) {
8910 this._animatingZoom = true;
8913 // put transform transition on all layers with leaflet-zoom-animated class
8914 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8916 // remember what center/zoom to set after animation
8917 this._animateToCenter = center;
8918 this._animateToZoom = zoom;
8920 // disable any dragging during animation
8922 L.Draggable._disabled = true;
8925 L.Util.requestAnimFrame(function () {
8926 this.fire('zoomanim', {
8932 backwards: backwards
8934 // horrible hack to work around a Chrome bug https://github.com/Leaflet/Leaflet/issues/3689
8935 setTimeout(L.bind(this._onZoomTransitionEnd, this), 250);
8939 _onZoomTransitionEnd: function () {
8940 if (!this._animatingZoom) { return; }
8942 this._animatingZoom = false;
8944 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8946 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8949 L.Draggable._disabled = false;
8956 Zoom animation logic for L.TileLayer.
8959 L.TileLayer.include({
8960 _animateZoom: function (e) {
8961 if (!this._animating) {
8962 this._animating = true;
8963 this._prepareBgBuffer();
8966 var bg = this._bgBuffer,
8967 transform = L.DomUtil.TRANSFORM,
8968 initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
8969 scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
8971 bg.style[transform] = e.backwards ?
8972 scaleStr + ' ' + initialTransform :
8973 initialTransform + ' ' + scaleStr;
8976 _endZoomAnim: function () {
8977 var front = this._tileContainer,
8978 bg = this._bgBuffer;
8980 front.style.visibility = '';
8981 front.parentNode.appendChild(front); // Bring to fore
8984 L.Util.falseFn(bg.offsetWidth);
8986 var zoom = this._map.getZoom();
8987 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
8988 this._clearBgBuffer();
8991 this._animating = false;
8994 _clearBgBuffer: function () {
8995 var map = this._map;
8997 if (map && !map._animatingZoom && !map.touchZoom._zooming) {
8998 this._bgBuffer.innerHTML = '';
8999 this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
9003 _prepareBgBuffer: function () {
9005 var front = this._tileContainer,
9006 bg = this._bgBuffer;
9008 // if foreground layer doesn't have many tiles but bg layer does,
9009 // keep the existing bg layer and just zoom it some more
9011 var bgLoaded = this._getLoadedTilesPercentage(bg),
9012 frontLoaded = this._getLoadedTilesPercentage(front);
9014 if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
9016 front.style.visibility = 'hidden';
9017 this._stopLoadingImages(front);
9021 // prepare the buffer to become the front tile pane
9022 bg.style.visibility = 'hidden';
9023 bg.style[L.DomUtil.TRANSFORM] = '';
9025 // switch out the current layer to be the new bg layer (and vice-versa)
9026 this._tileContainer = bg;
9027 bg = this._bgBuffer = front;
9029 this._stopLoadingImages(bg);
9031 //prevent bg buffer from clearing right after zoom
9032 clearTimeout(this._clearBgBufferTimer);
9035 _getLoadedTilesPercentage: function (container) {
9036 var tiles = container.getElementsByTagName('img'),
9039 for (i = 0, len = tiles.length; i < len; i++) {
9040 if (tiles[i].complete) {
9047 // stops loading all tiles in the background layer
9048 _stopLoadingImages: function (container) {
9049 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
9052 for (i = 0, len = tiles.length; i < len; i++) {
9055 if (!tile.complete) {
9056 tile.onload = L.Util.falseFn;
9057 tile.onerror = L.Util.falseFn;
9058 tile.src = L.Util.emptyImageUrl;
9060 tile.parentNode.removeChild(tile);
9068 * Provides L.Map with convenient shortcuts for using browser geolocation features.
9072 _defaultLocateOptions: {
9078 enableHighAccuracy: false
9081 locate: function (/*Object*/ options) {
9083 options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
9085 if (!navigator.geolocation) {
9086 this._handleGeolocationError({
9088 message: 'Geolocation not supported.'
9093 var onResponse = L.bind(this._handleGeolocationResponse, this),
9094 onError = L.bind(this._handleGeolocationError, this);
9096 if (options.watch) {
9097 this._locationWatchId =
9098 navigator.geolocation.watchPosition(onResponse, onError, options);
9100 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
9105 stopLocate: function () {
9106 if (navigator.geolocation) {
9107 navigator.geolocation.clearWatch(this._locationWatchId);
9109 if (this._locateOptions) {
9110 this._locateOptions.setView = false;
9115 _handleGeolocationError: function (error) {
9117 message = error.message ||
9118 (c === 1 ? 'permission denied' :
9119 (c === 2 ? 'position unavailable' : 'timeout'));
9121 if (this._locateOptions.setView && !this._loaded) {
9125 this.fire('locationerror', {
9127 message: 'Geolocation error: ' + message + '.'
9131 _handleGeolocationResponse: function (pos) {
9132 var lat = pos.coords.latitude,
9133 lng = pos.coords.longitude,
9134 latlng = new L.LatLng(lat, lng),
9136 latAccuracy = 180 * pos.coords.accuracy / 40075017,
9137 lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
9139 bounds = L.latLngBounds(
9140 [lat - latAccuracy, lng - lngAccuracy],
9141 [lat + latAccuracy, lng + lngAccuracy]),
9143 options = this._locateOptions;
9145 if (options.setView) {
9146 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
9147 this.setView(latlng, zoom);
9153 timestamp: pos.timestamp
9156 for (var i in pos.coords) {
9157 if (typeof pos.coords[i] === 'number') {
9158 data[i] = pos.coords[i];
9162 this.fire('locationfound', data);
9167 }(window, document));