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});