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('&');
138 compileTemplate: function (str, data) {
139 // based on https://gist.github.com/padolsey/6008842
140 str = str.replace(/"/g, '\\\"');
141 str = str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
142 return '" + o["' + key + '"]' + (typeof data[key] === 'function' ? '(o)' : '') + ' + "';
145 return new Function('o', 'return "' + str + '";');
148 template: function (str, data) {
149 var cache = L.Util._templateCache = L.Util._templateCache || {};
150 cache[str] = cache[str] || L.Util.compileTemplate(str, data);
151 return cache[str](data);
154 isArray: Array.isArray || function (obj) {
155 return (Object.prototype.toString.call(obj) === '[object Array]');
158 emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
163 // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
165 function getPrefixed(name) {
167 prefixes = ['webkit', 'moz', 'o', 'ms'];
169 for (i = 0; i < prefixes.length && !fn; i++) {
170 fn = window[prefixes[i] + name];
178 function timeoutDefer(fn) {
179 var time = +new Date(),
180 timeToCall = Math.max(0, 16 - (time - lastTime));
182 lastTime = time + timeToCall;
183 return window.setTimeout(fn, timeToCall);
186 var requestFn = window.requestAnimationFrame ||
187 getPrefixed('RequestAnimationFrame') || timeoutDefer;
189 var cancelFn = window.cancelAnimationFrame ||
190 getPrefixed('CancelAnimationFrame') ||
191 getPrefixed('CancelRequestAnimationFrame') ||
192 function (id) { window.clearTimeout(id); };
195 L.Util.requestAnimFrame = function (fn, context, immediate, element) {
196 fn = L.bind(fn, context);
198 if (immediate && requestFn === timeoutDefer) {
201 return requestFn.call(window, fn, element);
205 L.Util.cancelAnimFrame = function (id) {
207 cancelFn.call(window, id);
213 // shortcuts for most used utility functions
214 L.extend = L.Util.extend;
215 L.bind = L.Util.bind;
216 L.stamp = L.Util.stamp;
217 L.setOptions = L.Util.setOptions;
221 * L.Class powers the OOP facilities of the library.
222 * Thanks to John Resig and Dean Edwards for inspiration!
225 L.Class = function () {};
227 L.Class.extend = function (props) {
229 // extended class with the new prototype
230 var NewClass = function () {
232 // call the constructor
233 if (this.initialize) {
234 this.initialize.apply(this, arguments);
237 // call all constructor hooks
238 if (this._initHooks) {
239 this.callInitHooks();
243 // instantiate class without calling constructor
244 var F = function () {};
245 F.prototype = this.prototype;
248 proto.constructor = NewClass;
250 NewClass.prototype = proto;
252 //inherit parent's statics
253 for (var i in this) {
254 if (this.hasOwnProperty(i) && i !== 'prototype') {
255 NewClass[i] = this[i];
259 // mix static properties into the class
261 L.extend(NewClass, props.statics);
262 delete props.statics;
265 // mix includes into the prototype
266 if (props.includes) {
267 L.Util.extend.apply(null, [proto].concat(props.includes));
268 delete props.includes;
272 if (props.options && proto.options) {
273 props.options = L.extend({}, proto.options, props.options);
276 // mix given properties into the prototype
277 L.extend(proto, props);
279 proto._initHooks = [];
282 // jshint camelcase: false
283 NewClass.__super__ = parent.prototype;
285 // add method for calling all hooks
286 proto.callInitHooks = function () {
288 if (this._initHooksCalled) { return; }
290 if (parent.prototype.callInitHooks) {
291 parent.prototype.callInitHooks.call(this);
294 this._initHooksCalled = true;
296 for (var i = 0, len = proto._initHooks.length; i < len; i++) {
297 proto._initHooks[i].call(this);
305 // method for adding properties to prototype
306 L.Class.include = function (props) {
307 L.extend(this.prototype, props);
310 // merge new default options to the Class
311 L.Class.mergeOptions = function (options) {
312 L.extend(this.prototype.options, options);
315 // add a constructor hook
316 L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
317 var args = Array.prototype.slice.call(arguments, 1);
319 var init = typeof fn === 'function' ? fn : function () {
320 this[fn].apply(this, args);
323 this.prototype._initHooks = this.prototype._initHooks || [];
324 this.prototype._initHooks.push(init);
329 * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
332 var eventsKey = '_leaflet_events';
338 addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
340 // types can be a map of types/handlers
341 if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
343 var events = this[eventsKey] = this[eventsKey] || {},
344 contextId = context && context !== this && L.stamp(context),
345 i, len, event, type, indexKey, indexLenKey, typeIndex;
347 // types can be a string of space-separated words
348 types = L.Util.splitWords(types);
350 for (i = 0, len = types.length; i < len; i++) {
353 context: context || this
358 // store listeners of a particular context in a separate hash (if it has an id)
359 // gives a major performance boost when removing thousands of map layers
361 indexKey = type + '_idx';
362 indexLenKey = indexKey + '_len';
364 typeIndex = events[indexKey] = events[indexKey] || {};
366 if (!typeIndex[contextId]) {
367 typeIndex[contextId] = [];
369 // keep track of the number of keys in the index to quickly check if it's empty
370 events[indexLenKey] = (events[indexLenKey] || 0) + 1;
373 typeIndex[contextId].push(event);
377 events[type] = events[type] || [];
378 events[type].push(event);
385 hasEventListeners: function (type) { // (String) -> Boolean
386 var events = this[eventsKey];
387 return !!events && ((type in events && events[type].length > 0) ||
388 (type + '_idx' in events && events[type + '_idx_len'] > 0));
391 removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
393 if (!this[eventsKey]) {
398 return this.clearAllEventListeners();
401 if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
403 var events = this[eventsKey],
404 contextId = context && context !== this && L.stamp(context),
405 i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
407 types = L.Util.splitWords(types);
409 for (i = 0, len = types.length; i < len; i++) {
411 indexKey = type + '_idx';
412 indexLenKey = indexKey + '_len';
414 typeIndex = events[indexKey];
417 // clear all listeners for a type if function isn't specified
419 delete events[indexKey];
420 delete events[indexLenKey];
423 listeners = contextId && typeIndex ? typeIndex[contextId] : events[type];
426 for (j = listeners.length - 1; j >= 0; j--) {
427 if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
428 removed = listeners.splice(j, 1);
429 // set the old action to a no-op, because it is possible
430 // that the listener is being iterated over as part of a dispatch
431 removed[0].action = L.Util.falseFn;
435 if (context && typeIndex && (listeners.length === 0)) {
436 delete typeIndex[contextId];
437 events[indexLenKey]--;
446 clearAllEventListeners: function () {
447 delete this[eventsKey];
451 fireEvent: function (type, data) { // (String[, Object])
452 if (!this.hasEventListeners(type)) {
456 var event = L.Util.extend({}, data, { type: type, target: this });
458 var events = this[eventsKey],
459 listeners, i, len, typeIndex, contextId;
462 // make sure adding/removing listeners inside other listeners won't cause infinite loop
463 listeners = events[type].slice();
465 for (i = 0, len = listeners.length; i < len; i++) {
466 listeners[i].action.call(listeners[i].context, event);
470 // fire event for the context-indexed listeners as well
471 typeIndex = events[type + '_idx'];
473 for (contextId in typeIndex) {
474 listeners = typeIndex[contextId].slice();
477 for (i = 0, len = listeners.length; i < len; i++) {
478 listeners[i].action.call(listeners[i].context, event);
486 addOneTimeEventListener: function (types, fn, context) {
488 if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
490 var handler = L.bind(function () {
492 .removeEventListener(types, fn, context)
493 .removeEventListener(types, handler, context);
497 .addEventListener(types, fn, context)
498 .addEventListener(types, handler, context);
502 L.Mixin.Events.on = L.Mixin.Events.addEventListener;
503 L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
504 L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
505 L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
509 * L.Browser handles different browser and feature detections for internal Leaflet use.
514 var ie = 'ActiveXObject' in window,
515 ielt9 = ie && !document.addEventListener,
517 // terrible browser detection to work around Safari / iOS / Android browser bugs
518 ua = navigator.userAgent.toLowerCase(),
519 webkit = ua.indexOf('webkit') !== -1,
520 chrome = ua.indexOf('chrome') !== -1,
521 phantomjs = ua.indexOf('phantom') !== -1,
522 android = ua.indexOf('android') !== -1,
523 android23 = ua.search('android [23]') !== -1,
524 gecko = ua.indexOf('gecko') !== -1,
526 mobile = typeof orientation !== undefined + '',
527 msPointer = window.navigator && window.navigator.msPointerEnabled &&
528 window.navigator.msMaxTouchPoints && !window.PointerEvent,
529 pointer = (window.PointerEvent && window.navigator.pointerEnabled && window.navigator.maxTouchPoints) ||
531 retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
532 ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
533 window.matchMedia('(min-resolution:144dpi)').matches),
535 doc = document.documentElement,
536 ie3d = ie && ('transition' in doc.style),
537 webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
538 gecko3d = 'MozPerspective' in doc.style,
539 opera3d = 'OTransition' in doc.style,
540 any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
543 // PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch.
544 // https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151
546 var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
548 var startName = 'ontouchstart';
550 // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.Pointer) or WebKit, etc.
551 if (pointer || (startName in doc)) {
556 var div = document.createElement('div'),
559 if (!div.setAttribute) {
562 div.setAttribute(startName, 'return;');
564 if (typeof div[startName] === 'function') {
568 div.removeAttribute(startName);
579 gecko: gecko && !webkit && !window.opera && !ie,
582 android23: android23,
593 mobileWebkit: mobile && webkit,
594 mobileWebkit3d: mobile && webkit3d,
595 mobileOpera: mobile && window.opera,
598 msPointer: msPointer,
608 * L.Point represents a point with x and y coordinates.
611 L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
612 this.x = (round ? Math.round(x) : x);
613 this.y = (round ? Math.round(y) : y);
616 L.Point.prototype = {
619 return new L.Point(this.x, this.y);
622 // non-destructive, returns a new point
623 add: function (point) {
624 return this.clone()._add(L.point(point));
627 // destructive, used directly for performance in situations where it's safe to modify existing point
628 _add: function (point) {
634 subtract: function (point) {
635 return this.clone()._subtract(L.point(point));
638 _subtract: function (point) {
644 divideBy: function (num) {
645 return this.clone()._divideBy(num);
648 _divideBy: function (num) {
654 multiplyBy: function (num) {
655 return this.clone()._multiplyBy(num);
658 _multiplyBy: function (num) {
665 return this.clone()._round();
668 _round: function () {
669 this.x = Math.round(this.x);
670 this.y = Math.round(this.y);
675 return this.clone()._floor();
678 _floor: function () {
679 this.x = Math.floor(this.x);
680 this.y = Math.floor(this.y);
684 distanceTo: function (point) {
685 point = L.point(point);
687 var x = point.x - this.x,
688 y = point.y - this.y;
690 return Math.sqrt(x * x + y * y);
693 equals: function (point) {
694 point = L.point(point);
696 return point.x === this.x &&
700 contains: function (point) {
701 point = L.point(point);
703 return Math.abs(point.x) <= Math.abs(this.x) &&
704 Math.abs(point.y) <= Math.abs(this.y);
707 toString: function () {
709 L.Util.formatNum(this.x) + ', ' +
710 L.Util.formatNum(this.y) + ')';
714 L.point = function (x, y, round) {
715 if (x instanceof L.Point) {
718 if (L.Util.isArray(x)) {
719 return new L.Point(x[0], x[1]);
721 if (x === undefined || x === null) {
724 return new L.Point(x, y, round);
729 * L.Bounds represents a rectangular area on the screen in pixel coordinates.
732 L.Bounds = function (a, b) { //(Point, Point) or Point[]
735 var points = b ? [a, b] : a;
737 for (var i = 0, len = points.length; i < len; i++) {
738 this.extend(points[i]);
742 L.Bounds.prototype = {
743 // extend the bounds to contain the given point
744 extend: function (point) { // (Point)
745 point = L.point(point);
747 if (!this.min && !this.max) {
748 this.min = point.clone();
749 this.max = point.clone();
751 this.min.x = Math.min(point.x, this.min.x);
752 this.max.x = Math.max(point.x, this.max.x);
753 this.min.y = Math.min(point.y, this.min.y);
754 this.max.y = Math.max(point.y, this.max.y);
759 getCenter: function (round) { // (Boolean) -> Point
761 (this.min.x + this.max.x) / 2,
762 (this.min.y + this.max.y) / 2, round);
765 getBottomLeft: function () { // -> Point
766 return new L.Point(this.min.x, this.max.y);
769 getTopRight: function () { // -> Point
770 return new L.Point(this.max.x, this.min.y);
773 getSize: function () {
774 return this.max.subtract(this.min);
777 contains: function (obj) { // (Bounds) or (Point) -> Boolean
780 if (typeof obj[0] === 'number' || obj instanceof L.Point) {
786 if (obj instanceof L.Bounds) {
793 return (min.x >= this.min.x) &&
794 (max.x <= this.max.x) &&
795 (min.y >= this.min.y) &&
796 (max.y <= this.max.y);
799 intersects: function (bounds) { // (Bounds) -> Boolean
800 bounds = L.bounds(bounds);
806 xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
807 yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
809 return xIntersects && yIntersects;
812 isValid: function () {
813 return !!(this.min && this.max);
817 L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
818 if (!a || a instanceof L.Bounds) {
821 return new L.Bounds(a, b);
826 * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
829 L.Transformation = function (a, b, c, d) {
836 L.Transformation.prototype = {
837 transform: function (point, scale) { // (Point, Number) -> Point
838 return this._transform(point.clone(), scale);
841 // destructive transform (faster)
842 _transform: function (point, scale) {
844 point.x = scale * (this._a * point.x + this._b);
845 point.y = scale * (this._c * point.y + this._d);
849 untransform: function (point, scale) {
852 (point.x / scale - this._b) / this._a,
853 (point.y / scale - this._d) / this._c);
859 * L.DomUtil contains various utility functions for working with DOM.
864 return (typeof id === 'string' ? document.getElementById(id) : id);
867 getStyle: function (el, style) {
869 var value = el.style[style];
871 if (!value && el.currentStyle) {
872 value = el.currentStyle[style];
875 if ((!value || value === 'auto') && document.defaultView) {
876 var css = document.defaultView.getComputedStyle(el, null);
877 value = css ? css[style] : null;
880 return value === 'auto' ? null : value;
883 getViewportOffset: function (element) {
888 docBody = document.body,
889 docEl = document.documentElement,
893 top += el.offsetTop || 0;
894 left += el.offsetLeft || 0;
897 top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
898 left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
900 pos = L.DomUtil.getStyle(el, 'position');
902 if (el.offsetParent === docBody && pos === 'absolute') { break; }
904 if (pos === 'fixed') {
905 top += docBody.scrollTop || docEl.scrollTop || 0;
906 left += docBody.scrollLeft || docEl.scrollLeft || 0;
910 if (pos === 'relative' && !el.offsetLeft) {
911 var width = L.DomUtil.getStyle(el, 'width'),
912 maxWidth = L.DomUtil.getStyle(el, 'max-width'),
913 r = el.getBoundingClientRect();
915 if (width !== 'none' || maxWidth !== 'none') {
916 left += r.left + el.clientLeft;
919 //calculate full y offset since we're breaking out of the loop
920 top += r.top + (docBody.scrollTop || docEl.scrollTop || 0);
925 el = el.offsetParent;
932 if (el === docBody) { break; }
934 top -= el.scrollTop || 0;
935 left -= el.scrollLeft || 0;
940 return new L.Point(left, top);
943 documentIsLtr: function () {
944 if (!L.DomUtil._docIsLtrCached) {
945 L.DomUtil._docIsLtrCached = true;
946 L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
948 return L.DomUtil._docIsLtr;
951 create: function (tagName, className, container) {
953 var el = document.createElement(tagName);
954 el.className = className;
957 container.appendChild(el);
963 hasClass: function (el, name) {
964 if (el.classList !== undefined) {
965 return el.classList.contains(name);
967 var className = L.DomUtil._getClass(el);
968 return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
971 addClass: function (el, name) {
972 if (el.classList !== undefined) {
973 var classes = L.Util.splitWords(name);
974 for (var i = 0, len = classes.length; i < len; i++) {
975 el.classList.add(classes[i]);
977 } else if (!L.DomUtil.hasClass(el, name)) {
978 var className = L.DomUtil._getClass(el);
979 L.DomUtil._setClass(el, (className ? className + ' ' : '') + name);
983 removeClass: function (el, name) {
984 if (el.classList !== undefined) {
985 el.classList.remove(name);
987 L.DomUtil._setClass(el, L.Util.trim((' ' + L.DomUtil._getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
991 _setClass: function (el, name) {
992 if (el.className.baseVal === undefined) {
995 // in case of SVG element
996 el.className.baseVal = name;
1000 _getClass: function (el) {
1001 return el.className.baseVal === undefined ? el.className : el.className.baseVal;
1004 setOpacity: function (el, value) {
1006 if ('opacity' in el.style) {
1007 el.style.opacity = value;
1009 } else if ('filter' in el.style) {
1012 filterName = 'DXImageTransform.Microsoft.Alpha';
1014 // filters collection throws an error if we try to retrieve a filter that doesn't exist
1016 filter = el.filters.item(filterName);
1018 // don't set opacity to 1 if we haven't already set an opacity,
1019 // it isn't needed and breaks transparent pngs.
1020 if (value === 1) { return; }
1023 value = Math.round(value * 100);
1026 filter.Enabled = (value !== 100);
1027 filter.Opacity = value;
1029 el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
1034 testProp: function (props) {
1036 var style = document.documentElement.style;
1038 for (var i = 0; i < props.length; i++) {
1039 if (props[i] in style) {
1046 getTranslateString: function (point) {
1047 // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
1048 // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
1049 // (same speed either way), Opera 12 doesn't support translate3d
1051 var is3d = L.Browser.webkit3d,
1052 open = 'translate' + (is3d ? '3d' : '') + '(',
1053 close = (is3d ? ',0' : '') + ')';
1055 return open + point.x + 'px,' + point.y + 'px' + close;
1058 getScaleString: function (scale, origin) {
1060 var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
1061 scaleStr = ' scale(' + scale + ') ';
1063 return preTranslateStr + scaleStr;
1066 setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
1068 // jshint camelcase: false
1069 el._leaflet_pos = point;
1071 if (!disable3D && L.Browser.any3d) {
1072 el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
1074 // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
1075 if (L.Browser.mobileWebkit3d) {
1076 el.style.WebkitBackfaceVisibility = 'hidden';
1079 el.style.left = point.x + 'px';
1080 el.style.top = point.y + 'px';
1084 getPosition: function (el) {
1085 // this method is only used for elements previously positioned using setPosition,
1086 // so it's safe to cache the position for performance
1088 // jshint camelcase: false
1089 return el._leaflet_pos;
1094 // prefix style property names
1096 L.DomUtil.TRANSFORM = L.DomUtil.testProp(
1097 ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
1099 // webkitTransition comes first because some browser versions that drop vendor prefix don't do
1100 // the same for the transitionend event, in particular the Android 4.1 stock browser
1102 L.DomUtil.TRANSITION = L.DomUtil.testProp(
1103 ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
1105 L.DomUtil.TRANSITION_END =
1106 L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
1107 L.DomUtil.TRANSITION + 'End' : 'transitionend';
1110 if ('onselectstart' in document) {
1111 L.extend(L.DomUtil, {
1112 disableTextSelection: function () {
1113 L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
1116 enableTextSelection: function () {
1117 L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
1121 var userSelectProperty = L.DomUtil.testProp(
1122 ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
1124 L.extend(L.DomUtil, {
1125 disableTextSelection: function () {
1126 if (userSelectProperty) {
1127 var style = document.documentElement.style;
1128 this._userSelect = style[userSelectProperty];
1129 style[userSelectProperty] = 'none';
1133 enableTextSelection: function () {
1134 if (userSelectProperty) {
1135 document.documentElement.style[userSelectProperty] = this._userSelect;
1136 delete this._userSelect;
1142 L.extend(L.DomUtil, {
1143 disableImageDrag: function () {
1144 L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
1147 enableImageDrag: function () {
1148 L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
1155 * L.LatLng represents a geographical point with latitude and longitude coordinates.
1158 L.LatLng = function (lat, lng, alt) { // (Number, Number, Number)
1159 lat = parseFloat(lat);
1160 lng = parseFloat(lng);
1162 if (isNaN(lat) || isNaN(lng)) {
1163 throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
1169 if (alt !== undefined) {
1170 this.alt = parseFloat(alt);
1174 L.extend(L.LatLng, {
1175 DEG_TO_RAD: Math.PI / 180,
1176 RAD_TO_DEG: 180 / Math.PI,
1177 MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
1180 L.LatLng.prototype = {
1181 equals: function (obj) { // (LatLng) -> Boolean
1182 if (!obj) { return false; }
1184 obj = L.latLng(obj);
1186 var margin = Math.max(
1187 Math.abs(this.lat - obj.lat),
1188 Math.abs(this.lng - obj.lng));
1190 return margin <= L.LatLng.MAX_MARGIN;
1193 toString: function (precision) { // (Number) -> String
1195 L.Util.formatNum(this.lat, precision) + ', ' +
1196 L.Util.formatNum(this.lng, precision) + ')';
1199 // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
1200 // TODO move to projection code, LatLng shouldn't know about Earth
1201 distanceTo: function (other) { // (LatLng) -> Number
1202 other = L.latLng(other);
1204 var R = 6378137, // earth radius in meters
1205 d2r = L.LatLng.DEG_TO_RAD,
1206 dLat = (other.lat - this.lat) * d2r,
1207 dLon = (other.lng - this.lng) * d2r,
1208 lat1 = this.lat * d2r,
1209 lat2 = other.lat * d2r,
1210 sin1 = Math.sin(dLat / 2),
1211 sin2 = Math.sin(dLon / 2);
1213 var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
1215 return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1218 wrap: function (a, b) { // (Number, Number) -> LatLng
1224 lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
1226 return new L.LatLng(this.lat, lng);
1230 L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
1231 if (a instanceof L.LatLng) {
1234 if (L.Util.isArray(a)) {
1235 if (typeof a[0] === 'number' || typeof a[0] === 'string') {
1236 return new L.LatLng(a[0], a[1], a[2]);
1241 if (a === undefined || a === null) {
1244 if (typeof a === 'object' && 'lat' in a) {
1245 return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
1247 if (b === undefined) {
1250 return new L.LatLng(a, b);
1256 * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
1259 L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
1260 if (!southWest) { return; }
1262 var latlngs = northEast ? [southWest, northEast] : southWest;
1264 for (var i = 0, len = latlngs.length; i < len; i++) {
1265 this.extend(latlngs[i]);
1269 L.LatLngBounds.prototype = {
1270 // extend the bounds to contain the given point or bounds
1271 extend: function (obj) { // (LatLng) or (LatLngBounds)
1272 if (!obj) { return this; }
1274 var latLng = L.latLng(obj);
1275 if (latLng !== null) {
1278 obj = L.latLngBounds(obj);
1281 if (obj instanceof L.LatLng) {
1282 if (!this._southWest && !this._northEast) {
1283 this._southWest = new L.LatLng(obj.lat, obj.lng);
1284 this._northEast = new L.LatLng(obj.lat, obj.lng);
1286 this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
1287 this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
1289 this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
1290 this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
1292 } else if (obj instanceof L.LatLngBounds) {
1293 this.extend(obj._southWest);
1294 this.extend(obj._northEast);
1299 // extend the bounds by a percentage
1300 pad: function (bufferRatio) { // (Number) -> LatLngBounds
1301 var sw = this._southWest,
1302 ne = this._northEast,
1303 heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
1304 widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
1306 return new L.LatLngBounds(
1307 new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
1308 new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
1311 getCenter: function () { // -> LatLng
1312 return new L.LatLng(
1313 (this._southWest.lat + this._northEast.lat) / 2,
1314 (this._southWest.lng + this._northEast.lng) / 2);
1317 getSouthWest: function () {
1318 return this._southWest;
1321 getNorthEast: function () {
1322 return this._northEast;
1325 getNorthWest: function () {
1326 return new L.LatLng(this.getNorth(), this.getWest());
1329 getSouthEast: function () {
1330 return new L.LatLng(this.getSouth(), this.getEast());
1333 getWest: function () {
1334 return this._southWest.lng;
1337 getSouth: function () {
1338 return this._southWest.lat;
1341 getEast: function () {
1342 return this._northEast.lng;
1345 getNorth: function () {
1346 return this._northEast.lat;
1349 contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
1350 if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
1351 obj = L.latLng(obj);
1353 obj = L.latLngBounds(obj);
1356 var sw = this._southWest,
1357 ne = this._northEast,
1360 if (obj instanceof L.LatLngBounds) {
1361 sw2 = obj.getSouthWest();
1362 ne2 = obj.getNorthEast();
1367 return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
1368 (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
1371 intersects: function (bounds) { // (LatLngBounds)
1372 bounds = L.latLngBounds(bounds);
1374 var sw = this._southWest,
1375 ne = this._northEast,
1376 sw2 = bounds.getSouthWest(),
1377 ne2 = bounds.getNorthEast(),
1379 latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
1380 lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
1382 return latIntersects && lngIntersects;
1385 toBBoxString: function () {
1386 return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
1389 equals: function (bounds) { // (LatLngBounds)
1390 if (!bounds) { return false; }
1392 bounds = L.latLngBounds(bounds);
1394 return this._southWest.equals(bounds.getSouthWest()) &&
1395 this._northEast.equals(bounds.getNorthEast());
1398 isValid: function () {
1399 return !!(this._southWest && this._northEast);
1403 //TODO International date line?
1405 L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
1406 if (!a || a instanceof L.LatLngBounds) {
1409 return new L.LatLngBounds(a, b);
1414 * L.Projection contains various geographical projections used by CRS classes.
1421 * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
1424 L.Projection.SphericalMercator = {
1425 MAX_LATITUDE: 85.0511287798,
1427 project: function (latlng) { // (LatLng) -> Point
1428 var d = L.LatLng.DEG_TO_RAD,
1429 max = this.MAX_LATITUDE,
1430 lat = Math.max(Math.min(max, latlng.lat), -max),
1434 y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
1436 return new L.Point(x, y);
1439 unproject: function (point) { // (Point, Boolean) -> LatLng
1440 var d = L.LatLng.RAD_TO_DEG,
1442 lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
1444 return new L.LatLng(lat, lng);
1450 * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
1453 L.Projection.LonLat = {
1454 project: function (latlng) {
1455 return new L.Point(latlng.lng, latlng.lat);
1458 unproject: function (point) {
1459 return new L.LatLng(point.y, point.x);
1465 * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
1469 latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
1470 var projectedPoint = this.projection.project(latlng),
1471 scale = this.scale(zoom);
1473 return this.transformation._transform(projectedPoint, scale);
1476 pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
1477 var scale = this.scale(zoom),
1478 untransformedPoint = this.transformation.untransform(point, scale);
1480 return this.projection.unproject(untransformedPoint);
1483 project: function (latlng) {
1484 return this.projection.project(latlng);
1487 scale: function (zoom) {
1488 return 256 * Math.pow(2, zoom);
1491 getSize: function (zoom) {
1492 var s = this.scale(zoom);
1493 return L.point(s, s);
1499 * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
1502 L.CRS.Simple = L.extend({}, L.CRS, {
1503 projection: L.Projection.LonLat,
1504 transformation: new L.Transformation(1, 0, -1, 0),
1506 scale: function (zoom) {
1507 return Math.pow(2, zoom);
1513 * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
1514 * and is used by Leaflet by default.
1517 L.CRS.EPSG3857 = L.extend({}, L.CRS, {
1520 projection: L.Projection.SphericalMercator,
1521 transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
1523 project: function (latlng) { // (LatLng) -> Point
1524 var projectedPoint = this.projection.project(latlng),
1525 earthRadius = 6378137;
1526 return projectedPoint.multiplyBy(earthRadius);
1530 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
1536 * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
1539 L.CRS.EPSG4326 = L.extend({}, L.CRS, {
1542 projection: L.Projection.LonLat,
1543 transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
1548 * L.Map is the central class of the API - it is used to create a map.
1551 L.Map = L.Class.extend({
1553 includes: L.Mixin.Events,
1556 crs: L.CRS.EPSG3857,
1564 fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
1566 markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
1569 initialize: function (id, options) { // (HTMLElement or String, Object)
1570 options = L.setOptions(this, options);
1573 this._initContainer(id);
1576 // hack for https://github.com/Leaflet/Leaflet/issues/1980
1577 this._onResize = L.bind(this._onResize, this);
1581 if (options.maxBounds) {
1582 this.setMaxBounds(options.maxBounds);
1585 if (options.center && options.zoom !== undefined) {
1586 this.setView(L.latLng(options.center), options.zoom, {reset: true});
1589 this._handlers = [];
1592 this._zoomBoundLayers = {};
1593 this._tileLayersNum = 0;
1595 this.callInitHooks();
1597 this._addLayers(options.layers);
1601 // public methods that modify map state
1603 // replaced by animation-powered implementation in Map.PanAnimation.js
1604 setView: function (center, zoom) {
1605 zoom = zoom === undefined ? this.getZoom() : zoom;
1606 this._resetView(L.latLng(center), this._limitZoom(zoom));
1610 setZoom: function (zoom, options) {
1611 if (!this._loaded) {
1612 this._zoom = this._limitZoom(zoom);
1615 return this.setView(this.getCenter(), zoom, {zoom: options});
1618 zoomIn: function (delta, options) {
1619 return this.setZoom(this._zoom + (delta || 1), options);
1622 zoomOut: function (delta, options) {
1623 return this.setZoom(this._zoom - (delta || 1), options);
1626 setZoomAround: function (latlng, zoom, options) {
1627 var scale = this.getZoomScale(zoom),
1628 viewHalf = this.getSize().divideBy(2),
1629 containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
1631 centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
1632 newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
1634 return this.setView(newCenter, zoom, {zoom: options});
1637 fitBounds: function (bounds, options) {
1639 options = options || {};
1640 bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
1642 var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
1643 paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
1645 zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
1646 paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
1648 swPoint = this.project(bounds.getSouthWest(), zoom),
1649 nePoint = this.project(bounds.getNorthEast(), zoom),
1650 center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
1652 zoom = options && options.maxZoom ? Math.min(options.maxZoom, zoom) : zoom;
1654 return this.setView(center, zoom, options);
1657 fitWorld: function (options) {
1658 return this.fitBounds([[-90, -180], [90, 180]], options);
1661 panTo: function (center, options) { // (LatLng)
1662 return this.setView(center, this._zoom, {pan: options});
1665 panBy: function (offset) { // (Point)
1666 // replaced with animated panBy in Map.PanAnimation.js
1667 this.fire('movestart');
1669 this._rawPanBy(L.point(offset));
1672 return this.fire('moveend');
1675 setMaxBounds: function (bounds) {
1676 bounds = L.latLngBounds(bounds);
1678 this.options.maxBounds = bounds;
1681 return this.off('moveend', this._panInsideMaxBounds, this);
1685 this._panInsideMaxBounds();
1688 return this.on('moveend', this._panInsideMaxBounds, this);
1691 panInsideBounds: function (bounds, options) {
1692 var center = this.getCenter(),
1693 newCenter = this._limitCenter(center, this._zoom, bounds);
1695 if (center.equals(newCenter)) { return this; }
1697 return this.panTo(newCenter, options);
1700 addLayer: function (layer) {
1701 // TODO method is too big, refactor
1703 var id = L.stamp(layer);
1705 if (this._layers[id]) { return this; }
1707 this._layers[id] = layer;
1709 // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
1710 if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
1711 this._zoomBoundLayers[id] = layer;
1712 this._updateZoomLevels();
1715 // TODO looks ugly, refactor!!!
1716 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1717 this._tileLayersNum++;
1718 this._tileLayersToLoad++;
1719 layer.on('load', this._onTileLayerLoad, this);
1723 this._layerAdd(layer);
1729 removeLayer: function (layer) {
1730 var id = L.stamp(layer);
1732 if (!this._layers[id]) { return this; }
1735 layer.onRemove(this);
1738 delete this._layers[id];
1741 this.fire('layerremove', {layer: layer});
1744 if (this._zoomBoundLayers[id]) {
1745 delete this._zoomBoundLayers[id];
1746 this._updateZoomLevels();
1749 // TODO looks ugly, refactor
1750 if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
1751 this._tileLayersNum--;
1752 this._tileLayersToLoad--;
1753 layer.off('load', this._onTileLayerLoad, this);
1759 hasLayer: function (layer) {
1760 if (!layer) { return false; }
1762 return (L.stamp(layer) in this._layers);
1765 eachLayer: function (method, context) {
1766 for (var i in this._layers) {
1767 method.call(context, this._layers[i]);
1772 invalidateSize: function (options) {
1773 options = L.extend({
1776 }, options === true ? {animate: true} : options);
1778 var oldSize = this.getSize();
1779 this._sizeChanged = true;
1780 this._initialCenter = null;
1782 if (!this._loaded) { return this; }
1784 var newSize = this.getSize(),
1785 oldCenter = oldSize.divideBy(2).round(),
1786 newCenter = newSize.divideBy(2).round(),
1787 offset = oldCenter.subtract(newCenter);
1789 if (!offset.x && !offset.y) { return this; }
1791 if (options.animate && options.pan) {
1796 this._rawPanBy(offset);
1801 if (options.debounceMoveend) {
1802 clearTimeout(this._sizeTimer);
1803 this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
1805 this.fire('moveend');
1809 return this.fire('resize', {
1815 // TODO handler.addTo
1816 addHandler: function (name, HandlerClass) {
1817 if (!HandlerClass) { return this; }
1819 var handler = this[name] = new HandlerClass(this);
1821 this._handlers.push(handler);
1823 if (this.options[name]) {
1830 remove: function () {
1832 this.fire('unload');
1835 this._initEvents('off');
1838 // throws error in IE6-8
1839 delete this._container._leaflet;
1841 this._container._leaflet = undefined;
1845 if (this._clearControlPos) {
1846 this._clearControlPos();
1849 this._clearHandlers();
1855 // public methods for getting map state
1857 getCenter: function () { // (Boolean) -> LatLng
1858 this._checkIfLoaded();
1860 if (this._initialCenter && !this._moved()) {
1861 return this._initialCenter;
1863 return this.layerPointToLatLng(this._getCenterLayerPoint());
1866 getZoom: function () {
1870 getBounds: function () {
1871 var bounds = this.getPixelBounds(),
1872 sw = this.unproject(bounds.getBottomLeft()),
1873 ne = this.unproject(bounds.getTopRight());
1875 return new L.LatLngBounds(sw, ne);
1878 getMinZoom: function () {
1879 return this.options.minZoom === undefined ?
1880 (this._layersMinZoom === undefined ? 0 : this._layersMinZoom) :
1881 this.options.minZoom;
1884 getMaxZoom: function () {
1885 return this.options.maxZoom === undefined ?
1886 (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
1887 this.options.maxZoom;
1890 getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
1891 bounds = L.latLngBounds(bounds);
1893 var zoom = this.getMinZoom() - (inside ? 1 : 0),
1894 maxZoom = this.getMaxZoom(),
1895 size = this.getSize(),
1897 nw = bounds.getNorthWest(),
1898 se = bounds.getSouthEast(),
1900 zoomNotFound = true,
1903 padding = L.point(padding || [0, 0]);
1907 boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
1908 zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
1910 } while (zoomNotFound && zoom <= maxZoom);
1912 if (zoomNotFound && inside) {
1916 return inside ? zoom : zoom - 1;
1919 getSize: function () {
1920 if (!this._size || this._sizeChanged) {
1921 this._size = new L.Point(
1922 this._container.clientWidth,
1923 this._container.clientHeight);
1925 this._sizeChanged = false;
1927 return this._size.clone();
1930 getPixelBounds: function () {
1931 var topLeftPoint = this._getTopLeftPoint();
1932 return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
1935 getPixelOrigin: function () {
1936 this._checkIfLoaded();
1937 return this._initialTopLeftPoint;
1940 getPanes: function () {
1944 getContainer: function () {
1945 return this._container;
1949 // TODO replace with universal implementation after refactoring projections
1951 getZoomScale: function (toZoom) {
1952 var crs = this.options.crs;
1953 return crs.scale(toZoom) / crs.scale(this._zoom);
1956 getScaleZoom: function (scale) {
1957 return this._zoom + (Math.log(scale) / Math.LN2);
1961 // conversion methods
1963 project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
1964 zoom = zoom === undefined ? this._zoom : zoom;
1965 return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
1968 unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
1969 zoom = zoom === undefined ? this._zoom : zoom;
1970 return this.options.crs.pointToLatLng(L.point(point), zoom);
1973 layerPointToLatLng: function (point) { // (Point)
1974 var projectedPoint = L.point(point).add(this.getPixelOrigin());
1975 return this.unproject(projectedPoint);
1978 latLngToLayerPoint: function (latlng) { // (LatLng)
1979 var projectedPoint = this.project(L.latLng(latlng))._round();
1980 return projectedPoint._subtract(this.getPixelOrigin());
1983 containerPointToLayerPoint: function (point) { // (Point)
1984 return L.point(point).subtract(this._getMapPanePos());
1987 layerPointToContainerPoint: function (point) { // (Point)
1988 return L.point(point).add(this._getMapPanePos());
1991 containerPointToLatLng: function (point) {
1992 var layerPoint = this.containerPointToLayerPoint(L.point(point));
1993 return this.layerPointToLatLng(layerPoint);
1996 latLngToContainerPoint: function (latlng) {
1997 return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
2000 mouseEventToContainerPoint: function (e) { // (MouseEvent)
2001 return L.DomEvent.getMousePosition(e, this._container);
2004 mouseEventToLayerPoint: function (e) { // (MouseEvent)
2005 return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
2008 mouseEventToLatLng: function (e) { // (MouseEvent)
2009 return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
2013 // map initialization methods
2015 _initContainer: function (id) {
2016 var container = this._container = L.DomUtil.get(id);
2019 throw new Error('Map container not found.');
2020 } else if (container._leaflet) {
2021 throw new Error('Map container is already initialized.');
2024 container._leaflet = true;
2027 _initLayout: function () {
2028 var container = this._container;
2030 L.DomUtil.addClass(container, 'leaflet-container' +
2031 (L.Browser.touch ? ' leaflet-touch' : '') +
2032 (L.Browser.retina ? ' leaflet-retina' : '') +
2033 (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
2034 (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
2036 var position = L.DomUtil.getStyle(container, 'position');
2038 if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
2039 container.style.position = 'relative';
2044 if (this._initControlPos) {
2045 this._initControlPos();
2049 _initPanes: function () {
2050 var panes = this._panes = {};
2052 this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
2054 this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
2055 panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
2056 panes.shadowPane = this._createPane('leaflet-shadow-pane');
2057 panes.overlayPane = this._createPane('leaflet-overlay-pane');
2058 panes.markerPane = this._createPane('leaflet-marker-pane');
2059 panes.popupPane = this._createPane('leaflet-popup-pane');
2061 var zoomHide = ' leaflet-zoom-hide';
2063 if (!this.options.markerZoomAnimation) {
2064 L.DomUtil.addClass(panes.markerPane, zoomHide);
2065 L.DomUtil.addClass(panes.shadowPane, zoomHide);
2066 L.DomUtil.addClass(panes.popupPane, zoomHide);
2070 _createPane: function (className, container) {
2071 return L.DomUtil.create('div', className, container || this._panes.objectsPane);
2074 _clearPanes: function () {
2075 this._container.removeChild(this._mapPane);
2078 _addLayers: function (layers) {
2079 layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
2081 for (var i = 0, len = layers.length; i < len; i++) {
2082 this.addLayer(layers[i]);
2087 // private methods that modify map state
2089 _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
2091 var zoomChanged = (this._zoom !== zoom);
2093 if (!afterZoomAnim) {
2094 this.fire('movestart');
2097 this.fire('zoomstart');
2102 this._initialCenter = center;
2104 this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
2106 if (!preserveMapOffset) {
2107 L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
2109 this._initialTopLeftPoint._add(this._getMapPanePos());
2112 this._tileLayersToLoad = this._tileLayersNum;
2114 var loading = !this._loaded;
2115 this._loaded = true;
2119 this.eachLayer(this._layerAdd, this);
2122 this.fire('viewreset', {hard: !preserveMapOffset});
2126 if (zoomChanged || afterZoomAnim) {
2127 this.fire('zoomend');
2130 this.fire('moveend', {hard: !preserveMapOffset});
2133 _rawPanBy: function (offset) {
2134 L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
2137 _getZoomSpan: function () {
2138 return this.getMaxZoom() - this.getMinZoom();
2141 _updateZoomLevels: function () {
2144 maxZoom = -Infinity,
2145 oldZoomSpan = this._getZoomSpan();
2147 for (i in this._zoomBoundLayers) {
2148 var layer = this._zoomBoundLayers[i];
2149 if (!isNaN(layer.options.minZoom)) {
2150 minZoom = Math.min(minZoom, layer.options.minZoom);
2152 if (!isNaN(layer.options.maxZoom)) {
2153 maxZoom = Math.max(maxZoom, layer.options.maxZoom);
2157 if (i === undefined) { // we have no tilelayers
2158 this._layersMaxZoom = this._layersMinZoom = undefined;
2160 this._layersMaxZoom = maxZoom;
2161 this._layersMinZoom = minZoom;
2164 if (oldZoomSpan !== this._getZoomSpan()) {
2165 this.fire('zoomlevelschange');
2169 _panInsideMaxBounds: function () {
2170 this.panInsideBounds(this.options.maxBounds);
2173 _checkIfLoaded: function () {
2174 if (!this._loaded) {
2175 throw new Error('Set map center and zoom first.');
2181 _initEvents: function (onOff) {
2182 if (!L.DomEvent) { return; }
2184 onOff = onOff || 'on';
2186 L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
2188 var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
2189 'mouseleave', 'mousemove', 'contextmenu'],
2192 for (i = 0, len = events.length; i < len; i++) {
2193 L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
2196 if (this.options.trackResize) {
2197 L.DomEvent[onOff](window, 'resize', this._onResize, this);
2201 _onResize: function () {
2202 L.Util.cancelAnimFrame(this._resizeRequest);
2203 this._resizeRequest = L.Util.requestAnimFrame(
2204 function () { this.invalidateSize({debounceMoveend: true}); }, this, false, this._container);
2207 _onMouseClick: function (e) {
2208 if (!this._loaded || (!e._simulated &&
2209 ((this.dragging && this.dragging.moved()) ||
2210 (this.boxZoom && this.boxZoom.moved()))) ||
2211 L.DomEvent._skipped(e)) { return; }
2213 this.fire('preclick');
2214 this._fireMouseEvent(e);
2217 _fireMouseEvent: function (e) {
2218 if (!this._loaded || L.DomEvent._skipped(e)) { return; }
2222 type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
2224 if (!this.hasEventListeners(type)) { return; }
2226 if (type === 'contextmenu') {
2227 L.DomEvent.preventDefault(e);
2230 var containerPoint = this.mouseEventToContainerPoint(e),
2231 layerPoint = this.containerPointToLayerPoint(containerPoint),
2232 latlng = this.layerPointToLatLng(layerPoint);
2236 layerPoint: layerPoint,
2237 containerPoint: containerPoint,
2242 _onTileLayerLoad: function () {
2243 this._tileLayersToLoad--;
2244 if (this._tileLayersNum && !this._tileLayersToLoad) {
2245 this.fire('tilelayersload');
2249 _clearHandlers: function () {
2250 for (var i = 0, len = this._handlers.length; i < len; i++) {
2251 this._handlers[i].disable();
2255 whenReady: function (callback, context) {
2257 callback.call(context || this, this);
2259 this.on('load', callback, context);
2264 _layerAdd: function (layer) {
2266 this.fire('layeradd', {layer: layer});
2270 // private methods for getting map state
2272 _getMapPanePos: function () {
2273 return L.DomUtil.getPosition(this._mapPane);
2276 _moved: function () {
2277 var pos = this._getMapPanePos();
2278 return pos && !pos.equals([0, 0]);
2281 _getTopLeftPoint: function () {
2282 return this.getPixelOrigin().subtract(this._getMapPanePos());
2285 _getNewTopLeftPoint: function (center, zoom) {
2286 var viewHalf = this.getSize()._divideBy(2);
2287 // TODO round on display, not calculation to increase precision?
2288 return this.project(center, zoom)._subtract(viewHalf)._round();
2291 _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
2292 var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
2293 return this.project(latlng, newZoom)._subtract(topLeft);
2296 // layer point of the current center
2297 _getCenterLayerPoint: function () {
2298 return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
2301 // offset of the specified place to the current center in pixels
2302 _getCenterOffset: function (latlng) {
2303 return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
2306 // adjust center for view to get inside bounds
2307 _limitCenter: function (center, zoom, bounds) {
2309 if (!bounds) { return center; }
2311 var centerPoint = this.project(center, zoom),
2312 viewHalf = this.getSize().divideBy(2),
2313 viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
2314 offset = this._getBoundsOffset(viewBounds, bounds, zoom);
2316 return this.unproject(centerPoint.add(offset), zoom);
2319 // adjust offset for view to get inside bounds
2320 _limitOffset: function (offset, bounds) {
2321 if (!bounds) { return offset; }
2323 var viewBounds = this.getPixelBounds(),
2324 newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
2326 return offset.add(this._getBoundsOffset(newBounds, bounds));
2329 // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
2330 _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
2331 var nwOffset = this.project(maxBounds.getNorthWest(), zoom).subtract(pxBounds.min),
2332 seOffset = this.project(maxBounds.getSouthEast(), zoom).subtract(pxBounds.max),
2334 dx = this._rebound(nwOffset.x, -seOffset.x),
2335 dy = this._rebound(nwOffset.y, -seOffset.y);
2337 return new L.Point(dx, dy);
2340 _rebound: function (left, right) {
2341 return left + right > 0 ?
2342 Math.round(left - right) / 2 :
2343 Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
2346 _limitZoom: function (zoom) {
2347 var min = this.getMinZoom(),
2348 max = this.getMaxZoom();
2350 return Math.max(min, Math.min(max, zoom));
2354 L.map = function (id, options) {
2355 return new L.Map(id, options);
2360 * Mercator projection that takes into account that the Earth is not a perfect sphere.
2361 * Less popular than spherical mercator; used by projections like EPSG:3395.
2364 L.Projection.Mercator = {
2365 MAX_LATITUDE: 85.0840591556,
2367 R_MINOR: 6356752.314245179,
2370 project: function (latlng) { // (LatLng) -> Point
2371 var d = L.LatLng.DEG_TO_RAD,
2372 max = this.MAX_LATITUDE,
2373 lat = Math.max(Math.min(max, latlng.lat), -max),
2376 x = latlng.lng * d * r,
2379 eccent = Math.sqrt(1.0 - tmp * tmp),
2380 con = eccent * Math.sin(y);
2382 con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
2384 var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
2385 y = -r * Math.log(ts);
2387 return new L.Point(x, y);
2390 unproject: function (point) { // (Point, Boolean) -> LatLng
2391 var d = L.LatLng.RAD_TO_DEG,
2394 lng = point.x * d / r,
2396 eccent = Math.sqrt(1 - (tmp * tmp)),
2397 ts = Math.exp(- point.y / r),
2398 phi = (Math.PI / 2) - 2 * Math.atan(ts),
2405 while ((Math.abs(dphi) > tol) && (--i > 0)) {
2406 con = eccent * Math.sin(phi);
2407 dphi = (Math.PI / 2) - 2 * Math.atan(ts *
2408 Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
2412 return new L.LatLng(phi * d, lng);
2418 L.CRS.EPSG3395 = L.extend({}, L.CRS, {
2421 projection: L.Projection.Mercator,
2423 transformation: (function () {
2424 var m = L.Projection.Mercator,
2426 scale = 0.5 / (Math.PI * r);
2428 return new L.Transformation(scale, 0.5, -scale, 0.5);
2434 * L.TileLayer is used for standard xyz-numbered tile layers.
2437 L.TileLayer = L.Class.extend({
2438 includes: L.Mixin.Events,
2450 maxNativeZoom: null,
2453 continuousWorld: false,
2456 detectRetina: false,
2460 unloadInvisibleTiles: L.Browser.mobile,
2461 updateWhenIdle: L.Browser.mobile
2464 initialize: function (url, options) {
2465 options = L.setOptions(this, options);
2467 // detecting retina displays, adjusting tileSize and zoom levels
2468 if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
2470 options.tileSize = Math.floor(options.tileSize / 2);
2471 options.zoomOffset++;
2473 if (options.minZoom > 0) {
2476 this.options.maxZoom--;
2479 if (options.bounds) {
2480 options.bounds = L.latLngBounds(options.bounds);
2485 var subdomains = this.options.subdomains;
2487 if (typeof subdomains === 'string') {
2488 this.options.subdomains = subdomains.split('');
2492 onAdd: function (map) {
2494 this._animated = map._zoomAnimated;
2496 // create a container div for tiles
2497 this._initContainer();
2501 'viewreset': this._reset,
2502 'moveend': this._update
2505 if (this._animated) {
2507 'zoomanim': this._animateZoom,
2508 'zoomend': this._endZoomAnim
2512 if (!this.options.updateWhenIdle) {
2513 this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
2514 map.on('move', this._limitedUpdate, this);
2521 addTo: function (map) {
2526 onRemove: function (map) {
2527 this._container.parentNode.removeChild(this._container);
2530 'viewreset': this._reset,
2531 'moveend': this._update
2534 if (this._animated) {
2536 'zoomanim': this._animateZoom,
2537 'zoomend': this._endZoomAnim
2541 if (!this.options.updateWhenIdle) {
2542 map.off('move', this._limitedUpdate, this);
2545 this._container = null;
2549 bringToFront: function () {
2550 var pane = this._map._panes.tilePane;
2552 if (this._container) {
2553 pane.appendChild(this._container);
2554 this._setAutoZIndex(pane, Math.max);
2560 bringToBack: function () {
2561 var pane = this._map._panes.tilePane;
2563 if (this._container) {
2564 pane.insertBefore(this._container, pane.firstChild);
2565 this._setAutoZIndex(pane, Math.min);
2571 getAttribution: function () {
2572 return this.options.attribution;
2575 getContainer: function () {
2576 return this._container;
2579 setOpacity: function (opacity) {
2580 this.options.opacity = opacity;
2583 this._updateOpacity();
2589 setZIndex: function (zIndex) {
2590 this.options.zIndex = zIndex;
2591 this._updateZIndex();
2596 setUrl: function (url, noRedraw) {
2606 redraw: function () {
2608 this._reset({hard: true});
2614 _updateZIndex: function () {
2615 if (this._container && this.options.zIndex !== undefined) {
2616 this._container.style.zIndex = this.options.zIndex;
2620 _setAutoZIndex: function (pane, compare) {
2622 var layers = pane.children,
2623 edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
2626 for (i = 0, len = layers.length; i < len; i++) {
2628 if (layers[i] !== this._container) {
2629 zIndex = parseInt(layers[i].style.zIndex, 10);
2631 if (!isNaN(zIndex)) {
2632 edgeZIndex = compare(edgeZIndex, zIndex);
2637 this.options.zIndex = this._container.style.zIndex =
2638 (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
2641 _updateOpacity: function () {
2643 tiles = this._tiles;
2645 if (L.Browser.ielt9) {
2647 L.DomUtil.setOpacity(tiles[i], this.options.opacity);
2650 L.DomUtil.setOpacity(this._container, this.options.opacity);
2654 _initContainer: function () {
2655 var tilePane = this._map._panes.tilePane;
2657 if (!this._container) {
2658 this._container = L.DomUtil.create('div', 'leaflet-layer');
2660 this._updateZIndex();
2662 if (this._animated) {
2663 var className = 'leaflet-tile-container';
2665 this._bgBuffer = L.DomUtil.create('div', className, this._container);
2666 this._tileContainer = L.DomUtil.create('div', className, this._container);
2669 this._tileContainer = this._container;
2672 tilePane.appendChild(this._container);
2674 if (this.options.opacity < 1) {
2675 this._updateOpacity();
2680 _reset: function (e) {
2681 for (var key in this._tiles) {
2682 this.fire('tileunload', {tile: this._tiles[key]});
2686 this._tilesToLoad = 0;
2688 if (this.options.reuseTiles) {
2689 this._unusedTiles = [];
2692 this._tileContainer.innerHTML = '';
2694 if (this._animated && e && e.hard) {
2695 this._clearBgBuffer();
2698 this._initContainer();
2701 _getTileSize: function () {
2702 var map = this._map,
2703 zoom = map.getZoom() + this.options.zoomOffset,
2704 zoomN = this.options.maxNativeZoom,
2705 tileSize = this.options.tileSize;
2707 if (zoomN && zoom > zoomN) {
2708 tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize);
2714 _update: function () {
2716 if (!this._map) { return; }
2718 var map = this._map,
2719 bounds = map.getPixelBounds(),
2720 zoom = map.getZoom(),
2721 tileSize = this._getTileSize();
2723 if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
2727 var tileBounds = L.bounds(
2728 bounds.min.divideBy(tileSize)._floor(),
2729 bounds.max.divideBy(tileSize)._floor());
2731 this._addTilesFromCenterOut(tileBounds);
2733 if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
2734 this._removeOtherTiles(tileBounds);
2738 _addTilesFromCenterOut: function (bounds) {
2740 center = bounds.getCenter();
2744 for (j = bounds.min.y; j <= bounds.max.y; j++) {
2745 for (i = bounds.min.x; i <= bounds.max.x; i++) {
2746 point = new L.Point(i, j);
2748 if (this._tileShouldBeLoaded(point)) {
2754 var tilesToLoad = queue.length;
2756 if (tilesToLoad === 0) { return; }
2758 // load tiles in order of their distance to center
2759 queue.sort(function (a, b) {
2760 return a.distanceTo(center) - b.distanceTo(center);
2763 var fragment = document.createDocumentFragment();
2765 // if its the first batch of tiles to load
2766 if (!this._tilesToLoad) {
2767 this.fire('loading');
2770 this._tilesToLoad += tilesToLoad;
2772 for (i = 0; i < tilesToLoad; i++) {
2773 this._addTile(queue[i], fragment);
2776 this._tileContainer.appendChild(fragment);
2779 _tileShouldBeLoaded: function (tilePoint) {
2780 if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
2781 return false; // already loaded
2784 var options = this.options;
2786 if (!options.continuousWorld) {
2787 var limit = this._getWrapTileNum();
2789 // don't load if exceeds world bounds
2790 if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) ||
2791 tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; }
2794 if (options.bounds) {
2795 var tileSize = options.tileSize,
2796 nwPoint = tilePoint.multiplyBy(tileSize),
2797 sePoint = nwPoint.add([tileSize, tileSize]),
2798 nw = this._map.unproject(nwPoint),
2799 se = this._map.unproject(sePoint);
2801 // TODO temporary hack, will be removed after refactoring projections
2802 // https://github.com/Leaflet/Leaflet/issues/1618
2803 if (!options.continuousWorld && !options.noWrap) {
2808 if (!options.bounds.intersects([nw, se])) { return false; }
2814 _removeOtherTiles: function (bounds) {
2815 var kArr, x, y, key;
2817 for (key in this._tiles) {
2818 kArr = key.split(':');
2819 x = parseInt(kArr[0], 10);
2820 y = parseInt(kArr[1], 10);
2822 // remove tile if it's out of bounds
2823 if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
2824 this._removeTile(key);
2829 _removeTile: function (key) {
2830 var tile = this._tiles[key];
2832 this.fire('tileunload', {tile: tile, url: tile.src});
2834 if (this.options.reuseTiles) {
2835 L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
2836 this._unusedTiles.push(tile);
2838 } else if (tile.parentNode === this._tileContainer) {
2839 this._tileContainer.removeChild(tile);
2842 // for https://github.com/CloudMade/Leaflet/issues/137
2843 if (!L.Browser.android) {
2845 tile.src = L.Util.emptyImageUrl;
2848 delete this._tiles[key];
2851 _addTile: function (tilePoint, container) {
2852 var tilePos = this._getTilePos(tilePoint);
2854 // get unused tile - or create a new tile
2855 var tile = this._getTile();
2858 Chrome 20 layouts much faster with top/left (verify with timeline, frames)
2859 Android 4 browser has display issues with top/left and requires transform instead
2860 Android 2 browser requires top/left or tiles disappear on load or first drag
2861 (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
2862 (other browsers don't currently care) - see debug/hacks/jitter.html for an example
2864 L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
2866 this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
2868 this._loadTile(tile, tilePoint);
2870 if (tile.parentNode !== this._tileContainer) {
2871 container.appendChild(tile);
2875 _getZoomForUrl: function () {
2877 var options = this.options,
2878 zoom = this._map.getZoom();
2880 if (options.zoomReverse) {
2881 zoom = options.maxZoom - zoom;
2884 zoom += options.zoomOffset;
2886 return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom;
2889 _getTilePos: function (tilePoint) {
2890 var origin = this._map.getPixelOrigin(),
2891 tileSize = this._getTileSize();
2893 return tilePoint.multiplyBy(tileSize).subtract(origin);
2896 // image-specific code (override to implement e.g. Canvas or SVG tile layer)
2898 getTileUrl: function (tilePoint) {
2899 return L.Util.template(this._url, L.extend({
2900 s: this._getSubdomain(tilePoint),
2907 _getWrapTileNum: function () {
2908 var crs = this._map.options.crs,
2909 size = crs.getSize(this._map.getZoom());
2910 return size.divideBy(this.options.tileSize);
2913 _adjustTilePoint: function (tilePoint) {
2915 var limit = this._getWrapTileNum();
2917 // wrap tile coordinates
2918 if (!this.options.continuousWorld && !this.options.noWrap) {
2919 tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x;
2922 if (this.options.tms) {
2923 tilePoint.y = limit.y - tilePoint.y - 1;
2926 tilePoint.z = this._getZoomForUrl();
2929 _getSubdomain: function (tilePoint) {
2930 var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
2931 return this.options.subdomains[index];
2934 _getTile: function () {
2935 if (this.options.reuseTiles && this._unusedTiles.length > 0) {
2936 var tile = this._unusedTiles.pop();
2937 this._resetTile(tile);
2940 return this._createTile();
2943 // Override if data stored on a tile needs to be cleaned up before reuse
2944 _resetTile: function (/*tile*/) {},
2946 _createTile: function () {
2947 var tile = L.DomUtil.create('img', 'leaflet-tile');
2948 tile.style.width = tile.style.height = this._getTileSize() + 'px';
2949 tile.galleryimg = 'no';
2951 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
2953 if (L.Browser.ielt9 && this.options.opacity !== undefined) {
2954 L.DomUtil.setOpacity(tile, this.options.opacity);
2956 // without this hack, tiles disappear after zoom on Chrome for Android
2957 // https://github.com/Leaflet/Leaflet/issues/2078
2958 if (L.Browser.mobileWebkit3d) {
2959 tile.style.WebkitBackfaceVisibility = 'hidden';
2964 _loadTile: function (tile, tilePoint) {
2966 tile.onload = this._tileOnLoad;
2967 tile.onerror = this._tileOnError;
2969 this._adjustTilePoint(tilePoint);
2970 tile.src = this.getTileUrl(tilePoint);
2972 this.fire('tileloadstart', {
2978 _tileLoaded: function () {
2979 this._tilesToLoad--;
2981 if (this._animated) {
2982 L.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated');
2985 if (!this._tilesToLoad) {
2988 if (this._animated) {
2989 // clear scaled tiles after all new tiles are loaded (for performance)
2990 clearTimeout(this._clearBgBufferTimer);
2991 this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
2996 _tileOnLoad: function () {
2997 var layer = this._layer;
2999 //Only if we are loading an actual image
3000 if (this.src !== L.Util.emptyImageUrl) {
3001 L.DomUtil.addClass(this, 'leaflet-tile-loaded');
3003 layer.fire('tileload', {
3009 layer._tileLoaded();
3012 _tileOnError: function () {
3013 var layer = this._layer;
3015 layer.fire('tileerror', {
3020 var newUrl = layer.options.errorTileUrl;
3025 layer._tileLoaded();
3029 L.tileLayer = function (url, options) {
3030 return new L.TileLayer(url, options);
3035 * L.TileLayer.WMS is used for putting WMS tile layers on the map.
3038 L.TileLayer.WMS = L.TileLayer.extend({
3046 format: 'image/jpeg',
3050 initialize: function (url, options) { // (String, Object)
3054 var wmsParams = L.extend({}, this.defaultWmsParams),
3055 tileSize = options.tileSize || this.options.tileSize;
3057 if (options.detectRetina && L.Browser.retina) {
3058 wmsParams.width = wmsParams.height = tileSize * 2;
3060 wmsParams.width = wmsParams.height = tileSize;
3063 for (var i in options) {
3064 // all keys that are not TileLayer options go to WMS params
3065 if (!this.options.hasOwnProperty(i) && i !== 'crs') {
3066 wmsParams[i] = options[i];
3070 this.wmsParams = wmsParams;
3072 L.setOptions(this, options);
3075 onAdd: function (map) {
3077 this._crs = this.options.crs || map.options.crs;
3079 this._wmsVersion = parseFloat(this.wmsParams.version);
3081 var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
3082 this.wmsParams[projectionKey] = this._crs.code;
3084 L.TileLayer.prototype.onAdd.call(this, map);
3087 getTileUrl: function (tilePoint) { // (Point, Number) -> String
3089 var map = this._map,
3090 tileSize = this.options.tileSize,
3092 nwPoint = tilePoint.multiplyBy(tileSize),
3093 sePoint = nwPoint.add([tileSize, tileSize]),
3095 nw = this._crs.project(map.unproject(nwPoint, tilePoint.z)),
3096 se = this._crs.project(map.unproject(sePoint, tilePoint.z)),
3097 bbox = this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
3098 [se.y, nw.x, nw.y, se.x].join(',') :
3099 [nw.x, se.y, se.x, nw.y].join(','),
3101 url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
3103 return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
3106 setParams: function (params, noRedraw) {
3108 L.extend(this.wmsParams, params);
3118 L.tileLayer.wms = function (url, options) {
3119 return new L.TileLayer.WMS(url, options);
3124 * L.TileLayer.Canvas is a class that you can use as a base for creating
3125 * dynamically drawn Canvas-based tile layers.
3128 L.TileLayer.Canvas = L.TileLayer.extend({
3133 initialize: function (options) {
3134 L.setOptions(this, options);
3137 redraw: function () {
3139 this._reset({hard: true});
3143 for (var i in this._tiles) {
3144 this._redrawTile(this._tiles[i]);
3149 _redrawTile: function (tile) {
3150 this.drawTile(tile, tile._tilePoint, this._map._zoom);
3153 _createTile: function () {
3154 var tile = L.DomUtil.create('canvas', 'leaflet-tile');
3155 tile.width = tile.height = this.options.tileSize;
3156 tile.onselectstart = tile.onmousemove = L.Util.falseFn;
3160 _loadTile: function (tile, tilePoint) {
3162 tile._tilePoint = tilePoint;
3164 this._redrawTile(tile);
3166 if (!this.options.async) {
3167 this.tileDrawn(tile);
3171 drawTile: function (/*tile, tilePoint*/) {
3172 // override with rendering code
3175 tileDrawn: function (tile) {
3176 this._tileOnLoad.call(tile);
3181 L.tileLayer.canvas = function (options) {
3182 return new L.TileLayer.Canvas(options);
3187 * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
3190 L.ImageOverlay = L.Class.extend({
3191 includes: L.Mixin.Events,
3197 initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
3199 this._bounds = L.latLngBounds(bounds);
3201 L.setOptions(this, options);
3204 onAdd: function (map) {
3211 map._panes.overlayPane.appendChild(this._image);
3213 map.on('viewreset', this._reset, this);
3215 if (map.options.zoomAnimation && L.Browser.any3d) {
3216 map.on('zoomanim', this._animateZoom, this);
3222 onRemove: function (map) {
3223 map.getPanes().overlayPane.removeChild(this._image);
3225 map.off('viewreset', this._reset, this);
3227 if (map.options.zoomAnimation) {
3228 map.off('zoomanim', this._animateZoom, this);
3232 addTo: function (map) {
3237 setOpacity: function (opacity) {
3238 this.options.opacity = opacity;
3239 this._updateOpacity();
3243 // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
3244 bringToFront: function () {
3246 this._map._panes.overlayPane.appendChild(this._image);
3251 bringToBack: function () {
3252 var pane = this._map._panes.overlayPane;
3254 pane.insertBefore(this._image, pane.firstChild);
3259 setUrl: function (url) {
3261 this._image.src = this._url;
3264 getAttribution: function () {
3265 return this.options.attribution;
3268 _initImage: function () {
3269 this._image = L.DomUtil.create('img', 'leaflet-image-layer');
3271 if (this._map.options.zoomAnimation && L.Browser.any3d) {
3272 L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
3274 L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
3277 this._updateOpacity();
3279 //TODO createImage util method to remove duplication
3280 L.extend(this._image, {
3282 onselectstart: L.Util.falseFn,
3283 onmousemove: L.Util.falseFn,
3284 onload: L.bind(this._onImageLoad, this),
3289 _animateZoom: function (e) {
3290 var map = this._map,
3291 image = this._image,
3292 scale = map.getZoomScale(e.zoom),
3293 nw = this._bounds.getNorthWest(),
3294 se = this._bounds.getSouthEast(),
3296 topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
3297 size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
3298 origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
3300 image.style[L.DomUtil.TRANSFORM] =
3301 L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
3304 _reset: function () {
3305 var image = this._image,
3306 topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
3307 size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
3309 L.DomUtil.setPosition(image, topLeft);
3311 image.style.width = size.x + 'px';
3312 image.style.height = size.y + 'px';
3315 _onImageLoad: function () {
3319 _updateOpacity: function () {
3320 L.DomUtil.setOpacity(this._image, this.options.opacity);
3324 L.imageOverlay = function (url, bounds, options) {
3325 return new L.ImageOverlay(url, bounds, options);
3330 * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
3333 L.Icon = L.Class.extend({
3336 iconUrl: (String) (required)
3337 iconRetinaUrl: (String) (optional, used for retina devices if detected)
3338 iconSize: (Point) (can be set through CSS)
3339 iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
3340 popupAnchor: (Point) (if not specified, popup opens in the anchor point)
3341 shadowUrl: (String) (no shadow by default)
3342 shadowRetinaUrl: (String) (optional, used for retina devices if detected)
3344 shadowAnchor: (Point)
3349 initialize: function (options) {
3350 L.setOptions(this, options);
3353 createIcon: function (oldIcon) {
3354 return this._createIcon('icon', oldIcon);
3357 createShadow: function (oldIcon) {
3358 return this._createIcon('shadow', oldIcon);
3361 _createIcon: function (name, oldIcon) {
3362 var src = this._getIconUrl(name);
3365 if (name === 'icon') {
3366 throw new Error('iconUrl not set in Icon options (see the docs).');
3372 if (!oldIcon || oldIcon.tagName !== 'IMG') {
3373 img = this._createImg(src);
3375 img = this._createImg(src, oldIcon);
3377 this._setIconStyles(img, name);
3382 _setIconStyles: function (img, name) {
3383 var options = this.options,
3384 size = L.point(options[name + 'Size']),
3387 if (name === 'shadow') {
3388 anchor = L.point(options.shadowAnchor || options.iconAnchor);
3390 anchor = L.point(options.iconAnchor);
3393 if (!anchor && size) {
3394 anchor = size.divideBy(2, true);
3397 img.className = 'leaflet-marker-' + name + ' ' + options.className;
3400 img.style.marginLeft = (-anchor.x) + 'px';
3401 img.style.marginTop = (-anchor.y) + 'px';
3405 img.style.width = size.x + 'px';
3406 img.style.height = size.y + 'px';
3410 _createImg: function (src, el) {
3411 el = el || document.createElement('img');
3416 _getIconUrl: function (name) {
3417 if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
3418 return this.options[name + 'RetinaUrl'];
3420 return this.options[name + 'Url'];
3424 L.icon = function (options) {
3425 return new L.Icon(options);
3430 * L.Icon.Default is the blue marker icon used by default in Leaflet.
3433 L.Icon.Default = L.Icon.extend({
3437 iconAnchor: [12, 41],
3438 popupAnchor: [1, -34],
3440 shadowSize: [41, 41]
3443 _getIconUrl: function (name) {
3444 var key = name + 'Url';
3446 if (this.options[key]) {
3447 return this.options[key];
3450 if (L.Browser.retina && name === 'icon') {
3454 var path = L.Icon.Default.imagePath;
3457 throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
3460 return path + '/marker-' + name + '.png';
3464 L.Icon.Default.imagePath = (function () {
3465 var scripts = document.getElementsByTagName('script'),
3466 leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
3468 var i, len, src, matches, path;
3470 for (i = 0, len = scripts.length; i < len; i++) {
3471 src = scripts[i].src;
3472 matches = src.match(leafletRe);
3475 path = src.split(leafletRe)[0];
3476 return (path ? path + '/' : '') + 'images';
3483 * L.Marker is used to display clickable/draggable icons on the map.
3486 L.Marker = L.Class.extend({
3488 includes: L.Mixin.Events,
3491 icon: new L.Icon.Default(),
3503 initialize: function (latlng, options) {
3504 L.setOptions(this, options);
3505 this._latlng = L.latLng(latlng);
3508 onAdd: function (map) {
3511 map.on('viewreset', this.update, this);
3517 if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
3518 map.on('zoomanim', this._animateZoom, this);
3522 addTo: function (map) {
3527 onRemove: function (map) {
3528 if (this.dragging) {
3529 this.dragging.disable();
3533 this._removeShadow();
3535 this.fire('remove');
3538 'viewreset': this.update,
3539 'zoomanim': this._animateZoom
3545 getLatLng: function () {
3546 return this._latlng;
3549 setLatLng: function (latlng) {
3550 this._latlng = L.latLng(latlng);
3554 return this.fire('move', { latlng: this._latlng });
3557 setZIndexOffset: function (offset) {
3558 this.options.zIndexOffset = offset;
3564 setIcon: function (icon) {
3566 this.options.icon = icon;
3574 this.bindPopup(this._popup);
3580 update: function () {
3582 var pos = this._map.latLngToLayerPoint(this._latlng).round();
3589 _initIcon: function () {
3590 var options = this.options,
3592 animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
3593 classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
3595 var icon = options.icon.createIcon(this._icon),
3598 // if we're not reusing the icon, remove the old one and init new one
3599 if (icon !== this._icon) {
3605 if (options.title) {
3606 icon.title = options.title;
3610 icon.alt = options.alt;
3614 L.DomUtil.addClass(icon, classToAdd);
3616 if (options.keyboard) {
3617 icon.tabIndex = '0';
3622 this._initInteraction();
3624 if (options.riseOnHover) {
3626 .on(icon, 'mouseover', this._bringToFront, this)
3627 .on(icon, 'mouseout', this._resetZIndex, this);
3630 var newShadow = options.icon.createShadow(this._shadow),
3633 if (newShadow !== this._shadow) {
3634 this._removeShadow();
3639 L.DomUtil.addClass(newShadow, classToAdd);
3641 this._shadow = newShadow;
3644 if (options.opacity < 1) {
3645 this._updateOpacity();
3649 var panes = this._map._panes;
3652 panes.markerPane.appendChild(this._icon);
3655 if (newShadow && addShadow) {
3656 panes.shadowPane.appendChild(this._shadow);
3660 _removeIcon: function () {
3661 if (this.options.riseOnHover) {
3663 .off(this._icon, 'mouseover', this._bringToFront)
3664 .off(this._icon, 'mouseout', this._resetZIndex);
3667 this._map._panes.markerPane.removeChild(this._icon);
3672 _removeShadow: function () {
3674 this._map._panes.shadowPane.removeChild(this._shadow);
3676 this._shadow = null;
3679 _setPos: function (pos) {
3680 L.DomUtil.setPosition(this._icon, pos);
3683 L.DomUtil.setPosition(this._shadow, pos);
3686 this._zIndex = pos.y + this.options.zIndexOffset;
3688 this._resetZIndex();
3691 _updateZIndex: function (offset) {
3692 this._icon.style.zIndex = this._zIndex + offset;
3695 _animateZoom: function (opt) {
3696 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
3701 _initInteraction: function () {
3703 if (!this.options.clickable) { return; }
3705 // TODO refactor into something shared with Map/Path/etc. to DRY it up
3707 var icon = this._icon,
3708 events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
3710 L.DomUtil.addClass(icon, 'leaflet-clickable');
3711 L.DomEvent.on(icon, 'click', this._onMouseClick, this);
3712 L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
3714 for (var i = 0; i < events.length; i++) {
3715 L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
3718 if (L.Handler.MarkerDrag) {
3719 this.dragging = new L.Handler.MarkerDrag(this);
3721 if (this.options.draggable) {
3722 this.dragging.enable();
3727 _onMouseClick: function (e) {
3728 var wasDragged = this.dragging && this.dragging.moved();
3730 if (this.hasEventListeners(e.type) || wasDragged) {
3731 L.DomEvent.stopPropagation(e);
3734 if (wasDragged) { return; }
3736 if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
3740 latlng: this._latlng
3744 _onKeyPress: function (e) {
3745 if (e.keyCode === 13) {
3746 this.fire('click', {
3748 latlng: this._latlng
3753 _fireMouseEvent: function (e) {
3757 latlng: this._latlng
3760 // TODO proper custom event propagation
3761 // this line will always be called if marker is in a FeatureGroup
3762 if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
3763 L.DomEvent.preventDefault(e);
3765 if (e.type !== 'mousedown') {
3766 L.DomEvent.stopPropagation(e);
3768 L.DomEvent.preventDefault(e);
3772 setOpacity: function (opacity) {
3773 this.options.opacity = opacity;
3775 this._updateOpacity();
3781 _updateOpacity: function () {
3782 L.DomUtil.setOpacity(this._icon, this.options.opacity);
3784 L.DomUtil.setOpacity(this._shadow, this.options.opacity);
3788 _bringToFront: function () {
3789 this._updateZIndex(this.options.riseOffset);
3792 _resetZIndex: function () {
3793 this._updateZIndex(0);
3797 L.marker = function (latlng, options) {
3798 return new L.Marker(latlng, options);
3803 * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
3804 * to use with L.Marker.
3807 L.DivIcon = L.Icon.extend({
3809 iconSize: [12, 12], // also can be set through CSS
3812 popupAnchor: (Point)
3816 className: 'leaflet-div-icon',
3820 createIcon: function (oldIcon) {
3821 var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
3822 options = this.options;
3824 if (options.html !== false) {
3825 div.innerHTML = options.html;
3830 if (options.bgPos) {
3831 div.style.backgroundPosition =
3832 (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
3835 this._setIconStyles(div, 'icon');
3839 createShadow: function () {
3844 L.divIcon = function (options) {
3845 return new L.DivIcon(options);
3850 * L.Popup is used for displaying popups on the map.
3853 L.Map.mergeOptions({
3854 closePopupOnClick: true
3857 L.Popup = L.Class.extend({
3858 includes: L.Mixin.Events,
3867 autoPanPadding: [5, 5],
3868 // autoPanPaddingTopLeft: null,
3869 // autoPanPaddingBottomRight: null,
3875 initialize: function (options, source) {
3876 L.setOptions(this, options);
3878 this._source = source;
3879 this._animated = L.Browser.any3d && this.options.zoomAnimation;
3880 this._isOpen = false;
3883 onAdd: function (map) {
3886 if (!this._container) {
3890 var animFade = map.options.fadeAnimation;
3893 L.DomUtil.setOpacity(this._container, 0);
3895 map._panes.popupPane.appendChild(this._container);
3897 map.on(this._getEvents(), this);
3902 L.DomUtil.setOpacity(this._container, 1);
3907 map.fire('popupopen', {popup: this});
3910 this._source.fire('popupopen', {popup: this});
3914 addTo: function (map) {
3919 openOn: function (map) {
3920 map.openPopup(this);
3924 onRemove: function (map) {
3925 map._panes.popupPane.removeChild(this._container);
3927 L.Util.falseFn(this._container.offsetWidth); // force reflow
3929 map.off(this._getEvents(), this);
3931 if (map.options.fadeAnimation) {
3932 L.DomUtil.setOpacity(this._container, 0);
3939 map.fire('popupclose', {popup: this});
3942 this._source.fire('popupclose', {popup: this});
3946 getLatLng: function () {
3947 return this._latlng;
3950 setLatLng: function (latlng) {
3951 this._latlng = L.latLng(latlng);
3953 this._updatePosition();
3959 getContent: function () {
3960 return this._content;
3963 setContent: function (content) {
3964 this._content = content;
3969 update: function () {
3970 if (!this._map) { return; }
3972 this._container.style.visibility = 'hidden';
3974 this._updateContent();
3975 this._updateLayout();
3976 this._updatePosition();
3978 this._container.style.visibility = '';
3983 _getEvents: function () {
3985 viewreset: this._updatePosition
3988 if (this._animated) {
3989 events.zoomanim = this._zoomAnimation;
3991 if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
3992 events.preclick = this._close;
3994 if (this.options.keepInView) {
3995 events.moveend = this._adjustPan;
4001 _close: function () {
4003 this._map.closePopup(this);
4007 _initLayout: function () {
4008 var prefix = 'leaflet-popup',
4009 containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
4010 (this._animated ? 'animated' : 'hide'),
4011 container = this._container = L.DomUtil.create('div', containerClass),
4014 if (this.options.closeButton) {
4015 closeButton = this._closeButton =
4016 L.DomUtil.create('a', prefix + '-close-button', container);
4017 closeButton.href = '#close';
4018 closeButton.innerHTML = '×';
4019 L.DomEvent.disableClickPropagation(closeButton);
4021 L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
4024 var wrapper = this._wrapper =
4025 L.DomUtil.create('div', prefix + '-content-wrapper', container);
4026 L.DomEvent.disableClickPropagation(wrapper);
4028 this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
4030 L.DomEvent.disableScrollPropagation(this._contentNode);
4031 L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
4033 this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
4034 this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
4037 _updateContent: function () {
4038 if (!this._content) { return; }
4040 if (typeof this._content === 'string') {
4041 this._contentNode.innerHTML = this._content;
4043 while (this._contentNode.hasChildNodes()) {
4044 this._contentNode.removeChild(this._contentNode.firstChild);
4046 this._contentNode.appendChild(this._content);
4048 this.fire('contentupdate');
4051 _updateLayout: function () {
4052 var container = this._contentNode,
4053 style = container.style;
4056 style.whiteSpace = 'nowrap';
4058 var width = container.offsetWidth;
4059 width = Math.min(width, this.options.maxWidth);
4060 width = Math.max(width, this.options.minWidth);
4062 style.width = (width + 1) + 'px';
4063 style.whiteSpace = '';
4067 var height = container.offsetHeight,
4068 maxHeight = this.options.maxHeight,
4069 scrolledClass = 'leaflet-popup-scrolled';
4071 if (maxHeight && height > maxHeight) {
4072 style.height = maxHeight + 'px';
4073 L.DomUtil.addClass(container, scrolledClass);
4075 L.DomUtil.removeClass(container, scrolledClass);
4078 this._containerWidth = this._container.offsetWidth;
4081 _updatePosition: function () {
4082 if (!this._map) { return; }
4084 var pos = this._map.latLngToLayerPoint(this._latlng),
4085 animated = this._animated,
4086 offset = L.point(this.options.offset);
4089 L.DomUtil.setPosition(this._container, pos);
4092 this._containerBottom = -offset.y - (animated ? 0 : pos.y);
4093 this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
4095 // bottom position the popup in case the height of the popup changes (images loading etc)
4096 this._container.style.bottom = this._containerBottom + 'px';
4097 this._container.style.left = this._containerLeft + 'px';
4100 _zoomAnimation: function (opt) {
4101 var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
4103 L.DomUtil.setPosition(this._container, pos);
4106 _adjustPan: function () {
4107 if (!this.options.autoPan) { return; }
4109 var map = this._map,
4110 containerHeight = this._container.offsetHeight,
4111 containerWidth = this._containerWidth,
4113 layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
4115 if (this._animated) {
4116 layerPos._add(L.DomUtil.getPosition(this._container));
4119 var containerPos = map.layerPointToContainerPoint(layerPos),
4120 padding = L.point(this.options.autoPanPadding),
4121 paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding),
4122 paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding),
4123 size = map.getSize(),
4127 if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
4128 dx = containerPos.x + containerWidth - size.x + paddingBR.x;
4130 if (containerPos.x - dx - paddingTL.x < 0) { // left
4131 dx = containerPos.x - paddingTL.x;
4133 if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
4134 dy = containerPos.y + containerHeight - size.y + paddingBR.y;
4136 if (containerPos.y - dy - paddingTL.y < 0) { // top
4137 dy = containerPos.y - paddingTL.y;
4142 .fire('autopanstart')
4147 _onCloseButtonClick: function (e) {
4153 L.popup = function (options, source) {
4154 return new L.Popup(options, source);
4159 openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
4162 if (!(popup instanceof L.Popup)) {
4163 var content = popup;
4165 popup = new L.Popup(options)
4167 .setContent(content);
4169 popup._isOpen = true;
4171 this._popup = popup;
4172 return this.addLayer(popup);
4175 closePopup: function (popup) {
4176 if (!popup || popup === this._popup) {
4177 popup = this._popup;
4181 this.removeLayer(popup);
4182 popup._isOpen = false;
4190 * Popup extension to L.Marker, adding popup-related methods.
4194 openPopup: function () {
4195 if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
4196 this._popup.setLatLng(this._latlng);
4197 this._map.openPopup(this._popup);
4203 closePopup: function () {
4205 this._popup._close();
4210 togglePopup: function () {
4212 if (this._popup._isOpen) {
4221 bindPopup: function (content, options) {
4222 var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
4224 anchor = anchor.add(L.Popup.prototype.options.offset);
4226 if (options && options.offset) {
4227 anchor = anchor.add(options.offset);
4230 options = L.extend({offset: anchor}, options);
4232 if (!this._popupHandlersAdded) {
4234 .on('click', this.togglePopup, this)
4235 .on('remove', this.closePopup, this)
4236 .on('move', this._movePopup, this);
4237 this._popupHandlersAdded = true;
4240 if (content instanceof L.Popup) {
4241 L.setOptions(content, options);
4242 this._popup = content;
4244 this._popup = new L.Popup(options, this)
4245 .setContent(content);
4251 setPopupContent: function (content) {
4253 this._popup.setContent(content);
4258 unbindPopup: function () {
4262 .off('click', this.togglePopup, this)
4263 .off('remove', this.closePopup, this)
4264 .off('move', this._movePopup, this);
4265 this._popupHandlersAdded = false;
4270 getPopup: function () {
4274 _movePopup: function (e) {
4275 this._popup.setLatLng(e.latlng);
4281 * L.LayerGroup is a class to combine several layers into one so that
4282 * you can manipulate the group (e.g. add/remove it) as one layer.
4285 L.LayerGroup = L.Class.extend({
4286 initialize: function (layers) {
4292 for (i = 0, len = layers.length; i < len; i++) {
4293 this.addLayer(layers[i]);
4298 addLayer: function (layer) {
4299 var id = this.getLayerId(layer);
4301 this._layers[id] = layer;
4304 this._map.addLayer(layer);
4310 removeLayer: function (layer) {
4311 var id = layer in this._layers ? layer : this.getLayerId(layer);
4313 if (this._map && this._layers[id]) {
4314 this._map.removeLayer(this._layers[id]);
4317 delete this._layers[id];
4322 hasLayer: function (layer) {
4323 if (!layer) { return false; }
4325 return (layer in this._layers || this.getLayerId(layer) in this._layers);
4328 clearLayers: function () {
4329 this.eachLayer(this.removeLayer, this);
4333 invoke: function (methodName) {
4334 var args = Array.prototype.slice.call(arguments, 1),
4337 for (i in this._layers) {
4338 layer = this._layers[i];
4340 if (layer[methodName]) {
4341 layer[methodName].apply(layer, args);
4348 onAdd: function (map) {
4350 this.eachLayer(map.addLayer, map);
4353 onRemove: function (map) {
4354 this.eachLayer(map.removeLayer, map);
4358 addTo: function (map) {
4363 eachLayer: function (method, context) {
4364 for (var i in this._layers) {
4365 method.call(context, this._layers[i]);
4370 getLayer: function (id) {
4371 return this._layers[id];
4374 getLayers: function () {
4377 for (var i in this._layers) {
4378 layers.push(this._layers[i]);
4383 setZIndex: function (zIndex) {
4384 return this.invoke('setZIndex', zIndex);
4387 getLayerId: function (layer) {
4388 return L.stamp(layer);
4392 L.layerGroup = function (layers) {
4393 return new L.LayerGroup(layers);
4398 * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
4399 * shared between a group of interactive layers (like vectors or markers).
4402 L.FeatureGroup = L.LayerGroup.extend({
4403 includes: L.Mixin.Events,
4406 EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
4409 addLayer: function (layer) {
4410 if (this.hasLayer(layer)) {
4414 if ('on' in layer) {
4415 layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4418 L.LayerGroup.prototype.addLayer.call(this, layer);
4420 if (this._popupContent && layer.bindPopup) {
4421 layer.bindPopup(this._popupContent, this._popupOptions);
4424 return this.fire('layeradd', {layer: layer});
4427 removeLayer: function (layer) {
4428 if (!this.hasLayer(layer)) {
4431 if (layer in this._layers) {
4432 layer = this._layers[layer];
4435 layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
4437 L.LayerGroup.prototype.removeLayer.call(this, layer);
4439 if (this._popupContent) {
4440 this.invoke('unbindPopup');
4443 return this.fire('layerremove', {layer: layer});
4446 bindPopup: function (content, options) {
4447 this._popupContent = content;
4448 this._popupOptions = options;
4449 return this.invoke('bindPopup', content, options);
4452 openPopup: function (latlng) {
4453 // open popup on the first layer
4454 for (var id in this._layers) {
4455 this._layers[id].openPopup(latlng);
4461 setStyle: function (style) {
4462 return this.invoke('setStyle', style);
4465 bringToFront: function () {
4466 return this.invoke('bringToFront');
4469 bringToBack: function () {
4470 return this.invoke('bringToBack');
4473 getBounds: function () {
4474 var bounds = new L.LatLngBounds();
4476 this.eachLayer(function (layer) {
4477 bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
4483 _propagateEvent: function (e) {
4484 e = L.extend({}, e, {
4488 this.fire(e.type, e);
4492 L.featureGroup = function (layers) {
4493 return new L.FeatureGroup(layers);
4498 * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
4501 L.Path = L.Class.extend({
4502 includes: [L.Mixin.Events],
4505 // how much to extend the clip area around the map view
4506 // (relative to its size, e.g. 0.5 is half the screen in each direction)
4507 // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
4508 CLIP_PADDING: (function () {
4509 var max = L.Browser.mobile ? 1280 : 2000,
4510 target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
4511 return Math.max(0, Math.min(0.5, target));
4525 fillColor: null, //same as color by default
4531 initialize: function (options) {
4532 L.setOptions(this, options);
4535 onAdd: function (map) {
4538 if (!this._container) {
4539 this._initElements();
4543 this.projectLatlngs();
4546 if (this._container) {
4547 this._map._pathRoot.appendChild(this._container);
4553 'viewreset': this.projectLatlngs,
4554 'moveend': this._updatePath
4558 addTo: function (map) {
4563 onRemove: function (map) {
4564 map._pathRoot.removeChild(this._container);
4566 // Need to fire remove event before we set _map to null as the event hooks might need the object
4567 this.fire('remove');
4570 if (L.Browser.vml) {
4571 this._container = null;
4572 this._stroke = null;
4577 'viewreset': this.projectLatlngs,
4578 'moveend': this._updatePath
4582 projectLatlngs: function () {
4583 // do all projection stuff here
4586 setStyle: function (style) {
4587 L.setOptions(this, style);
4589 if (this._container) {
4590 this._updateStyle();
4596 redraw: function () {
4598 this.projectLatlngs();
4606 _updatePathViewport: function () {
4607 var p = L.Path.CLIP_PADDING,
4608 size = this.getSize(),
4609 panePos = L.DomUtil.getPosition(this._mapPane),
4610 min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
4611 max = min.add(size.multiplyBy(1 + p * 2)._round());
4613 this._pathViewport = new L.Bounds(min, max);
4619 * Extends L.Path with SVG-specific rendering code.
4622 L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
4624 L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
4626 L.Path = L.Path.extend({
4631 bringToFront: function () {
4632 var root = this._map._pathRoot,
4633 path = this._container;
4635 if (path && root.lastChild !== path) {
4636 root.appendChild(path);
4641 bringToBack: function () {
4642 var root = this._map._pathRoot,
4643 path = this._container,
4644 first = root.firstChild;
4646 if (path && first !== path) {
4647 root.insertBefore(path, first);
4652 getPathString: function () {
4653 // form path string here
4656 _createElement: function (name) {
4657 return document.createElementNS(L.Path.SVG_NS, name);
4660 _initElements: function () {
4661 this._map._initPathRoot();
4666 _initPath: function () {
4667 this._container = this._createElement('g');
4669 this._path = this._createElement('path');
4671 if (this.options.className) {
4672 L.DomUtil.addClass(this._path, this.options.className);
4675 this._container.appendChild(this._path);
4678 _initStyle: function () {
4679 if (this.options.stroke) {
4680 this._path.setAttribute('stroke-linejoin', 'round');
4681 this._path.setAttribute('stroke-linecap', 'round');
4683 if (this.options.fill) {
4684 this._path.setAttribute('fill-rule', 'evenodd');
4686 if (this.options.pointerEvents) {
4687 this._path.setAttribute('pointer-events', this.options.pointerEvents);
4689 if (!this.options.clickable && !this.options.pointerEvents) {
4690 this._path.setAttribute('pointer-events', 'none');
4692 this._updateStyle();
4695 _updateStyle: function () {
4696 if (this.options.stroke) {
4697 this._path.setAttribute('stroke', this.options.color);
4698 this._path.setAttribute('stroke-opacity', this.options.opacity);
4699 this._path.setAttribute('stroke-width', this.options.weight);
4700 if (this.options.dashArray) {
4701 this._path.setAttribute('stroke-dasharray', this.options.dashArray);
4703 this._path.removeAttribute('stroke-dasharray');
4705 if (this.options.lineCap) {
4706 this._path.setAttribute('stroke-linecap', this.options.lineCap);
4708 if (this.options.lineJoin) {
4709 this._path.setAttribute('stroke-linejoin', this.options.lineJoin);
4712 this._path.setAttribute('stroke', 'none');
4714 if (this.options.fill) {
4715 this._path.setAttribute('fill', this.options.fillColor || this.options.color);
4716 this._path.setAttribute('fill-opacity', this.options.fillOpacity);
4718 this._path.setAttribute('fill', 'none');
4722 _updatePath: function () {
4723 var str = this.getPathString();
4725 // fix webkit empty string parsing bug
4728 this._path.setAttribute('d', str);
4731 // TODO remove duplication with L.Map
4732 _initEvents: function () {
4733 if (this.options.clickable) {
4734 if (L.Browser.svg || !L.Browser.vml) {
4735 L.DomUtil.addClass(this._path, 'leaflet-clickable');
4738 L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
4740 var events = ['dblclick', 'mousedown', 'mouseover',
4741 'mouseout', 'mousemove', 'contextmenu'];
4742 for (var i = 0; i < events.length; i++) {
4743 L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
4748 _onMouseClick: function (e) {
4749 if (this._map.dragging && this._map.dragging.moved()) { return; }
4751 this._fireMouseEvent(e);
4754 _fireMouseEvent: function (e) {
4755 if (!this.hasEventListeners(e.type)) { return; }
4757 var map = this._map,
4758 containerPoint = map.mouseEventToContainerPoint(e),
4759 layerPoint = map.containerPointToLayerPoint(containerPoint),
4760 latlng = map.layerPointToLatLng(layerPoint);
4764 layerPoint: layerPoint,
4765 containerPoint: containerPoint,
4769 if (e.type === 'contextmenu') {
4770 L.DomEvent.preventDefault(e);
4772 if (e.type !== 'mousemove') {
4773 L.DomEvent.stopPropagation(e);
4779 _initPathRoot: function () {
4780 if (!this._pathRoot) {
4781 this._pathRoot = L.Path.prototype._createElement('svg');
4782 this._panes.overlayPane.appendChild(this._pathRoot);
4784 if (this.options.zoomAnimation && L.Browser.any3d) {
4785 L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-animated');
4788 'zoomanim': this._animatePathZoom,
4789 'zoomend': this._endPathZoom
4792 L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-hide');
4795 this.on('moveend', this._updateSvgViewport);
4796 this._updateSvgViewport();
4800 _animatePathZoom: function (e) {
4801 var scale = this.getZoomScale(e.zoom),
4802 offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
4804 this._pathRoot.style[L.DomUtil.TRANSFORM] =
4805 L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
4807 this._pathZooming = true;
4810 _endPathZoom: function () {
4811 this._pathZooming = false;
4814 _updateSvgViewport: function () {
4816 if (this._pathZooming) {
4817 // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
4818 // When the zoom animation ends we will be updated again anyway
4819 // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
4823 this._updatePathViewport();
4825 var vp = this._pathViewport,
4828 width = max.x - min.x,
4829 height = max.y - min.y,
4830 root = this._pathRoot,
4831 pane = this._panes.overlayPane;
4833 // Hack to make flicker on drag end on mobile webkit less irritating
4834 if (L.Browser.mobileWebkit) {
4835 pane.removeChild(root);
4838 L.DomUtil.setPosition(root, min);
4839 root.setAttribute('width', width);
4840 root.setAttribute('height', height);
4841 root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
4843 if (L.Browser.mobileWebkit) {
4844 pane.appendChild(root);
4851 * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
4856 bindPopup: function (content, options) {
4858 if (content instanceof L.Popup) {
4859 this._popup = content;
4861 if (!this._popup || options) {
4862 this._popup = new L.Popup(options, this);
4864 this._popup.setContent(content);
4867 if (!this._popupHandlersAdded) {
4869 .on('click', this._openPopup, this)
4870 .on('remove', this.closePopup, this);
4872 this._popupHandlersAdded = true;
4878 unbindPopup: function () {
4882 .off('click', this._openPopup)
4883 .off('remove', this.closePopup);
4885 this._popupHandlersAdded = false;
4890 openPopup: function (latlng) {
4893 // open the popup from one of the path's points if not specified
4894 latlng = latlng || this._latlng ||
4895 this._latlngs[Math.floor(this._latlngs.length / 2)];
4897 this._openPopup({latlng: latlng});
4903 closePopup: function () {
4905 this._popup._close();
4910 _openPopup: function (e) {
4911 this._popup.setLatLng(e.latlng);
4912 this._map.openPopup(this._popup);
4918 * Vector rendering for IE6-8 through VML.
4919 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
4922 L.Browser.vml = !L.Browser.svg && (function () {
4924 var div = document.createElement('div');
4925 div.innerHTML = '<v:shape adj="1"/>';
4927 var shape = div.firstChild;
4928 shape.style.behavior = 'url(#default#VML)';
4930 return shape && (typeof shape.adj === 'object');
4937 L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
4943 _createElement: (function () {
4945 document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
4946 return function (name) {
4947 return document.createElement('<lvml:' + name + ' class="lvml">');
4950 return function (name) {
4951 return document.createElement(
4952 '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
4957 _initPath: function () {
4958 var container = this._container = this._createElement('shape');
4960 L.DomUtil.addClass(container, 'leaflet-vml-shape' +
4961 (this.options.className ? ' ' + this.options.className : ''));
4963 if (this.options.clickable) {
4964 L.DomUtil.addClass(container, 'leaflet-clickable');
4967 container.coordsize = '1 1';
4969 this._path = this._createElement('path');
4970 container.appendChild(this._path);
4972 this._map._pathRoot.appendChild(container);
4975 _initStyle: function () {
4976 this._updateStyle();
4979 _updateStyle: function () {
4980 var stroke = this._stroke,
4982 options = this.options,
4983 container = this._container;
4985 container.stroked = options.stroke;
4986 container.filled = options.fill;
4988 if (options.stroke) {
4990 stroke = this._stroke = this._createElement('stroke');
4991 stroke.endcap = 'round';
4992 container.appendChild(stroke);
4994 stroke.weight = options.weight + 'px';
4995 stroke.color = options.color;
4996 stroke.opacity = options.opacity;
4998 if (options.dashArray) {
4999 stroke.dashStyle = L.Util.isArray(options.dashArray) ?
5000 options.dashArray.join(' ') :
5001 options.dashArray.replace(/( *, *)/g, ' ');
5003 stroke.dashStyle = '';
5005 if (options.lineCap) {
5006 stroke.endcap = options.lineCap.replace('butt', 'flat');
5008 if (options.lineJoin) {
5009 stroke.joinstyle = options.lineJoin;
5012 } else if (stroke) {
5013 container.removeChild(stroke);
5014 this._stroke = null;
5019 fill = this._fill = this._createElement('fill');
5020 container.appendChild(fill);
5022 fill.color = options.fillColor || options.color;
5023 fill.opacity = options.fillOpacity;
5026 container.removeChild(fill);
5031 _updatePath: function () {
5032 var style = this._container.style;
5034 style.display = 'none';
5035 this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
5040 L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
5041 _initPathRoot: function () {
5042 if (this._pathRoot) { return; }
5044 var root = this._pathRoot = document.createElement('div');
5045 root.className = 'leaflet-vml-container';
5046 this._panes.overlayPane.appendChild(root);
5048 this.on('moveend', this._updatePathViewport);
5049 this._updatePathViewport();
5055 * Vector rendering for all browsers that support canvas.
5058 L.Browser.canvas = (function () {
5059 return !!document.createElement('canvas').getContext;
5062 L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
5064 //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
5069 redraw: function () {
5071 this.projectLatlngs();
5072 this._requestUpdate();
5077 setStyle: function (style) {
5078 L.setOptions(this, style);
5081 this._updateStyle();
5082 this._requestUpdate();
5087 onRemove: function (map) {
5089 .off('viewreset', this.projectLatlngs, this)
5090 .off('moveend', this._updatePath, this);
5092 if (this.options.clickable) {
5093 this._map.off('click', this._onClick, this);
5094 this._map.off('mousemove', this._onMouseMove, this);
5097 this._requestUpdate();
5102 _requestUpdate: function () {
5103 if (this._map && !L.Path._updateRequest) {
5104 L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
5108 _fireMapMoveEnd: function () {
5109 L.Path._updateRequest = null;
5110 this.fire('moveend');
5113 _initElements: function () {
5114 this._map._initPathRoot();
5115 this._ctx = this._map._canvasCtx;
5118 _updateStyle: function () {
5119 var options = this.options;
5121 if (options.stroke) {
5122 this._ctx.lineWidth = options.weight;
5123 this._ctx.strokeStyle = options.color;
5126 this._ctx.fillStyle = options.fillColor || options.color;
5130 _drawPath: function () {
5131 var i, j, len, len2, point, drawMethod;
5133 this._ctx.beginPath();
5135 for (i = 0, len = this._parts.length; i < len; i++) {
5136 for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
5137 point = this._parts[i][j];
5138 drawMethod = (j === 0 ? 'move' : 'line') + 'To';
5140 this._ctx[drawMethod](point.x, point.y);
5142 // TODO refactor ugly hack
5143 if (this instanceof L.Polygon) {
5144 this._ctx.closePath();
5149 _checkIfEmpty: function () {
5150 return !this._parts.length;
5153 _updatePath: function () {
5154 if (this._checkIfEmpty()) { return; }
5156 var ctx = this._ctx,
5157 options = this.options;
5161 this._updateStyle();
5164 ctx.globalAlpha = options.fillOpacity;
5168 if (options.stroke) {
5169 ctx.globalAlpha = options.opacity;
5175 // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
5178 _initEvents: function () {
5179 if (this.options.clickable) {
5181 this._map.on('mousemove', this._onMouseMove, this);
5182 this._map.on('click', this._onClick, this);
5186 _onClick: function (e) {
5187 if (this._containsPoint(e.layerPoint)) {
5188 this.fire('click', e);
5192 _onMouseMove: function (e) {
5193 if (!this._map || this._map._animatingZoom) { return; }
5195 // TODO don't do on each move
5196 if (this._containsPoint(e.layerPoint)) {
5197 this._ctx.canvas.style.cursor = 'pointer';
5198 this._mouseInside = true;
5199 this.fire('mouseover', e);
5201 } else if (this._mouseInside) {
5202 this._ctx.canvas.style.cursor = '';
5203 this._mouseInside = false;
5204 this.fire('mouseout', e);
5209 L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
5210 _initPathRoot: function () {
5211 var root = this._pathRoot,
5215 root = this._pathRoot = document.createElement('canvas');
5216 root.style.position = 'absolute';
5217 ctx = this._canvasCtx = root.getContext('2d');
5219 ctx.lineCap = 'round';
5220 ctx.lineJoin = 'round';
5222 this._panes.overlayPane.appendChild(root);
5224 if (this.options.zoomAnimation) {
5225 this._pathRoot.className = 'leaflet-zoom-animated';
5226 this.on('zoomanim', this._animatePathZoom);
5227 this.on('zoomend', this._endPathZoom);
5229 this.on('moveend', this._updateCanvasViewport);
5230 this._updateCanvasViewport();
5234 _updateCanvasViewport: function () {
5235 // don't redraw while zooming. See _updateSvgViewport for more details
5236 if (this._pathZooming) { return; }
5237 this._updatePathViewport();
5239 var vp = this._pathViewport,
5241 size = vp.max.subtract(min),
5242 root = this._pathRoot;
5244 //TODO check if this works properly on mobile webkit
5245 L.DomUtil.setPosition(root, min);
5246 root.width = size.x;
5247 root.height = size.y;
5248 root.getContext('2d').translate(-min.x, -min.y);
5254 * L.LineUtil contains different utility functions for line segments
5255 * and polylines (clipping, simplification, distances, etc.)
5258 /*jshint bitwise:false */ // allow bitwise oprations for this file
5262 // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
5263 // Improves rendering performance dramatically by lessening the number of points to draw.
5265 simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
5266 if (!tolerance || !points.length) {
5267 return points.slice();
5270 var sqTolerance = tolerance * tolerance;
5272 // stage 1: vertex reduction
5273 points = this._reducePoints(points, sqTolerance);
5275 // stage 2: Douglas-Peucker simplification
5276 points = this._simplifyDP(points, sqTolerance);
5281 // distance from a point to a segment between two points
5282 pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5283 return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
5286 closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
5287 return this._sqClosestPointOnSegment(p, p1, p2);
5290 // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
5291 _simplifyDP: function (points, sqTolerance) {
5293 var len = points.length,
5294 ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
5295 markers = new ArrayConstructor(len);
5297 markers[0] = markers[len - 1] = 1;
5299 this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
5304 for (i = 0; i < len; i++) {
5306 newPoints.push(points[i]);
5313 _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
5318 for (i = first + 1; i <= last - 1; i++) {
5319 sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
5321 if (sqDist > maxSqDist) {
5327 if (maxSqDist > sqTolerance) {
5330 this._simplifyDPStep(points, markers, sqTolerance, first, index);
5331 this._simplifyDPStep(points, markers, sqTolerance, index, last);
5335 // reduce points that are too close to each other to a single point
5336 _reducePoints: function (points, sqTolerance) {
5337 var reducedPoints = [points[0]];
5339 for (var i = 1, prev = 0, len = points.length; i < len; i++) {
5340 if (this._sqDist(points[i], points[prev]) > sqTolerance) {
5341 reducedPoints.push(points[i]);
5345 if (prev < len - 1) {
5346 reducedPoints.push(points[len - 1]);
5348 return reducedPoints;
5351 // Cohen-Sutherland line clipping algorithm.
5352 // Used to avoid rendering parts of a polyline that are not currently visible.
5354 clipSegment: function (a, b, bounds, useLastCode) {
5355 var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
5356 codeB = this._getBitCode(b, bounds),
5358 codeOut, p, newCode;
5360 // save 2nd code to avoid calculating it on the next segment
5361 this._lastCode = codeB;
5364 // if a,b is inside the clip window (trivial accept)
5365 if (!(codeA | codeB)) {
5367 // if a,b is outside the clip window (trivial reject)
5368 } else if (codeA & codeB) {
5372 codeOut = codeA || codeB;
5373 p = this._getEdgeIntersection(a, b, codeOut, bounds);
5374 newCode = this._getBitCode(p, bounds);
5376 if (codeOut === codeA) {
5387 _getEdgeIntersection: function (a, b, code, bounds) {
5393 if (code & 8) { // top
5394 return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
5395 } else if (code & 4) { // bottom
5396 return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
5397 } else if (code & 2) { // right
5398 return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
5399 } else if (code & 1) { // left
5400 return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
5404 _getBitCode: function (/*Point*/ p, bounds) {
5407 if (p.x < bounds.min.x) { // left
5409 } else if (p.x > bounds.max.x) { // right
5412 if (p.y < bounds.min.y) { // bottom
5414 } else if (p.y > bounds.max.y) { // top
5421 // square distance (to avoid unnecessary Math.sqrt calls)
5422 _sqDist: function (p1, p2) {
5423 var dx = p2.x - p1.x,
5425 return dx * dx + dy * dy;
5428 // return closest point on segment or distance to that point
5429 _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
5434 dot = dx * dx + dy * dy,
5438 t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
5452 return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
5458 * L.Polyline is used to display polylines on a map.
5461 L.Polyline = L.Path.extend({
5462 initialize: function (latlngs, options) {
5463 L.Path.prototype.initialize.call(this, options);
5465 this._latlngs = this._convertLatLngs(latlngs);
5469 // how much to simplify the polyline on each zoom level
5470 // more = better performance and smoother look, less = more accurate
5475 projectLatlngs: function () {
5476 this._originalPoints = [];
5478 for (var i = 0, len = this._latlngs.length; i < len; i++) {
5479 this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
5483 getPathString: function () {
5484 for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
5485 str += this._getPathPartStr(this._parts[i]);
5490 getLatLngs: function () {
5491 return this._latlngs;
5494 setLatLngs: function (latlngs) {
5495 this._latlngs = this._convertLatLngs(latlngs);
5496 return this.redraw();
5499 addLatLng: function (latlng) {
5500 this._latlngs.push(L.latLng(latlng));
5501 return this.redraw();
5504 spliceLatLngs: function () { // (Number index, Number howMany)
5505 var removed = [].splice.apply(this._latlngs, arguments);
5506 this._convertLatLngs(this._latlngs, true);
5511 closestLayerPoint: function (p) {
5512 var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
5514 for (var j = 0, jLen = parts.length; j < jLen; j++) {
5515 var points = parts[j];
5516 for (var i = 1, len = points.length; i < len; i++) {
5519 var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
5520 if (sqDist < minDistance) {
5521 minDistance = sqDist;
5522 minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
5527 minPoint.distance = Math.sqrt(minDistance);
5532 getBounds: function () {
5533 return new L.LatLngBounds(this.getLatLngs());
5536 _convertLatLngs: function (latlngs, overwrite) {
5537 var i, len, target = overwrite ? latlngs : [];
5539 for (i = 0, len = latlngs.length; i < len; i++) {
5540 if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
5543 target[i] = L.latLng(latlngs[i]);
5548 _initEvents: function () {
5549 L.Path.prototype._initEvents.call(this);
5552 _getPathPartStr: function (points) {
5553 var round = L.Path.VML;
5555 for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
5560 str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
5565 _clipPoints: function () {
5566 var points = this._originalPoints,
5567 len = points.length,
5570 if (this.options.noClip) {
5571 this._parts = [points];
5577 var parts = this._parts,
5578 vp = this._map._pathViewport,
5581 for (i = 0, k = 0; i < len - 1; i++) {
5582 segment = lu.clipSegment(points[i], points[i + 1], vp, i);
5587 parts[k] = parts[k] || [];
5588 parts[k].push(segment[0]);
5590 // if segment goes out of screen, or it's the last one, it's the end of the line part
5591 if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
5592 parts[k].push(segment[1]);
5598 // simplify each clipped part of the polyline
5599 _simplifyPoints: function () {
5600 var parts = this._parts,
5603 for (var i = 0, len = parts.length; i < len; i++) {
5604 parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
5608 _updatePath: function () {
5609 if (!this._map) { return; }
5612 this._simplifyPoints();
5614 L.Path.prototype._updatePath.call(this);
5618 L.polyline = function (latlngs, options) {
5619 return new L.Polyline(latlngs, options);
5624 * L.PolyUtil contains utility functions for polygons (clipping, etc.).
5627 /*jshint bitwise:false */ // allow bitwise operations here
5632 * Sutherland-Hodgeman polygon clipping algorithm.
5633 * Used to avoid rendering parts of a polygon that are not currently visible.
5635 L.PolyUtil.clipPolygon = function (points, bounds) {
5637 edges = [1, 4, 2, 8],
5643 for (i = 0, len = points.length; i < len; i++) {
5644 points[i]._code = lu._getBitCode(points[i], bounds);
5647 // for each edge (left, bottom, right, top)
5648 for (k = 0; k < 4; k++) {
5652 for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
5656 // if a is inside the clip window
5657 if (!(a._code & edge)) {
5658 // if b is outside the clip window (a->b goes out of screen)
5659 if (b._code & edge) {
5660 p = lu._getEdgeIntersection(b, a, edge, bounds);
5661 p._code = lu._getBitCode(p, bounds);
5662 clippedPoints.push(p);
5664 clippedPoints.push(a);
5666 // else if b is inside the clip window (a->b enters the screen)
5667 } else if (!(b._code & edge)) {
5668 p = lu._getEdgeIntersection(b, a, edge, bounds);
5669 p._code = lu._getBitCode(p, bounds);
5670 clippedPoints.push(p);
5673 points = clippedPoints;
5681 * L.Polygon is used to display polygons on a map.
5684 L.Polygon = L.Polyline.extend({
5689 initialize: function (latlngs, options) {
5690 L.Polyline.prototype.initialize.call(this, latlngs, options);
5691 this._initWithHoles(latlngs);
5694 _initWithHoles: function (latlngs) {
5696 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5697 this._latlngs = this._convertLatLngs(latlngs[0]);
5698 this._holes = latlngs.slice(1);
5700 for (i = 0, len = this._holes.length; i < len; i++) {
5701 hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
5702 if (hole[0].equals(hole[hole.length - 1])) {
5708 // filter out last point if its equal to the first one
5709 latlngs = this._latlngs;
5711 if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
5716 projectLatlngs: function () {
5717 L.Polyline.prototype.projectLatlngs.call(this);
5719 // project polygon holes points
5720 // TODO move this logic to Polyline to get rid of duplication
5721 this._holePoints = [];
5723 if (!this._holes) { return; }
5725 var i, j, len, len2;
5727 for (i = 0, len = this._holes.length; i < len; i++) {
5728 this._holePoints[i] = [];
5730 for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
5731 this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
5736 setLatLngs: function (latlngs) {
5737 if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
5738 this._initWithHoles(latlngs);
5739 return this.redraw();
5741 return L.Polyline.prototype.setLatLngs.call(this, latlngs);
5745 _clipPoints: function () {
5746 var points = this._originalPoints,
5749 this._parts = [points].concat(this._holePoints);
5751 if (this.options.noClip) { return; }
5753 for (var i = 0, len = this._parts.length; i < len; i++) {
5754 var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
5755 if (clipped.length) {
5756 newParts.push(clipped);
5760 this._parts = newParts;
5763 _getPathPartStr: function (points) {
5764 var str = L.Polyline.prototype._getPathPartStr.call(this, points);
5765 return str + (L.Browser.svg ? 'z' : 'x');
5769 L.polygon = function (latlngs, options) {
5770 return new L.Polygon(latlngs, options);
5775 * Contains L.MultiPolyline and L.MultiPolygon layers.
5779 function createMulti(Klass) {
5781 return L.FeatureGroup.extend({
5783 initialize: function (latlngs, options) {
5785 this._options = options;
5786 this.setLatLngs(latlngs);
5789 setLatLngs: function (latlngs) {
5791 len = latlngs.length;
5793 this.eachLayer(function (layer) {
5795 layer.setLatLngs(latlngs[i++]);
5797 this.removeLayer(layer);
5802 this.addLayer(new Klass(latlngs[i++], this._options));
5808 getLatLngs: function () {
5811 this.eachLayer(function (layer) {
5812 latlngs.push(layer.getLatLngs());
5820 L.MultiPolyline = createMulti(L.Polyline);
5821 L.MultiPolygon = createMulti(L.Polygon);
5823 L.multiPolyline = function (latlngs, options) {
5824 return new L.MultiPolyline(latlngs, options);
5827 L.multiPolygon = function (latlngs, options) {
5828 return new L.MultiPolygon(latlngs, options);
5834 * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
5837 L.Rectangle = L.Polygon.extend({
5838 initialize: function (latLngBounds, options) {
5839 L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
5842 setBounds: function (latLngBounds) {
5843 this.setLatLngs(this._boundsToLatLngs(latLngBounds));
5846 _boundsToLatLngs: function (latLngBounds) {
5847 latLngBounds = L.latLngBounds(latLngBounds);
5849 latLngBounds.getSouthWest(),
5850 latLngBounds.getNorthWest(),
5851 latLngBounds.getNorthEast(),
5852 latLngBounds.getSouthEast()
5857 L.rectangle = function (latLngBounds, options) {
5858 return new L.Rectangle(latLngBounds, options);
5863 * L.Circle is a circle overlay (with a certain radius in meters).
5866 L.Circle = L.Path.extend({
5867 initialize: function (latlng, radius, options) {
5868 L.Path.prototype.initialize.call(this, options);
5870 this._latlng = L.latLng(latlng);
5871 this._mRadius = radius;
5878 setLatLng: function (latlng) {
5879 this._latlng = L.latLng(latlng);
5880 return this.redraw();
5883 setRadius: function (radius) {
5884 this._mRadius = radius;
5885 return this.redraw();
5888 projectLatlngs: function () {
5889 var lngRadius = this._getLngRadius(),
5890 latlng = this._latlng,
5891 pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
5893 this._point = this._map.latLngToLayerPoint(latlng);
5894 this._radius = Math.max(this._point.x - pointLeft.x, 1);
5897 getBounds: function () {
5898 var lngRadius = this._getLngRadius(),
5899 latRadius = (this._mRadius / 40075017) * 360,
5900 latlng = this._latlng;
5902 return new L.LatLngBounds(
5903 [latlng.lat - latRadius, latlng.lng - lngRadius],
5904 [latlng.lat + latRadius, latlng.lng + lngRadius]);
5907 getLatLng: function () {
5908 return this._latlng;
5911 getPathString: function () {
5912 var p = this._point,
5915 if (this._checkIfEmpty()) {
5919 if (L.Browser.svg) {
5920 return 'M' + p.x + ',' + (p.y - r) +
5921 'A' + r + ',' + r + ',0,1,1,' +
5922 (p.x - 0.1) + ',' + (p.y - r) + ' z';
5926 return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
5930 getRadius: function () {
5931 return this._mRadius;
5934 // TODO Earth hardcoded, move into projection code!
5936 _getLatRadius: function () {
5937 return (this._mRadius / 40075017) * 360;
5940 _getLngRadius: function () {
5941 return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
5944 _checkIfEmpty: function () {
5948 var vp = this._map._pathViewport,
5952 return p.x - r > vp.max.x || p.y - r > vp.max.y ||
5953 p.x + r < vp.min.x || p.y + r < vp.min.y;
5957 L.circle = function (latlng, radius, options) {
5958 return new L.Circle(latlng, radius, options);
5963 * L.CircleMarker is a circle overlay with a permanent pixel radius.
5966 L.CircleMarker = L.Circle.extend({
5972 initialize: function (latlng, options) {
5973 L.Circle.prototype.initialize.call(this, latlng, null, options);
5974 this._radius = this.options.radius;
5977 projectLatlngs: function () {
5978 this._point = this._map.latLngToLayerPoint(this._latlng);
5981 _updateStyle : function () {
5982 L.Circle.prototype._updateStyle.call(this);
5983 this.setRadius(this.options.radius);
5986 setLatLng: function (latlng) {
5987 L.Circle.prototype.setLatLng.call(this, latlng);
5988 if (this._popup && this._popup._isOpen) {
5989 this._popup.setLatLng(latlng);
5993 setRadius: function (radius) {
5994 this.options.radius = this._radius = radius;
5995 return this.redraw();
5998 getRadius: function () {
5999 return this._radius;
6003 L.circleMarker = function (latlng, options) {
6004 return new L.CircleMarker(latlng, options);
6009 * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
6012 L.Polyline.include(!L.Path.CANVAS ? {} : {
6013 _containsPoint: function (p, closed) {
6014 var i, j, k, len, len2, dist, part,
6015 w = this.options.weight / 2;
6017 if (L.Browser.touch) {
6018 w += 10; // polyline click tolerance on touch devices
6021 for (i = 0, len = this._parts.length; i < len; i++) {
6022 part = this._parts[i];
6023 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
6024 if (!closed && (j === 0)) {
6028 dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
6041 * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
6044 L.Polygon.include(!L.Path.CANVAS ? {} : {
6045 _containsPoint: function (p) {
6051 // TODO optimization: check if within bounds first
6053 if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
6054 // click on polygon border
6058 // ray casting algorithm for detecting if point is in polygon
6060 for (i = 0, len = this._parts.length; i < len; i++) {
6061 part = this._parts[i];
6063 for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
6067 if (((p1.y > p.y) !== (p2.y > p.y)) &&
6068 (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
6080 * Extends L.Circle with Canvas-specific code.
6083 L.Circle.include(!L.Path.CANVAS ? {} : {
6084 _drawPath: function () {
6085 var p = this._point;
6086 this._ctx.beginPath();
6087 this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
6090 _containsPoint: function (p) {
6091 var center = this._point,
6092 w2 = this.options.stroke ? this.options.weight / 2 : 0;
6094 return (p.distanceTo(center) <= this._radius + w2);
6100 * CircleMarker canvas specific drawing parts.
6103 L.CircleMarker.include(!L.Path.CANVAS ? {} : {
6104 _updateStyle: function () {
6105 L.Path.prototype._updateStyle.call(this);
6111 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
6114 L.GeoJSON = L.FeatureGroup.extend({
6116 initialize: function (geojson, options) {
6117 L.setOptions(this, options);
6122 this.addData(geojson);
6126 addData: function (geojson) {
6127 var features = L.Util.isArray(geojson) ? geojson : geojson.features,
6131 for (i = 0, len = features.length; i < len; i++) {
6132 // Only add this if geometry or geometries are set and not null
6133 feature = features[i];
6134 if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
6135 this.addData(features[i]);
6141 var options = this.options;
6143 if (options.filter && !options.filter(geojson)) { return; }
6145 var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng, options);
6146 layer.feature = L.GeoJSON.asFeature(geojson);
6148 layer.defaultOptions = layer.options;
6149 this.resetStyle(layer);
6151 if (options.onEachFeature) {
6152 options.onEachFeature(geojson, layer);
6155 return this.addLayer(layer);
6158 resetStyle: function (layer) {
6159 var style = this.options.style;
6161 // reset any custom styles
6162 L.Util.extend(layer.options, layer.defaultOptions);
6164 this._setLayerStyle(layer, style);
6168 setStyle: function (style) {
6169 this.eachLayer(function (layer) {
6170 this._setLayerStyle(layer, style);
6174 _setLayerStyle: function (layer, style) {
6175 if (typeof style === 'function') {
6176 style = style(layer.feature);
6178 if (layer.setStyle) {
6179 layer.setStyle(style);
6184 L.extend(L.GeoJSON, {
6185 geometryToLayer: function (geojson, pointToLayer, coordsToLatLng, vectorOptions) {
6186 var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
6187 coords = geometry.coordinates,
6189 latlng, latlngs, i, len;
6191 coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
6193 switch (geometry.type) {
6195 latlng = coordsToLatLng(coords);
6196 return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
6199 for (i = 0, len = coords.length; i < len; i++) {
6200 latlng = coordsToLatLng(coords[i]);
6201 layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng));
6203 return new L.FeatureGroup(layers);
6206 latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
6207 return new L.Polyline(latlngs, vectorOptions);
6210 if (coords.length === 2 && !coords[1].length) {
6211 throw new Error('Invalid GeoJSON object.');
6213 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6214 return new L.Polygon(latlngs, vectorOptions);
6216 case 'MultiLineString':
6217 latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
6218 return new L.MultiPolyline(latlngs, vectorOptions);
6220 case 'MultiPolygon':
6221 latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
6222 return new L.MultiPolygon(latlngs, vectorOptions);
6224 case 'GeometryCollection':
6225 for (i = 0, len = geometry.geometries.length; i < len; i++) {
6227 layers.push(this.geometryToLayer({
6228 geometry: geometry.geometries[i],
6230 properties: geojson.properties
6231 }, pointToLayer, coordsToLatLng, vectorOptions));
6233 return new L.FeatureGroup(layers);
6236 throw new Error('Invalid GeoJSON object.');
6240 coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
6241 return new L.LatLng(coords[1], coords[0], coords[2]);
6244 coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
6248 for (i = 0, len = coords.length; i < len; i++) {
6249 latlng = levelsDeep ?
6250 this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
6251 (coordsToLatLng || this.coordsToLatLng)(coords[i]);
6253 latlngs.push(latlng);
6259 latLngToCoords: function (latlng) {
6260 var coords = [latlng.lng, latlng.lat];
6262 if (latlng.alt !== undefined) {
6263 coords.push(latlng.alt);
6268 latLngsToCoords: function (latLngs) {
6271 for (var i = 0, len = latLngs.length; i < len; i++) {
6272 coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
6278 getFeature: function (layer, newGeometry) {
6279 return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
6282 asFeature: function (geoJSON) {
6283 if (geoJSON.type === 'Feature') {
6295 var PointToGeoJSON = {
6296 toGeoJSON: function () {
6297 return L.GeoJSON.getFeature(this, {
6299 coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
6304 L.Marker.include(PointToGeoJSON);
6305 L.Circle.include(PointToGeoJSON);
6306 L.CircleMarker.include(PointToGeoJSON);
6308 L.Polyline.include({
6309 toGeoJSON: function () {
6310 return L.GeoJSON.getFeature(this, {
6312 coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
6318 toGeoJSON: function () {
6319 var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
6322 coords[0].push(coords[0][0]);
6325 for (i = 0, len = this._holes.length; i < len; i++) {
6326 hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
6332 return L.GeoJSON.getFeature(this, {
6340 function multiToGeoJSON(type) {
6341 return function () {
6344 this.eachLayer(function (layer) {
6345 coords.push(layer.toGeoJSON().geometry.coordinates);
6348 return L.GeoJSON.getFeature(this, {
6355 L.MultiPolyline.include({toGeoJSON: multiToGeoJSON('MultiLineString')});
6356 L.MultiPolygon.include({toGeoJSON: multiToGeoJSON('MultiPolygon')});
6358 L.LayerGroup.include({
6359 toGeoJSON: function () {
6361 var geometry = this.feature && this.feature.geometry,
6365 if (geometry && geometry.type === 'MultiPoint') {
6366 return multiToGeoJSON('MultiPoint').call(this);
6369 var isGeometryCollection = geometry && geometry.type === 'GeometryCollection';
6371 this.eachLayer(function (layer) {
6372 if (layer.toGeoJSON) {
6373 json = layer.toGeoJSON();
6374 jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
6378 if (isGeometryCollection) {
6379 return L.GeoJSON.getFeature(this, {
6381 type: 'GeometryCollection'
6386 type: 'FeatureCollection',
6393 L.geoJson = function (geojson, options) {
6394 return new L.GeoJSON(geojson, options);
6399 * L.DomEvent contains functions for working with DOM events.
6403 /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
6404 addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
6406 var id = L.stamp(fn),
6407 key = '_leaflet_' + type + id,
6408 handler, originalHandler, newType;
6410 if (obj[key]) { return this; }
6412 handler = function (e) {
6413 return fn.call(context || obj, e || L.DomEvent._getEvent());
6416 if (L.Browser.pointer && type.indexOf('touch') === 0) {
6417 return this.addPointerListener(obj, type, handler, id);
6419 if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
6420 this.addDoubleTapListener(obj, handler, id);
6423 if ('addEventListener' in obj) {
6425 if (type === 'mousewheel') {
6426 obj.addEventListener('DOMMouseScroll', handler, false);
6427 obj.addEventListener(type, handler, false);
6429 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6431 originalHandler = handler;
6432 newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
6434 handler = function (e) {
6435 if (!L.DomEvent._checkMouse(obj, e)) { return; }
6436 return originalHandler(e);
6439 obj.addEventListener(newType, handler, false);
6441 } else if (type === 'click' && L.Browser.android) {
6442 originalHandler = handler;
6443 handler = function (e) {
6444 return L.DomEvent._filterClick(e, originalHandler);
6447 obj.addEventListener(type, handler, false);
6449 obj.addEventListener(type, handler, false);
6452 } else if ('attachEvent' in obj) {
6453 obj.attachEvent('on' + type, handler);
6461 removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
6463 var id = L.stamp(fn),
6464 key = '_leaflet_' + type + id,
6467 if (!handler) { return this; }
6469 if (L.Browser.pointer && type.indexOf('touch') === 0) {
6470 this.removePointerListener(obj, type, id);
6471 } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
6472 this.removeDoubleTapListener(obj, id);
6474 } else if ('removeEventListener' in obj) {
6476 if (type === 'mousewheel') {
6477 obj.removeEventListener('DOMMouseScroll', handler, false);
6478 obj.removeEventListener(type, handler, false);
6480 } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
6481 obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
6483 obj.removeEventListener(type, handler, false);
6485 } else if ('detachEvent' in obj) {
6486 obj.detachEvent('on' + type, handler);
6494 stopPropagation: function (e) {
6496 if (e.stopPropagation) {
6497 e.stopPropagation();
6499 e.cancelBubble = true;
6501 L.DomEvent._skipped(e);
6506 disableScrollPropagation: function (el) {
6507 var stop = L.DomEvent.stopPropagation;
6510 .on(el, 'mousewheel', stop)
6511 .on(el, 'MozMousePixelScroll', stop);
6514 disableClickPropagation: function (el) {
6515 var stop = L.DomEvent.stopPropagation;
6517 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6518 L.DomEvent.on(el, L.Draggable.START[i], stop);
6522 .on(el, 'click', L.DomEvent._fakeStop)
6523 .on(el, 'dblclick', stop);
6526 preventDefault: function (e) {
6528 if (e.preventDefault) {
6531 e.returnValue = false;
6536 stop: function (e) {
6539 .stopPropagation(e);
6542 getMousePosition: function (e, container) {
6543 var body = document.body,
6544 docEl = document.documentElement,
6545 //gecko makes scrollLeft more negative as you scroll in rtl, other browsers don't
6546 //ref: https://code.google.com/p/closure-library/source/browse/closure/goog/style/bidi.js
6547 x = L.DomUtil.documentIsLtr() ?
6548 (e.pageX ? e.pageX - body.scrollLeft - docEl.scrollLeft : e.clientX) :
6549 (L.Browser.gecko ? e.pageX - body.scrollLeft - docEl.scrollLeft :
6550 e.pageX ? e.pageX - body.scrollLeft + docEl.scrollLeft : e.clientX),
6551 y = e.pageY ? e.pageY - body.scrollTop - docEl.scrollTop: e.clientY,
6552 pos = new L.Point(x, y);
6558 var rect = container.getBoundingClientRect(),
6559 left = rect.left - container.clientLeft,
6560 top = rect.top - container.clientTop;
6562 return pos._subtract(new L.Point(left, top));
6565 getWheelDelta: function (e) {
6570 delta = e.wheelDelta / 120;
6573 delta = -e.detail / 3;
6580 _fakeStop: function (e) {
6581 // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
6582 L.DomEvent._skipEvents[e.type] = true;
6585 _skipped: function (e) {
6586 var skipped = this._skipEvents[e.type];
6587 // reset when checking, as it's only used in map container and propagates outside of the map
6588 this._skipEvents[e.type] = false;
6592 // check if element really left/entered the event target (for mouseenter/mouseleave)
6593 _checkMouse: function (el, e) {
6595 var related = e.relatedTarget;
6597 if (!related) { return true; }
6600 while (related && (related !== el)) {
6601 related = related.parentNode;
6606 return (related !== el);
6609 _getEvent: function () { // evil magic for IE
6610 /*jshint noarg:false */
6611 var e = window.event;
6613 var caller = arguments.callee.caller;
6615 e = caller['arguments'][0];
6616 if (e && window.Event === e.constructor) {
6619 caller = caller.caller;
6625 // this is a horrible workaround for a bug in Android where a single touch triggers two click events
6626 _filterClick: function (e, handler) {
6627 var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
6628 elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
6630 // are they closer together than 1000ms yet more than 100ms?
6631 // Android typically triggers them ~300ms apart while multiple listeners
6632 // on the same event should be triggered far faster;
6633 // or check if click is simulated on the element, and if it is, reject any non-simulated events
6635 if ((elapsed && elapsed > 100 && elapsed < 1000) || (e.target._simulatedClick && !e._simulated)) {
6639 L.DomEvent._lastClick = timeStamp;
6645 L.DomEvent.on = L.DomEvent.addListener;
6646 L.DomEvent.off = L.DomEvent.removeListener;
6650 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
6653 L.Draggable = L.Class.extend({
6654 includes: L.Mixin.Events,
6657 START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
6659 mousedown: 'mouseup',
6660 touchstart: 'touchend',
6661 pointerdown: 'touchend',
6662 MSPointerDown: 'touchend'
6665 mousedown: 'mousemove',
6666 touchstart: 'touchmove',
6667 pointerdown: 'touchmove',
6668 MSPointerDown: 'touchmove'
6672 initialize: function (element, dragStartTarget) {
6673 this._element = element;
6674 this._dragStartTarget = dragStartTarget || element;
6677 enable: function () {
6678 if (this._enabled) { return; }
6680 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6681 L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6684 this._enabled = true;
6687 disable: function () {
6688 if (!this._enabled) { return; }
6690 for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
6691 L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
6694 this._enabled = false;
6695 this._moved = false;
6698 _onDown: function (e) {
6699 this._moved = false;
6701 if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
6703 L.DomEvent.stopPropagation(e);
6705 if (L.Draggable._disabled) { return; }
6707 L.DomUtil.disableImageDrag();
6708 L.DomUtil.disableTextSelection();
6710 if (this._moving) { return; }
6712 var first = e.touches ? e.touches[0] : e;
6714 this._startPoint = new L.Point(first.clientX, first.clientY);
6715 this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
6718 .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
6719 .on(document, L.Draggable.END[e.type], this._onUp, this);
6722 _onMove: function (e) {
6723 if (e.touches && e.touches.length > 1) {
6728 var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
6729 newPoint = new L.Point(first.clientX, first.clientY),
6730 offset = newPoint.subtract(this._startPoint);
6732 if (!offset.x && !offset.y) { return; }
6734 L.DomEvent.preventDefault(e);
6737 this.fire('dragstart');
6740 this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
6742 L.DomUtil.addClass(document.body, 'leaflet-dragging');
6743 L.DomUtil.addClass((e.target || e.srcElement), 'leaflet-drag-target');
6746 this._newPos = this._startPos.add(offset);
6747 this._moving = true;
6749 L.Util.cancelAnimFrame(this._animRequest);
6750 this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
6753 _updatePosition: function () {
6754 this.fire('predrag');
6755 L.DomUtil.setPosition(this._element, this._newPos);
6759 _onUp: function (e) {
6760 L.DomUtil.removeClass(document.body, 'leaflet-dragging');
6761 L.DomUtil.removeClass((e.target || e.srcElement), 'leaflet-drag-target');
6763 for (var i in L.Draggable.MOVE) {
6765 .off(document, L.Draggable.MOVE[i], this._onMove)
6766 .off(document, L.Draggable.END[i], this._onUp);
6769 L.DomUtil.enableImageDrag();
6770 L.DomUtil.enableTextSelection();
6773 // ensure drag is not fired after dragend
6774 L.Util.cancelAnimFrame(this._animRequest);
6776 this.fire('dragend', {
6777 distance: this._newPos.distanceTo(this._startPos)
6781 this._moving = false;
6787 L.Handler is a base class for handler classes that are used internally to inject
6788 interaction features like dragging to classes like Map and Marker.
6791 L.Handler = L.Class.extend({
6792 initialize: function (map) {
6796 enable: function () {
6797 if (this._enabled) { return; }
6799 this._enabled = true;
6803 disable: function () {
6804 if (!this._enabled) { return; }
6806 this._enabled = false;
6810 enabled: function () {
6811 return !!this._enabled;
6817 * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
6820 L.Map.mergeOptions({
6823 inertia: !L.Browser.android23,
6824 inertiaDeceleration: 3400, // px/s^2
6825 inertiaMaxSpeed: Infinity, // px/s
6826 inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
6827 easeLinearity: 0.25,
6829 // TODO refactor, move to CRS
6830 worldCopyJump: false
6833 L.Map.Drag = L.Handler.extend({
6834 addHooks: function () {
6835 if (!this._draggable) {
6836 var map = this._map;
6838 this._draggable = new L.Draggable(map._mapPane, map._container);
6840 this._draggable.on({
6841 'dragstart': this._onDragStart,
6842 'drag': this._onDrag,
6843 'dragend': this._onDragEnd
6846 if (map.options.worldCopyJump) {
6847 this._draggable.on('predrag', this._onPreDrag, this);
6848 map.on('viewreset', this._onViewReset, this);
6850 map.whenReady(this._onViewReset, this);
6853 this._draggable.enable();
6856 removeHooks: function () {
6857 this._draggable.disable();
6860 moved: function () {
6861 return this._draggable && this._draggable._moved;
6864 _onDragStart: function () {
6865 var map = this._map;
6868 map._panAnim.stop();
6875 if (map.options.inertia) {
6876 this._positions = [];
6881 _onDrag: function () {
6882 if (this._map.options.inertia) {
6883 var time = this._lastTime = +new Date(),
6884 pos = this._lastPos = this._draggable._newPos;
6886 this._positions.push(pos);
6887 this._times.push(time);
6889 if (time - this._times[0] > 200) {
6890 this._positions.shift();
6891 this._times.shift();
6900 _onViewReset: function () {
6901 // TODO fix hardcoded Earth values
6902 var pxCenter = this._map.getSize()._divideBy(2),
6903 pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
6905 this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
6906 this._worldWidth = this._map.project([0, 180]).x;
6909 _onPreDrag: function () {
6910 // TODO refactor to be able to adjust map pane position after zoom
6911 var worldWidth = this._worldWidth,
6912 halfWidth = Math.round(worldWidth / 2),
6913 dx = this._initialWorldOffset,
6914 x = this._draggable._newPos.x,
6915 newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
6916 newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
6917 newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
6919 this._draggable._newPos.x = newX;
6922 _onDragEnd: function (e) {
6923 var map = this._map,
6924 options = map.options,
6925 delay = +new Date() - this._lastTime,
6927 noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
6929 map.fire('dragend', e);
6932 map.fire('moveend');
6936 var direction = this._lastPos.subtract(this._positions[0]),
6937 duration = (this._lastTime + delay - this._times[0]) / 1000,
6938 ease = options.easeLinearity,
6940 speedVector = direction.multiplyBy(ease / duration),
6941 speed = speedVector.distanceTo([0, 0]),
6943 limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
6944 limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
6946 decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
6947 offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
6949 if (!offset.x || !offset.y) {
6950 map.fire('moveend');
6953 offset = map._limitOffset(offset, map.options.maxBounds);
6955 L.Util.requestAnimFrame(function () {
6957 duration: decelerationDuration,
6958 easeLinearity: ease,
6967 L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
6971 * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
6974 L.Map.mergeOptions({
6975 doubleClickZoom: true
6978 L.Map.DoubleClickZoom = L.Handler.extend({
6979 addHooks: function () {
6980 this._map.on('dblclick', this._onDoubleClick, this);
6983 removeHooks: function () {
6984 this._map.off('dblclick', this._onDoubleClick, this);
6987 _onDoubleClick: function (e) {
6988 var map = this._map,
6989 zoom = map.getZoom() + (e.originalEvent.shiftKey ? -1 : 1);
6991 if (map.options.doubleClickZoom === 'center') {
6994 map.setZoomAround(e.containerPoint, zoom);
6999 L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
7003 * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
7006 L.Map.mergeOptions({
7007 scrollWheelZoom: true
7010 L.Map.ScrollWheelZoom = L.Handler.extend({
7011 addHooks: function () {
7012 L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
7013 L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
7017 removeHooks: function () {
7018 L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
7019 L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
7022 _onWheelScroll: function (e) {
7023 var delta = L.DomEvent.getWheelDelta(e);
7025 this._delta += delta;
7026 this._lastMousePos = this._map.mouseEventToContainerPoint(e);
7028 if (!this._startTime) {
7029 this._startTime = +new Date();
7032 var left = Math.max(40 - (+new Date() - this._startTime), 0);
7034 clearTimeout(this._timer);
7035 this._timer = setTimeout(L.bind(this._performZoom, this), left);
7037 L.DomEvent.preventDefault(e);
7038 L.DomEvent.stopPropagation(e);
7041 _performZoom: function () {
7042 var map = this._map,
7043 delta = this._delta,
7044 zoom = map.getZoom();
7046 delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
7047 delta = Math.max(Math.min(delta, 4), -4);
7048 delta = map._limitZoom(zoom + delta) - zoom;
7051 this._startTime = null;
7053 if (!delta) { return; }
7055 if (map.options.scrollWheelZoom === 'center') {
7056 map.setZoom(zoom + delta);
7058 map.setZoomAround(this._lastMousePos, zoom + delta);
7063 L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
7067 * Extends the event handling code with double tap support for mobile browsers.
7070 L.extend(L.DomEvent, {
7072 _touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart',
7073 _touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend',
7075 // inspired by Zepto touch code by Thomas Fuchs
7076 addDoubleTapListener: function (obj, handler, id) {
7082 touchstart = this._touchstart,
7083 touchend = this._touchend,
7084 trackedTouches = [];
7086 function onTouchStart(e) {
7089 if (L.Browser.pointer) {
7090 trackedTouches.push(e.pointerId);
7091 count = trackedTouches.length;
7093 count = e.touches.length;
7099 var now = Date.now(),
7100 delta = now - (last || now);
7102 touch = e.touches ? e.touches[0] : e;
7103 doubleTap = (delta > 0 && delta <= delay);
7107 function onTouchEnd(e) {
7108 if (L.Browser.pointer) {
7109 var idx = trackedTouches.indexOf(e.pointerId);
7113 trackedTouches.splice(idx, 1);
7117 if (L.Browser.pointer) {
7118 // work around .type being readonly with MSPointer* events
7122 // jshint forin:false
7123 for (var i in touch) {
7125 if (typeof prop === 'function') {
7126 newTouch[i] = prop.bind(touch);
7133 touch.type = 'dblclick';
7138 obj[pre + touchstart + id] = onTouchStart;
7139 obj[pre + touchend + id] = onTouchEnd;
7141 // on pointer we need to listen on the document, otherwise a drag starting on the map and moving off screen
7142 // will not come through to us, so we will lose track of how many touches are ongoing
7143 var endElement = L.Browser.pointer ? document.documentElement : obj;
7145 obj.addEventListener(touchstart, onTouchStart, false);
7146 endElement.addEventListener(touchend, onTouchEnd, false);
7148 if (L.Browser.pointer) {
7149 endElement.addEventListener(L.DomEvent.POINTER_CANCEL, onTouchEnd, false);
7155 removeDoubleTapListener: function (obj, id) {
7156 var pre = '_leaflet_';
7158 obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
7159 (L.Browser.pointer ? document.documentElement : obj).removeEventListener(
7160 this._touchend, obj[pre + this._touchend + id], false);
7162 if (L.Browser.pointer) {
7163 document.documentElement.removeEventListener(L.DomEvent.POINTER_CANCEL, obj[pre + this._touchend + id],
7173 * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
7176 L.extend(L.DomEvent, {
7179 POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown',
7180 POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove',
7181 POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup',
7182 POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel',
7185 _pointerDocumentListener: false,
7187 // Provides a touch events wrapper for (ms)pointer events.
7188 // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
7189 //ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
7191 addPointerListener: function (obj, type, handler, id) {
7195 return this.addPointerListenerStart(obj, type, handler, id);
7197 return this.addPointerListenerEnd(obj, type, handler, id);
7199 return this.addPointerListenerMove(obj, type, handler, id);
7201 throw 'Unknown touch event type';
7205 addPointerListenerStart: function (obj, type, handler, id) {
7206 var pre = '_leaflet_',
7207 pointers = this._pointers;
7209 var cb = function (e) {
7211 L.DomEvent.preventDefault(e);
7213 var alreadyInArray = false;
7214 for (var i = 0; i < pointers.length; i++) {
7215 if (pointers[i].pointerId === e.pointerId) {
7216 alreadyInArray = true;
7220 if (!alreadyInArray) {
7224 e.touches = pointers.slice();
7225 e.changedTouches = [e];
7230 obj[pre + 'touchstart' + id] = cb;
7231 obj.addEventListener(this.POINTER_DOWN, cb, false);
7233 // need to also listen for end events to keep the _pointers list accurate
7234 // this needs to be on the body and never go away
7235 if (!this._pointerDocumentListener) {
7236 var internalCb = function (e) {
7237 for (var i = 0; i < pointers.length; i++) {
7238 if (pointers[i].pointerId === e.pointerId) {
7239 pointers.splice(i, 1);
7244 //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
7245 document.documentElement.addEventListener(this.POINTER_UP, internalCb, false);
7246 document.documentElement.addEventListener(this.POINTER_CANCEL, internalCb, false);
7248 this._pointerDocumentListener = true;
7254 addPointerListenerMove: function (obj, type, handler, id) {
7255 var pre = '_leaflet_',
7256 touches = this._pointers;
7260 // don't fire touch moves when mouse isn't down
7261 if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
7263 for (var i = 0; i < touches.length; i++) {
7264 if (touches[i].pointerId === e.pointerId) {
7270 e.touches = touches.slice();
7271 e.changedTouches = [e];
7276 obj[pre + 'touchmove' + id] = cb;
7277 obj.addEventListener(this.POINTER_MOVE, cb, false);
7282 addPointerListenerEnd: function (obj, type, handler, id) {
7283 var pre = '_leaflet_',
7284 touches = this._pointers;
7286 var cb = function (e) {
7287 for (var i = 0; i < touches.length; i++) {
7288 if (touches[i].pointerId === e.pointerId) {
7289 touches.splice(i, 1);
7294 e.touches = touches.slice();
7295 e.changedTouches = [e];
7300 obj[pre + 'touchend' + id] = cb;
7301 obj.addEventListener(this.POINTER_UP, cb, false);
7302 obj.addEventListener(this.POINTER_CANCEL, cb, false);
7307 removePointerListener: function (obj, type, id) {
7308 var pre = '_leaflet_',
7309 cb = obj[pre + type + id];
7313 obj.removeEventListener(this.POINTER_DOWN, cb, false);
7316 obj.removeEventListener(this.POINTER_MOVE, cb, false);
7319 obj.removeEventListener(this.POINTER_UP, cb, false);
7320 obj.removeEventListener(this.POINTER_CANCEL, cb, false);
7330 * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
7333 L.Map.mergeOptions({
7334 touchZoom: L.Browser.touch && !L.Browser.android23,
7335 bounceAtZoomLimits: true
7338 L.Map.TouchZoom = L.Handler.extend({
7339 addHooks: function () {
7340 L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
7343 removeHooks: function () {
7344 L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
7347 _onTouchStart: function (e) {
7348 var map = this._map;
7350 if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
7352 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7353 p2 = map.mouseEventToLayerPoint(e.touches[1]),
7354 viewCenter = map._getCenterLayerPoint();
7356 this._startCenter = p1.add(p2)._divideBy(2);
7357 this._startDist = p1.distanceTo(p2);
7359 this._moved = false;
7360 this._zooming = true;
7362 this._centerOffset = viewCenter.subtract(this._startCenter);
7365 map._panAnim.stop();
7369 .on(document, 'touchmove', this._onTouchMove, this)
7370 .on(document, 'touchend', this._onTouchEnd, this);
7372 L.DomEvent.preventDefault(e);
7375 _onTouchMove: function (e) {
7376 var map = this._map;
7378 if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
7380 var p1 = map.mouseEventToLayerPoint(e.touches[0]),
7381 p2 = map.mouseEventToLayerPoint(e.touches[1]);
7383 this._scale = p1.distanceTo(p2) / this._startDist;
7384 this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
7386 if (this._scale === 1) { return; }
7388 if (!map.options.bounceAtZoomLimits) {
7389 if ((map.getZoom() === map.getMinZoom() && this._scale < 1) ||
7390 (map.getZoom() === map.getMaxZoom() && this._scale > 1)) { return; }
7394 L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
7403 L.Util.cancelAnimFrame(this._animRequest);
7404 this._animRequest = L.Util.requestAnimFrame(
7405 this._updateOnMove, this, true, this._map._container);
7407 L.DomEvent.preventDefault(e);
7410 _updateOnMove: function () {
7411 var map = this._map,
7412 origin = this._getScaleOrigin(),
7413 center = map.layerPointToLatLng(origin),
7414 zoom = map.getScaleZoom(this._scale);
7416 map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta);
7419 _onTouchEnd: function () {
7420 if (!this._moved || !this._zooming) {
7421 this._zooming = false;
7425 var map = this._map;
7427 this._zooming = false;
7428 L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
7429 L.Util.cancelAnimFrame(this._animRequest);
7432 .off(document, 'touchmove', this._onTouchMove)
7433 .off(document, 'touchend', this._onTouchEnd);
7435 var origin = this._getScaleOrigin(),
7436 center = map.layerPointToLatLng(origin),
7438 oldZoom = map.getZoom(),
7439 floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
7440 roundZoomDelta = (floatZoomDelta > 0 ?
7441 Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
7443 zoom = map._limitZoom(oldZoom + roundZoomDelta),
7444 scale = map.getZoomScale(zoom) / this._scale;
7446 map._animateZoom(center, zoom, origin, scale);
7449 _getScaleOrigin: function () {
7450 var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
7451 return this._startCenter.add(centerOffset);
7455 L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
7459 * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
7462 L.Map.mergeOptions({
7467 L.Map.Tap = L.Handler.extend({
7468 addHooks: function () {
7469 L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
7472 removeHooks: function () {
7473 L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
7476 _onDown: function (e) {
7477 if (!e.touches) { return; }
7479 L.DomEvent.preventDefault(e);
7481 this._fireClick = true;
7483 // don't simulate click or track longpress if more than 1 touch
7484 if (e.touches.length > 1) {
7485 this._fireClick = false;
7486 clearTimeout(this._holdTimeout);
7490 var first = e.touches[0],
7493 this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
7495 // if touching a link, highlight it
7496 if (el.tagName && el.tagName.toLowerCase() === 'a') {
7497 L.DomUtil.addClass(el, 'leaflet-active');
7500 // simulate long hold but setting a timeout
7501 this._holdTimeout = setTimeout(L.bind(function () {
7502 if (this._isTapValid()) {
7503 this._fireClick = false;
7505 this._simulateEvent('contextmenu', first);
7510 .on(document, 'touchmove', this._onMove, this)
7511 .on(document, 'touchend', this._onUp, this);
7514 _onUp: function (e) {
7515 clearTimeout(this._holdTimeout);
7518 .off(document, 'touchmove', this._onMove, this)
7519 .off(document, 'touchend', this._onUp, this);
7521 if (this._fireClick && e && e.changedTouches) {
7523 var first = e.changedTouches[0],
7526 if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
7527 L.DomUtil.removeClass(el, 'leaflet-active');
7530 // simulate click if the touch didn't move too much
7531 if (this._isTapValid()) {
7532 this._simulateEvent('click', first);
7537 _isTapValid: function () {
7538 return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
7541 _onMove: function (e) {
7542 var first = e.touches[0];
7543 this._newPos = new L.Point(first.clientX, first.clientY);
7546 _simulateEvent: function (type, e) {
7547 var simulatedEvent = document.createEvent('MouseEvents');
7549 simulatedEvent._simulated = true;
7550 e.target._simulatedClick = true;
7552 simulatedEvent.initMouseEvent(
7553 type, true, true, window, 1,
7554 e.screenX, e.screenY,
7555 e.clientX, e.clientY,
7556 false, false, false, false, 0, null);
7558 e.target.dispatchEvent(simulatedEvent);
7562 if (L.Browser.touch && !L.Browser.pointer) {
7563 L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
7568 * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
7569 * (zoom to a selected bounding box), enabled by default.
7572 L.Map.mergeOptions({
7576 L.Map.BoxZoom = L.Handler.extend({
7577 initialize: function (map) {
7579 this._container = map._container;
7580 this._pane = map._panes.overlayPane;
7581 this._moved = false;
7584 addHooks: function () {
7585 L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
7588 removeHooks: function () {
7589 L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
7590 this._moved = false;
7593 moved: function () {
7597 _onMouseDown: function (e) {
7598 this._moved = false;
7600 if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
7602 L.DomUtil.disableTextSelection();
7603 L.DomUtil.disableImageDrag();
7605 this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
7608 .on(document, 'mousemove', this._onMouseMove, this)
7609 .on(document, 'mouseup', this._onMouseUp, this)
7610 .on(document, 'keydown', this._onKeyDown, this);
7613 _onMouseMove: function (e) {
7615 this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
7616 L.DomUtil.setPosition(this._box, this._startLayerPoint);
7618 //TODO refactor: move cursor to styles
7619 this._container.style.cursor = 'crosshair';
7620 this._map.fire('boxzoomstart');
7623 var startPoint = this._startLayerPoint,
7626 layerPoint = this._map.mouseEventToLayerPoint(e),
7627 offset = layerPoint.subtract(startPoint),
7629 newPos = new L.Point(
7630 Math.min(layerPoint.x, startPoint.x),
7631 Math.min(layerPoint.y, startPoint.y));
7633 L.DomUtil.setPosition(box, newPos);
7637 // TODO refactor: remove hardcoded 4 pixels
7638 box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
7639 box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
7642 _finish: function () {
7644 this._pane.removeChild(this._box);
7645 this._container.style.cursor = '';
7648 L.DomUtil.enableTextSelection();
7649 L.DomUtil.enableImageDrag();
7652 .off(document, 'mousemove', this._onMouseMove)
7653 .off(document, 'mouseup', this._onMouseUp)
7654 .off(document, 'keydown', this._onKeyDown);
7657 _onMouseUp: function (e) {
7661 var map = this._map,
7662 layerPoint = map.mouseEventToLayerPoint(e);
7664 if (this._startLayerPoint.equals(layerPoint)) { return; }
7666 var bounds = new L.LatLngBounds(
7667 map.layerPointToLatLng(this._startLayerPoint),
7668 map.layerPointToLatLng(layerPoint));
7670 map.fitBounds(bounds);
7672 map.fire('boxzoomend', {
7673 boxZoomBounds: bounds
7677 _onKeyDown: function (e) {
7678 if (e.keyCode === 27) {
7684 L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
7688 * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
7691 L.Map.mergeOptions({
7693 keyboardPanOffset: 80,
7694 keyboardZoomOffset: 1
7697 L.Map.Keyboard = L.Handler.extend({
7704 zoomIn: [187, 107, 61, 171],
7705 zoomOut: [189, 109, 173]
7708 initialize: function (map) {
7711 this._setPanOffset(map.options.keyboardPanOffset);
7712 this._setZoomOffset(map.options.keyboardZoomOffset);
7715 addHooks: function () {
7716 var container = this._map._container;
7718 // make the container focusable by tabbing
7719 if (container.tabIndex === -1) {
7720 container.tabIndex = '0';
7724 .on(container, 'focus', this._onFocus, this)
7725 .on(container, 'blur', this._onBlur, this)
7726 .on(container, 'mousedown', this._onMouseDown, this);
7729 .on('focus', this._addHooks, this)
7730 .on('blur', this._removeHooks, this);
7733 removeHooks: function () {
7734 this._removeHooks();
7736 var container = this._map._container;
7739 .off(container, 'focus', this._onFocus, this)
7740 .off(container, 'blur', this._onBlur, this)
7741 .off(container, 'mousedown', this._onMouseDown, this);
7744 .off('focus', this._addHooks, this)
7745 .off('blur', this._removeHooks, this);
7748 _onMouseDown: function () {
7749 if (this._focused) { return; }
7751 var body = document.body,
7752 docEl = document.documentElement,
7753 top = body.scrollTop || docEl.scrollTop,
7754 left = body.scrollLeft || docEl.scrollLeft;
7756 this._map._container.focus();
7758 window.scrollTo(left, top);
7761 _onFocus: function () {
7762 this._focused = true;
7763 this._map.fire('focus');
7766 _onBlur: function () {
7767 this._focused = false;
7768 this._map.fire('blur');
7771 _setPanOffset: function (pan) {
7772 var keys = this._panKeys = {},
7773 codes = this.keyCodes,
7776 for (i = 0, len = codes.left.length; i < len; i++) {
7777 keys[codes.left[i]] = [-1 * pan, 0];
7779 for (i = 0, len = codes.right.length; i < len; i++) {
7780 keys[codes.right[i]] = [pan, 0];
7782 for (i = 0, len = codes.down.length; i < len; i++) {
7783 keys[codes.down[i]] = [0, pan];
7785 for (i = 0, len = codes.up.length; i < len; i++) {
7786 keys[codes.up[i]] = [0, -1 * pan];
7790 _setZoomOffset: function (zoom) {
7791 var keys = this._zoomKeys = {},
7792 codes = this.keyCodes,
7795 for (i = 0, len = codes.zoomIn.length; i < len; i++) {
7796 keys[codes.zoomIn[i]] = zoom;
7798 for (i = 0, len = codes.zoomOut.length; i < len; i++) {
7799 keys[codes.zoomOut[i]] = -zoom;
7803 _addHooks: function () {
7804 L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
7807 _removeHooks: function () {
7808 L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
7811 _onKeyDown: function (e) {
7812 var key = e.keyCode,
7815 if (key in this._panKeys) {
7817 if (map._panAnim && map._panAnim._inProgress) { return; }
7819 map.panBy(this._panKeys[key]);
7821 if (map.options.maxBounds) {
7822 map.panInsideBounds(map.options.maxBounds);
7825 } else if (key in this._zoomKeys) {
7826 map.setZoom(map.getZoom() + this._zoomKeys[key]);
7836 L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
7840 * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
7843 L.Handler.MarkerDrag = L.Handler.extend({
7844 initialize: function (marker) {
7845 this._marker = marker;
7848 addHooks: function () {
7849 var icon = this._marker._icon;
7850 if (!this._draggable) {
7851 this._draggable = new L.Draggable(icon, icon);
7855 .on('dragstart', this._onDragStart, this)
7856 .on('drag', this._onDrag, this)
7857 .on('dragend', this._onDragEnd, this);
7858 this._draggable.enable();
7859 L.DomUtil.addClass(this._marker._icon, 'leaflet-marker-draggable');
7862 removeHooks: function () {
7864 .off('dragstart', this._onDragStart, this)
7865 .off('drag', this._onDrag, this)
7866 .off('dragend', this._onDragEnd, this);
7868 this._draggable.disable();
7869 L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');
7872 moved: function () {
7873 return this._draggable && this._draggable._moved;
7876 _onDragStart: function () {
7883 _onDrag: function () {
7884 var marker = this._marker,
7885 shadow = marker._shadow,
7886 iconPos = L.DomUtil.getPosition(marker._icon),
7887 latlng = marker._map.layerPointToLatLng(iconPos);
7889 // update shadow position
7891 L.DomUtil.setPosition(shadow, iconPos);
7894 marker._latlng = latlng;
7897 .fire('move', {latlng: latlng})
7901 _onDragEnd: function (e) {
7904 .fire('dragend', e);
7910 * L.Control is a base class for implementing map controls. Handles positioning.
7911 * All other controls extend from this class.
7914 L.Control = L.Class.extend({
7916 position: 'topright'
7919 initialize: function (options) {
7920 L.setOptions(this, options);
7923 getPosition: function () {
7924 return this.options.position;
7927 setPosition: function (position) {
7928 var map = this._map;
7931 map.removeControl(this);
7934 this.options.position = position;
7937 map.addControl(this);
7943 getContainer: function () {
7944 return this._container;
7947 addTo: function (map) {
7950 var container = this._container = this.onAdd(map),
7951 pos = this.getPosition(),
7952 corner = map._controlCorners[pos];
7954 L.DomUtil.addClass(container, 'leaflet-control');
7956 if (pos.indexOf('bottom') !== -1) {
7957 corner.insertBefore(container, corner.firstChild);
7959 corner.appendChild(container);
7965 removeFrom: function (map) {
7966 var pos = this.getPosition(),
7967 corner = map._controlCorners[pos];
7969 corner.removeChild(this._container);
7972 if (this.onRemove) {
7979 _refocusOnMap: function () {
7981 this._map.getContainer().focus();
7986 L.control = function (options) {
7987 return new L.Control(options);
7991 // adds control-related methods to L.Map
7994 addControl: function (control) {
7995 control.addTo(this);
7999 removeControl: function (control) {
8000 control.removeFrom(this);
8004 _initControlPos: function () {
8005 var corners = this._controlCorners = {},
8007 container = this._controlContainer =
8008 L.DomUtil.create('div', l + 'control-container', this._container);
8010 function createCorner(vSide, hSide) {
8011 var className = l + vSide + ' ' + l + hSide;
8013 corners[vSide + hSide] = L.DomUtil.create('div', className, container);
8016 createCorner('top', 'left');
8017 createCorner('top', 'right');
8018 createCorner('bottom', 'left');
8019 createCorner('bottom', 'right');
8022 _clearControlPos: function () {
8023 this._container.removeChild(this._controlContainer);
8029 * L.Control.Zoom is used for the default zoom buttons on the map.
8032 L.Control.Zoom = L.Control.extend({
8034 position: 'topleft',
8036 zoomInTitle: 'Zoom in',
8038 zoomOutTitle: 'Zoom out'
8041 onAdd: function (map) {
8042 var zoomName = 'leaflet-control-zoom',
8043 container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
8047 this._zoomInButton = this._createButton(
8048 this.options.zoomInText, this.options.zoomInTitle,
8049 zoomName + '-in', container, this._zoomIn, this);
8050 this._zoomOutButton = this._createButton(
8051 this.options.zoomOutText, this.options.zoomOutTitle,
8052 zoomName + '-out', container, this._zoomOut, this);
8054 this._updateDisabled();
8055 map.on('zoomend zoomlevelschange', this._updateDisabled, this);
8060 onRemove: function (map) {
8061 map.off('zoomend zoomlevelschange', this._updateDisabled, this);
8064 _zoomIn: function (e) {
8065 this._map.zoomIn(e.shiftKey ? 3 : 1);
8068 _zoomOut: function (e) {
8069 this._map.zoomOut(e.shiftKey ? 3 : 1);
8072 _createButton: function (html, title, className, container, fn, context) {
8073 var link = L.DomUtil.create('a', className, container);
8074 link.innerHTML = html;
8078 var stop = L.DomEvent.stopPropagation;
8081 .on(link, 'click', stop)
8082 .on(link, 'mousedown', stop)
8083 .on(link, 'dblclick', stop)
8084 .on(link, 'click', L.DomEvent.preventDefault)
8085 .on(link, 'click', fn, context)
8086 .on(link, 'click', this._refocusOnMap, context);
8091 _updateDisabled: function () {
8092 var map = this._map,
8093 className = 'leaflet-disabled';
8095 L.DomUtil.removeClass(this._zoomInButton, className);
8096 L.DomUtil.removeClass(this._zoomOutButton, className);
8098 if (map._zoom === map.getMinZoom()) {
8099 L.DomUtil.addClass(this._zoomOutButton, className);
8101 if (map._zoom === map.getMaxZoom()) {
8102 L.DomUtil.addClass(this._zoomInButton, className);
8107 L.Map.mergeOptions({
8111 L.Map.addInitHook(function () {
8112 if (this.options.zoomControl) {
8113 this.zoomControl = new L.Control.Zoom();
8114 this.addControl(this.zoomControl);
8118 L.control.zoom = function (options) {
8119 return new L.Control.Zoom(options);
8125 * L.Control.Attribution is used for displaying attribution on the map (added by default).
8128 L.Control.Attribution = L.Control.extend({
8130 position: 'bottomright',
8131 prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
8134 initialize: function (options) {
8135 L.setOptions(this, options);
8137 this._attributions = {};
8140 onAdd: function (map) {
8141 this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
8142 L.DomEvent.disableClickPropagation(this._container);
8144 for (var i in map._layers) {
8145 if (map._layers[i].getAttribution) {
8146 this.addAttribution(map._layers[i].getAttribution());
8151 .on('layeradd', this._onLayerAdd, this)
8152 .on('layerremove', this._onLayerRemove, this);
8156 return this._container;
8159 onRemove: function (map) {
8161 .off('layeradd', this._onLayerAdd)
8162 .off('layerremove', this._onLayerRemove);
8166 setPrefix: function (prefix) {
8167 this.options.prefix = prefix;
8172 addAttribution: function (text) {
8173 if (!text) { return; }
8175 if (!this._attributions[text]) {
8176 this._attributions[text] = 0;
8178 this._attributions[text]++;
8185 removeAttribution: function (text) {
8186 if (!text) { return; }
8188 if (this._attributions[text]) {
8189 this._attributions[text]--;
8196 _update: function () {
8197 if (!this._map) { return; }
8201 for (var i in this._attributions) {
8202 if (this._attributions[i]) {
8207 var prefixAndAttribs = [];
8209 if (this.options.prefix) {
8210 prefixAndAttribs.push(this.options.prefix);
8212 if (attribs.length) {
8213 prefixAndAttribs.push(attribs.join(', '));
8216 this._container.innerHTML = prefixAndAttribs.join(' | ');
8219 _onLayerAdd: function (e) {
8220 if (e.layer.getAttribution) {
8221 this.addAttribution(e.layer.getAttribution());
8225 _onLayerRemove: function (e) {
8226 if (e.layer.getAttribution) {
8227 this.removeAttribution(e.layer.getAttribution());
8232 L.Map.mergeOptions({
8233 attributionControl: true
8236 L.Map.addInitHook(function () {
8237 if (this.options.attributionControl) {
8238 this.attributionControl = (new L.Control.Attribution()).addTo(this);
8242 L.control.attribution = function (options) {
8243 return new L.Control.Attribution(options);
8248 * L.Control.Scale is used for displaying metric/imperial scale on the map.
8251 L.Control.Scale = L.Control.extend({
8253 position: 'bottomleft',
8257 updateWhenIdle: false
8260 onAdd: function (map) {
8263 var className = 'leaflet-control-scale',
8264 container = L.DomUtil.create('div', className),
8265 options = this.options;
8267 this._addScales(options, className, container);
8269 map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8270 map.whenReady(this._update, this);
8275 onRemove: function (map) {
8276 map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
8279 _addScales: function (options, className, container) {
8280 if (options.metric) {
8281 this._mScale = L.DomUtil.create('div', className + '-line', container);
8283 if (options.imperial) {
8284 this._iScale = L.DomUtil.create('div', className + '-line', container);
8288 _update: function () {
8289 var bounds = this._map.getBounds(),
8290 centerLat = bounds.getCenter().lat,
8291 halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
8292 dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
8294 size = this._map.getSize(),
8295 options = this.options,
8299 maxMeters = dist * (options.maxWidth / size.x);
8302 this._updateScales(options, maxMeters);
8305 _updateScales: function (options, maxMeters) {
8306 if (options.metric && maxMeters) {
8307 this._updateMetric(maxMeters);
8310 if (options.imperial && maxMeters) {
8311 this._updateImperial(maxMeters);
8315 _updateMetric: function (maxMeters) {
8316 var meters = this._getRoundNum(maxMeters);
8318 this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
8319 this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
8322 _updateImperial: function (maxMeters) {
8323 var maxFeet = maxMeters * 3.2808399,
8324 scale = this._iScale,
8325 maxMiles, miles, feet;
8327 if (maxFeet > 5280) {
8328 maxMiles = maxFeet / 5280;
8329 miles = this._getRoundNum(maxMiles);
8331 scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
8332 scale.innerHTML = miles + ' mi';
8335 feet = this._getRoundNum(maxFeet);
8337 scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
8338 scale.innerHTML = feet + ' ft';
8342 _getScaleWidth: function (ratio) {
8343 return Math.round(this.options.maxWidth * ratio) - 10;
8346 _getRoundNum: function (num) {
8347 var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
8350 d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
8356 L.control.scale = function (options) {
8357 return new L.Control.Scale(options);
8362 * L.Control.Layers is a control to allow users to switch between different layers on the map.
8365 L.Control.Layers = L.Control.extend({
8368 position: 'topright',
8372 initialize: function (baseLayers, overlays, options) {
8373 L.setOptions(this, options);
8376 this._lastZIndex = 0;
8377 this._handlingClick = false;
8379 for (var i in baseLayers) {
8380 this._addLayer(baseLayers[i], i);
8383 for (i in overlays) {
8384 this._addLayer(overlays[i], i, true);
8388 onAdd: function (map) {
8393 .on('layeradd', this._onLayerChange, this)
8394 .on('layerremove', this._onLayerChange, this);
8396 return this._container;
8399 onRemove: function (map) {
8401 .off('layeradd', this._onLayerChange)
8402 .off('layerremove', this._onLayerChange);
8405 addBaseLayer: function (layer, name) {
8406 this._addLayer(layer, name);
8411 addOverlay: function (layer, name) {
8412 this._addLayer(layer, name, true);
8417 removeLayer: function (layer) {
8418 var id = L.stamp(layer);
8419 delete this._layers[id];
8424 _initLayout: function () {
8425 var className = 'leaflet-control-layers',
8426 container = this._container = L.DomUtil.create('div', className);
8428 //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
8429 container.setAttribute('aria-haspopup', true);
8431 if (!L.Browser.touch) {
8433 .disableClickPropagation(container)
8434 .disableScrollPropagation(container);
8436 L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
8439 var form = this._form = L.DomUtil.create('form', className + '-list');
8441 if (this.options.collapsed) {
8442 if (!L.Browser.android) {
8444 .on(container, 'mouseover', this._expand, this)
8445 .on(container, 'mouseout', this._collapse, this);
8447 var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
8449 link.title = 'Layers';
8451 if (L.Browser.touch) {
8453 .on(link, 'click', L.DomEvent.stop)
8454 .on(link, 'click', this._expand, this);
8457 L.DomEvent.on(link, 'focus', this._expand, this);
8459 //Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033
8460 L.DomEvent.on(form, 'click', function () {
8461 setTimeout(L.bind(this._onInputClick, this), 0);
8464 this._map.on('click', this._collapse, this);
8465 // TODO keyboard accessibility
8470 this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
8471 this._separator = L.DomUtil.create('div', className + '-separator', form);
8472 this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
8474 container.appendChild(form);
8477 _addLayer: function (layer, name, overlay) {
8478 var id = L.stamp(layer);
8480 this._layers[id] = {
8486 if (this.options.autoZIndex && layer.setZIndex) {
8488 layer.setZIndex(this._lastZIndex);
8492 _update: function () {
8493 if (!this._container) {
8497 this._baseLayersList.innerHTML = '';
8498 this._overlaysList.innerHTML = '';
8500 var baseLayersPresent = false,
8501 overlaysPresent = false,
8504 for (i in this._layers) {
8505 obj = this._layers[i];
8507 overlaysPresent = overlaysPresent || obj.overlay;
8508 baseLayersPresent = baseLayersPresent || !obj.overlay;
8511 this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
8514 _onLayerChange: function (e) {
8515 var obj = this._layers[L.stamp(e.layer)];
8517 if (!obj) { return; }
8519 if (!this._handlingClick) {
8523 var type = obj.overlay ?
8524 (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
8525 (e.type === 'layeradd' ? 'baselayerchange' : null);
8528 this._map.fire(type, obj);
8532 // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
8533 _createRadioElement: function (name, checked) {
8535 var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
8537 radioHtml += ' checked="checked"';
8541 var radioFragment = document.createElement('div');
8542 radioFragment.innerHTML = radioHtml;
8544 return radioFragment.firstChild;
8547 _addItem: function (obj) {
8548 var label = document.createElement('label'),
8550 checked = this._map.hasLayer(obj.layer);
8553 input = document.createElement('input');
8554 input.type = 'checkbox';
8555 input.className = 'leaflet-control-layers-selector';
8556 input.defaultChecked = checked;
8558 input = this._createRadioElement('leaflet-base-layers', checked);
8561 input.layerId = L.stamp(obj.layer);
8563 L.DomEvent.on(input, 'click', this._onInputClick, this);
8565 var name = document.createElement('span');
8566 name.innerHTML = ' ' + obj.name;
8568 label.appendChild(input);
8569 label.appendChild(name);
8571 var container = obj.overlay ? this._overlaysList : this._baseLayersList;
8572 container.appendChild(label);
8577 _onInputClick: function () {
8579 inputs = this._form.getElementsByTagName('input'),
8580 inputsLen = inputs.length;
8582 this._handlingClick = true;
8584 for (i = 0; i < inputsLen; i++) {
8586 obj = this._layers[input.layerId];
8588 if (input.checked && !this._map.hasLayer(obj.layer)) {
8589 this._map.addLayer(obj.layer);
8591 } else if (!input.checked && this._map.hasLayer(obj.layer)) {
8592 this._map.removeLayer(obj.layer);
8596 this._handlingClick = false;
8598 this._refocusOnMap();
8601 _expand: function () {
8602 L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
8605 _collapse: function () {
8606 this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
8610 L.control.layers = function (baseLayers, overlays, options) {
8611 return new L.Control.Layers(baseLayers, overlays, options);
8616 * L.PosAnimation is used by Leaflet internally for pan animations.
8619 L.PosAnimation = L.Class.extend({
8620 includes: L.Mixin.Events,
8622 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8626 this._inProgress = true;
8627 this._newPos = newPos;
8631 el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
8632 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
8634 L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8635 L.DomUtil.setPosition(el, newPos);
8637 // toggle reflow, Chrome flickers for some reason if you don't do this
8638 L.Util.falseFn(el.offsetWidth);
8640 // there's no native way to track value updates of transitioned properties, so we imitate this
8641 this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
8645 if (!this._inProgress) { return; }
8647 // if we just removed the transition property, the element would jump to its final position,
8648 // so we need to make it stay at the current position
8650 L.DomUtil.setPosition(this._el, this._getPos());
8651 this._onTransitionEnd();
8652 L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
8655 _onStep: function () {
8656 var stepPos = this._getPos();
8658 this._onTransitionEnd();
8661 // jshint camelcase: false
8662 // make L.DomUtil.getPosition return intermediate position value during animation
8663 this._el._leaflet_pos = stepPos;
8668 // you can't easily get intermediate values of properties animated with CSS3 Transitions,
8669 // we need to parse computed style (in case of transform it returns matrix string)
8671 _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
8673 _getPos: function () {
8674 var left, top, matches,
8676 style = window.getComputedStyle(el);
8678 if (L.Browser.any3d) {
8679 matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
8680 if (!matches) { return; }
8681 left = parseFloat(matches[1]);
8682 top = parseFloat(matches[2]);
8684 left = parseFloat(style.left);
8685 top = parseFloat(style.top);
8688 return new L.Point(left, top, true);
8691 _onTransitionEnd: function () {
8692 L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
8694 if (!this._inProgress) { return; }
8695 this._inProgress = false;
8697 this._el.style[L.DomUtil.TRANSITION] = '';
8699 // jshint camelcase: false
8700 // make sure L.DomUtil.getPosition returns the final position value after animation
8701 this._el._leaflet_pos = this._newPos;
8703 clearInterval(this._stepTimer);
8705 this.fire('step').fire('end');
8712 * Extends L.Map to handle panning animations.
8717 setView: function (center, zoom, options) {
8719 zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
8720 center = this._limitCenter(L.latLng(center), zoom, this.options.maxBounds);
8721 options = options || {};
8723 if (this._panAnim) {
8724 this._panAnim.stop();
8727 if (this._loaded && !options.reset && options !== true) {
8729 if (options.animate !== undefined) {
8730 options.zoom = L.extend({animate: options.animate}, options.zoom);
8731 options.pan = L.extend({animate: options.animate}, options.pan);
8734 // try animating pan or zoom
8735 var animated = (this._zoom !== zoom) ?
8736 this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
8737 this._tryAnimatedPan(center, options.pan);
8740 // prevent resize handler call, the view will refresh after animation anyway
8741 clearTimeout(this._sizeTimer);
8746 // animation didn't start, just reset the map view
8747 this._resetView(center, zoom);
8752 panBy: function (offset, options) {
8753 offset = L.point(offset).round();
8754 options = options || {};
8756 if (!offset.x && !offset.y) {
8760 if (!this._panAnim) {
8761 this._panAnim = new L.PosAnimation();
8764 'step': this._onPanTransitionStep,
8765 'end': this._onPanTransitionEnd
8769 // don't fire movestart if animating inertia
8770 if (!options.noMoveStart) {
8771 this.fire('movestart');
8774 // animate pan unless animate: false specified
8775 if (options.animate !== false) {
8776 L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
8778 var newPos = this._getMapPanePos().subtract(offset);
8779 this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
8781 this._rawPanBy(offset);
8782 this.fire('move').fire('moveend');
8788 _onPanTransitionStep: function () {
8792 _onPanTransitionEnd: function () {
8793 L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
8794 this.fire('moveend');
8797 _tryAnimatedPan: function (center, options) {
8798 // difference between the new and current centers in pixels
8799 var offset = this._getCenterOffset(center)._floor();
8801 // don't animate too far unless animate: true specified in options
8802 if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
8804 this.panBy(offset, options);
8812 * L.PosAnimation fallback implementation that powers Leaflet pan animations
8813 * in browsers that don't support CSS3 Transitions.
8816 L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
8818 run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
8822 this._inProgress = true;
8823 this._duration = duration || 0.25;
8824 this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
8826 this._startPos = L.DomUtil.getPosition(el);
8827 this._offset = newPos.subtract(this._startPos);
8828 this._startTime = +new Date();
8836 if (!this._inProgress) { return; }
8842 _animate: function () {
8844 this._animId = L.Util.requestAnimFrame(this._animate, this);
8848 _step: function () {
8849 var elapsed = (+new Date()) - this._startTime,
8850 duration = this._duration * 1000;
8852 if (elapsed < duration) {
8853 this._runFrame(this._easeOut(elapsed / duration));
8860 _runFrame: function (progress) {
8861 var pos = this._startPos.add(this._offset.multiplyBy(progress));
8862 L.DomUtil.setPosition(this._el, pos);
8867 _complete: function () {
8868 L.Util.cancelAnimFrame(this._animId);
8870 this._inProgress = false;
8874 _easeOut: function (t) {
8875 return 1 - Math.pow(1 - t, this._easeOutPower);
8881 * Extends L.Map to handle zoom animations.
8884 L.Map.mergeOptions({
8885 zoomAnimation: true,
8886 zoomAnimationThreshold: 4
8889 if (L.DomUtil.TRANSITION) {
8891 L.Map.addInitHook(function () {
8892 // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
8893 this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
8894 L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
8896 // zoom transitions run with the same duration for all layers, so if one of transitionend events
8897 // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
8898 if (this._zoomAnimated) {
8899 L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
8904 L.Map.include(!L.DomUtil.TRANSITION ? {} : {
8906 _catchTransitionEnd: function () {
8907 if (this._animatingZoom) {
8908 this._onZoomTransitionEnd();
8912 _nothingToAnimate: function () {
8913 return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
8916 _tryAnimatedZoom: function (center, zoom, options) {
8918 if (this._animatingZoom) { return true; }
8920 options = options || {};
8922 // don't animate if disabled, not supported or zoom difference is too large
8923 if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
8924 Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
8926 // offset is the pixel coords of the zoom origin relative to the current center
8927 var scale = this.getZoomScale(zoom),
8928 offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
8929 origin = this._getCenterLayerPoint()._add(offset);
8931 // don't animate if the zoom origin isn't within one screen from the current center, unless forced
8932 if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
8938 this._animateZoom(center, zoom, origin, scale, null, true);
8943 _animateZoom: function (center, zoom, origin, scale, delta, backwards) {
8945 this._animatingZoom = true;
8947 // put transform transition on all layers with leaflet-zoom-animated class
8948 L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
8950 // remember what center/zoom to set after animation
8951 this._animateToCenter = center;
8952 this._animateToZoom = zoom;
8954 // disable any dragging during animation
8956 L.Draggable._disabled = true;
8959 this.fire('zoomanim', {
8965 backwards: backwards
8969 _onZoomTransitionEnd: function () {
8971 this._animatingZoom = false;
8973 L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
8975 this._resetView(this._animateToCenter, this._animateToZoom, true, true);
8978 L.Draggable._disabled = false;
8985 Zoom animation logic for L.TileLayer.
8988 L.TileLayer.include({
8989 _animateZoom: function (e) {
8990 if (!this._animating) {
8991 this._animating = true;
8992 this._prepareBgBuffer();
8995 var bg = this._bgBuffer,
8996 transform = L.DomUtil.TRANSFORM,
8997 initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
8998 scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
9000 bg.style[transform] = e.backwards ?
9001 scaleStr + ' ' + initialTransform :
9002 initialTransform + ' ' + scaleStr;
9005 _endZoomAnim: function () {
9006 var front = this._tileContainer,
9007 bg = this._bgBuffer;
9009 front.style.visibility = '';
9010 front.parentNode.appendChild(front); // Bring to fore
9013 L.Util.falseFn(bg.offsetWidth);
9015 this._animating = false;
9018 _clearBgBuffer: function () {
9019 var map = this._map;
9021 if (map && !map._animatingZoom && !map.touchZoom._zooming) {
9022 this._bgBuffer.innerHTML = '';
9023 this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
9027 _prepareBgBuffer: function () {
9029 var front = this._tileContainer,
9030 bg = this._bgBuffer;
9032 // if foreground layer doesn't have many tiles but bg layer does,
9033 // keep the existing bg layer and just zoom it some more
9035 var bgLoaded = this._getLoadedTilesPercentage(bg),
9036 frontLoaded = this._getLoadedTilesPercentage(front);
9038 if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
9040 front.style.visibility = 'hidden';
9041 this._stopLoadingImages(front);
9045 // prepare the buffer to become the front tile pane
9046 bg.style.visibility = 'hidden';
9047 bg.style[L.DomUtil.TRANSFORM] = '';
9049 // switch out the current layer to be the new bg layer (and vice-versa)
9050 this._tileContainer = bg;
9051 bg = this._bgBuffer = front;
9053 this._stopLoadingImages(bg);
9055 //prevent bg buffer from clearing right after zoom
9056 clearTimeout(this._clearBgBufferTimer);
9059 _getLoadedTilesPercentage: function (container) {
9060 var tiles = container.getElementsByTagName('img'),
9063 for (i = 0, len = tiles.length; i < len; i++) {
9064 if (tiles[i].complete) {
9071 // stops loading all tiles in the background layer
9072 _stopLoadingImages: function (container) {
9073 var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
9076 for (i = 0, len = tiles.length; i < len; i++) {
9079 if (!tile.complete) {
9080 tile.onload = L.Util.falseFn;
9081 tile.onerror = L.Util.falseFn;
9082 tile.src = L.Util.emptyImageUrl;
9084 tile.parentNode.removeChild(tile);
9092 * Provides L.Map with convenient shortcuts for using browser geolocation features.
9096 _defaultLocateOptions: {
9102 enableHighAccuracy: false
9105 locate: function (/*Object*/ options) {
9107 options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
9109 if (!navigator.geolocation) {
9110 this._handleGeolocationError({
9112 message: 'Geolocation not supported.'
9117 var onResponse = L.bind(this._handleGeolocationResponse, this),
9118 onError = L.bind(this._handleGeolocationError, this);
9120 if (options.watch) {
9121 this._locationWatchId =
9122 navigator.geolocation.watchPosition(onResponse, onError, options);
9124 navigator.geolocation.getCurrentPosition(onResponse, onError, options);
9129 stopLocate: function () {
9130 if (navigator.geolocation) {
9131 navigator.geolocation.clearWatch(this._locationWatchId);
9133 if (this._locateOptions) {
9134 this._locateOptions.setView = false;
9139 _handleGeolocationError: function (error) {
9141 message = error.message ||
9142 (c === 1 ? 'permission denied' :
9143 (c === 2 ? 'position unavailable' : 'timeout'));
9145 if (this._locateOptions.setView && !this._loaded) {
9149 this.fire('locationerror', {
9151 message: 'Geolocation error: ' + message + '.'
9155 _handleGeolocationResponse: function (pos) {
9156 var lat = pos.coords.latitude,
9157 lng = pos.coords.longitude,
9158 latlng = new L.LatLng(lat, lng),
9160 latAccuracy = 180 * pos.coords.accuracy / 40075017,
9161 lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
9163 bounds = L.latLngBounds(
9164 [lat - latAccuracy, lng - lngAccuracy],
9165 [lat + latAccuracy, lng + lngAccuracy]),
9167 options = this._locateOptions;
9169 if (options.setView) {
9170 var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
9171 this.setView(latlng, zoom);
9177 timestamp: pos.timestamp
9180 for (var i in pos.coords) {
9181 if (typeof pos.coords[i] === 'number') {
9182 data[i] = pos.coords[i];
9186 this.fire('locationfound', data);
9191 }(window, document));