diff --git a/src/c3nav/static/leaflet/leaflet.js b/src/c3nav/static/leaflet/leaflet.js index c59ffa19..15a5e385 100644 --- a/src/c3nav/static/leaflet/leaflet.js +++ b/src/c3nav/static/leaflet/leaflet.js @@ -1,6 +1,6 @@ /* @preserve - * Leaflet 1.2.0+Detached: 0bcccb0190c471fba09f04c3b10e3ce14285a82e.0bcccb0, a JS library for interactive maps. http://leafletjs.com - * (c) 2010-2017 Vladimir Agafonkin, (c) 2010-2011 CloudMade + * Leaflet 1.6.0+Detached: 0c81bdf904d864fd12a286e3d1979f47aba17991.0c81bdf, a JS library for interactive maps. http://leafletjs.com + * (c) 2010-2019 Vladimir Agafonkin, (c) 2010-2011 CloudMade */ (function (global, factory) { @@ -9,7 +9,7 @@ (factory((global.L = {}))); }(this, (function (exports) { 'use strict'; -var version = "1.2.0+HEAD.0bcccb0"; +var version = "1.6.0+HEAD.0c81bdf"; /* * @namespace Util @@ -254,12 +254,12 @@ function cancelAnimFrame(id) { } -var Util = Object.freeze({ +var Util = (Object.freeze || Object)({ freeze: freeze, extend: extend, create: create, bind: bind, - get lastId () { return lastId; }, + lastId: lastId, stamp: stamp, throttle: throttle, wrapNum: wrapNum, @@ -391,7 +391,7 @@ Class.addInitHook = function (fn) { // (Function) || (String, args...) }; function checkDeprecatedMixinEvents(includes) { - if (!L || !L.Mixin) { return; } + if (typeof L === 'undefined' || !L || !L.Mixin) { return; } includes = isArray(includes) ? includes : [includes]; @@ -468,7 +468,7 @@ var Events = { * * @alternative * @method off: this - * Removes all listeners to all events on the object. + * Removes all listeners to all events on the object. This includes implicitly attached events. */ off: function (types, fn, context) { @@ -842,7 +842,7 @@ Point.prototype = { return this; }, - // @method ceil(): Point + // @method trunc(): Point // Returns a copy of the current point with truncated coordinates (rounded towards zero). trunc: function () { return this.clone()._trunc(); @@ -1360,7 +1360,7 @@ function toLatLngBounds(a, b) { * map.panTo(L.latLng(50, 30)); * ``` * - * Note that `LatLng` does not inherit from Leafet's `Class` object, + * Note that `LatLng` does not inherit from Leaflet's `Class` object, * which means new classes can't inherit from it, and new methods * can't be added to it with the `include` function. */ @@ -1631,10 +1631,11 @@ var Earth = extend({}, CRS, { var rad = Math.PI / 180, lat1 = latlng1.lat * rad, lat2 = latlng2.lat * rad, - a = Math.sin(lat1) * Math.sin(lat2) + - Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad); - - return this.R * Math.acos(Math.min(a, 1)); + sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2), + sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2), + a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon, + c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return this.R * c; } }); @@ -1647,9 +1648,11 @@ var Earth = extend({}, CRS, { * a sphere. Used by the `EPSG:3857` CRS. */ +var earthRadius = 6378137; + var SphericalMercator = { - R: 6378137, + R: earthRadius, MAX_LATITUDE: 85.0511287798, project: function (latlng) { @@ -1672,7 +1675,7 @@ var SphericalMercator = { }, bounds: (function () { - var d = 6378137 * Math.PI; + var d = earthRadius * Math.PI; return new Bounds([-d, -d], [d, d]); })() }; @@ -1903,7 +1906,7 @@ var msPointer = !window.PointerEvent && window.MSPointerEvent; // @property pointer: Boolean // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx). -var pointer = !!(window.PointerEvent || msPointer); +var pointer = !webkit && !!(window.PointerEvent || msPointer); // @property touch: Boolean // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events). @@ -1921,9 +1924,26 @@ var mobileOpera = mobile && opera; var mobileGecko = mobile && gecko; // @property retina: Boolean -// `true` for browsers on a high-resolution "retina" screen. +// `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1; +// @property passiveEvents: Boolean +// `true` for browsers that support passive events. +var passiveEvents = (function () { + var supportsPassiveOption = false; + try { + var opts = Object.defineProperty({}, 'passive', { + get: function () { + supportsPassiveOption = true; + } + }); + window.addEventListener('testPassiveEventSupport', falseFn, opts); + window.removeEventListener('testPassiveEventSupport', falseFn, opts); + } catch (e) { + // Errors can safely be ignored since this is only a browser support test. + } + return supportsPassiveOption; +}); // @property canvas: Boolean // `true` when the browser supports [``](https://developer.mozilla.org/docs/Web/API/Canvas_API). @@ -1958,7 +1978,7 @@ function userAgentContains(str) { } -var Browser = Object.freeze({ +var Browser = (Object.freeze || Object)({ ie: ie, ielt9: ielt9, edge: edge, @@ -1986,6 +2006,7 @@ var Browser = Object.freeze({ mobileOpera: mobileOpera, mobileGecko: mobileGecko, retina: retina, + passiveEvents: passiveEvents, canvas: canvas, svg: svg, vml: vml @@ -2170,6 +2191,7 @@ function addDoubleTapListener(obj, handler, id) { touch$$1 = newTouch; } touch$$1.type = 'dblclick'; + touch$$1.button = 0; handler(touch$$1); last = null; } @@ -2179,8 +2201,8 @@ function addDoubleTapListener(obj, handler, id) { obj[_pre + _touchend + id] = onTouchEnd; obj[_pre + 'dblclick' + id] = handler; - obj.addEventListener(_touchstart, onTouchStart, false); - obj.addEventListener(_touchend, onTouchEnd, false); + obj.addEventListener(_touchstart, onTouchStart, passiveEvents ? {passive: false} : false); + obj.addEventListener(_touchend, onTouchEnd, passiveEvents ? {passive: false} : false); // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse), // the browser doesn't fire touchend/pointerup events but does fire @@ -2196,8 +2218,8 @@ function removeDoubleTapListener(obj, id) { touchend = obj[_pre + _touchend + id], dblclick = obj[_pre + 'dblclick' + id]; - obj.removeEventListener(_touchstart, touchstart, false); - obj.removeEventListener(_touchend, touchend, false); + obj.removeEventListener(_touchstart, touchstart, passiveEvents ? {passive: false} : false); + obj.removeEventListener(_touchend, touchend, passiveEvents ? {passive: false} : false); if (!edge) { obj.removeEventListener('dblclick', dblclick, false); } @@ -2205,327 +2227,6 @@ function removeDoubleTapListener(obj, id) { return this; } -/* - * @namespace DomEvent - * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally. - */ - -// Inspired by John Resig, Dean Edwards and YUI addEvent implementations. - -// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this -// Adds a listener function (`fn`) to a particular DOM event type of the -// element `el`. You can optionally specify the context of the listener -// (object the `this` keyword will point to). You can also pass several -// space-separated types (e.g. `'click dblclick'`). - -// @alternative -// @function on(el: HTMLElement, eventMap: Object, context?: Object): this -// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` -function on(obj, types, fn, context) { - - if (typeof types === 'object') { - for (var type in types) { - addOne(obj, type, types[type], fn); - } - } else { - types = splitWords(types); - - for (var i = 0, len = types.length; i < len; i++) { - addOne(obj, types[i], fn, context); - } - } - - return this; -} - -var eventsKey = '_leaflet_events'; - -// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this -// Removes a previously added listener function. If no function is specified, -// it will remove all the listeners of that particular DOM event from the element. -// Note that if you passed a custom context to on, you must pass the same -// context to `off` in order to remove the listener. - -// @alternative -// @function off(el: HTMLElement, eventMap: Object, context?: Object): this -// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` -function off(obj, types, fn, context) { - - if (typeof types === 'object') { - for (var type in types) { - removeOne(obj, type, types[type], fn); - } - } else if (types) { - types = splitWords(types); - - for (var i = 0, len = types.length; i < len; i++) { - removeOne(obj, types[i], fn, context); - } - } else { - for (var j in obj[eventsKey]) { - removeOne(obj, j, obj[eventsKey][j]); - } - delete obj[eventsKey]; - } - - return this; -} - -function addOne(obj, type, fn, context) { - var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''); - - if (obj[eventsKey] && obj[eventsKey][id]) { return this; } - - var handler = function (e) { - return fn.call(context || obj, e || window.event); - }; - - var originalHandler = handler; - - if (pointer && type.indexOf('touch') === 0) { - // Needs DomEvent.Pointer.js - addPointerListener(obj, type, handler, id); - - } else if (touch && (type === 'dblclick') && addDoubleTapListener && - !(pointer && chrome)) { - // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener - // See #5180 - addDoubleTapListener(obj, handler, id); - - } else if ('addEventListener' in obj) { - - if (type === 'mousewheel') { - obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false); - - } else if ((type === 'mouseenter') || (type === 'mouseleave')) { - handler = function (e) { - e = e || window.event; - if (isExternalTarget(obj, e)) { - originalHandler(e); - } - }; - obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false); - - } else { - if (type === 'click' && android) { - handler = function (e) { - filterClick(e, originalHandler); - }; - } - obj.addEventListener(type, handler, false); - } - - } else if ('attachEvent' in obj) { - obj.attachEvent('on' + type, handler); - } - - obj[eventsKey] = obj[eventsKey] || {}; - obj[eventsKey][id] = handler; -} - -function removeOne(obj, type, fn, context) { - - var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''), - handler = obj[eventsKey] && obj[eventsKey][id]; - - if (!handler) { return this; } - - if (pointer && type.indexOf('touch') === 0) { - removePointerListener(obj, type, id); - - } else if (touch && (type === 'dblclick') && removeDoubleTapListener && - !(pointer && chrome)) { - removeDoubleTapListener(obj, id); - - } else if ('removeEventListener' in obj) { - - if (type === 'mousewheel') { - obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false); - - } else { - obj.removeEventListener( - type === 'mouseenter' ? 'mouseover' : - type === 'mouseleave' ? 'mouseout' : type, handler, false); - } - - } else if ('detachEvent' in obj) { - obj.detachEvent('on' + type, handler); - } - - obj[eventsKey][id] = null; -} - -// @function stopPropagation(ev: DOMEvent): this -// Stop the given event from propagation to parent elements. Used inside the listener functions: -// ```js -// L.DomEvent.on(div, 'click', function (ev) { -// L.DomEvent.stopPropagation(ev); -// }); -// ``` -function stopPropagation(e) { - - if (e.stopPropagation) { - e.stopPropagation(); - } else if (e.originalEvent) { // In case of Leaflet event. - e.originalEvent._stopped = true; - } else { - e.cancelBubble = true; - } - skipped(e); - - return this; -} - -// @function disableScrollPropagation(el: HTMLElement): this -// Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants). -function disableScrollPropagation(el) { - addOne(el, 'mousewheel', stopPropagation); - return this; -} - -// @function disableClickPropagation(el: HTMLElement): this -// Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`, -// `'mousedown'` and `'touchstart'` events (plus browser variants). -function disableClickPropagation(el) { - on(el, 'mousedown touchstart dblclick', stopPropagation); - addOne(el, 'click', fakeStop); - return this; -} - -// @function preventDefault(ev: DOMEvent): this -// Prevents the default action of the DOM Event `ev` from happening (such as -// following a link in the href of the a element, or doing a POST request -// with page reload when a `
` is submitted). -// Use it inside listener functions. -function preventDefault(e) { - if (e.preventDefault) { - e.preventDefault(); - } else { - e.returnValue = false; - } - return this; -} - -// @function stop(ev: DOMEvent): this -// Does `stopPropagation` and `preventDefault` at the same time. -function stop(e) { - preventDefault(e); - stopPropagation(e); - return this; -} - -// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point -// Gets normalized mouse position from a DOM event relative to the -// `container` or to the whole page if not specified. -function getMousePosition(e, container) { - if (!container) { - return new Point(e.clientX, e.clientY); - } - - var rect = container.getBoundingClientRect(); - - var scaleX = rect.width / container.offsetWidth || 1; - var scaleY = rect.height / container.offsetHeight || 1; - return new Point( - e.clientX / scaleX - rect.left - container.clientLeft, - e.clientY / scaleY - rect.top - container.clientTop); -} - -// Chrome on Win scrolls double the pixels as in other platforms (see #4538), -// and Firefox scrolls device pixels, not CSS pixels -var wheelPxFactor = - (win && chrome) ? 2 * window.devicePixelRatio : - gecko ? window.devicePixelRatio : 1; - -// @function getWheelDelta(ev: DOMEvent): Number -// Gets normalized wheel delta from a mousewheel DOM event, in vertical -// pixels scrolled (negative if scrolling down). -// Events from pointing devices without precise scrolling are mapped to -// a best guess of 60 pixels. -function getWheelDelta(e) { - return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta - (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels - (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines - (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages - (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events - e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels - (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines - e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages - 0; -} - -var skipEvents = {}; - -function fakeStop(e) { - // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e) - skipEvents[e.type] = true; -} - -function skipped(e) { - var events = skipEvents[e.type]; - // reset when checking, as it's only used in map container and propagates outside of the map - skipEvents[e.type] = false; - return events; -} - -// check if element really left/entered the event target (for mouseenter/mouseleave) -function isExternalTarget(el, e) { - - var related = e.relatedTarget; - - if (!related) { return true; } - - try { - while (related && (related !== el)) { - related = related.parentNode; - } - } catch (err) { - return false; - } - return (related !== el); -} - -var lastClick; - -// this is a horrible workaround for a bug in Android where a single touch triggers two click events -function filterClick(e, handler) { - var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)), - elapsed = lastClick && (timeStamp - lastClick); - - // are they closer together than 500ms yet more than 100ms? - // Android typically triggers them ~300ms apart while multiple listeners - // on the same event should be triggered far faster; - // or check if click is simulated on the element, and if it is, reject any non-simulated events - - if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) { - stop(e); - return; - } - lastClick = timeStamp; - - handler(e); -} - - - - -var DomEvent = Object.freeze({ - on: on, - off: off, - stopPropagation: stopPropagation, - disableScrollPropagation: disableScrollPropagation, - disableClickPropagation: disableClickPropagation, - preventDefault: preventDefault, - stop: stop, - getMousePosition: getMousePosition, - getWheelDelta: getWheelDelta, - fakeStop: fakeStop, - skipped: skipped, - isExternalTarget: isExternalTarget, - addListener: on, - removeListener: off -}); - /* * @namespace DomUtil * @@ -2541,7 +2242,7 @@ var DomEvent = Object.freeze({ // @property TRANSFORM: String // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit). var TRANSFORM = testProp( - ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']); + ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']); // webkitTransition comes first because some browser versions that drop vendor prefix don't do // the same for the transitionend event, in particular the Android 4.1 stock browser @@ -2610,7 +2311,7 @@ function empty(el) { // Makes `el` the last child of its parent, so it renders in front of the other children. function toFront(el) { var parent = el.parentNode; - if (parent.lastChild !== el) { + if (parent && parent.lastChild !== el) { parent.appendChild(el); } } @@ -2619,7 +2320,7 @@ function toFront(el) { // Makes `el` the first child of its parent, so it renders behind the other children. function toBack(el) { var parent = el.parentNode; - if (parent.firstChild !== el) { + if (parent && parent.firstChild !== el) { parent.insertBefore(el, parent.firstChild); } } @@ -2672,6 +2373,11 @@ function setClass(el, name) { // @function getClass(el: HTMLElement): String // Returns the element's class. function getClass(el) { + // Check if the element is an SVGElementInstance and use the correspondingElement instead + // (Required for linked SVG elements in IE11.) + if (el.correspondingElement) { + el = el.correspondingElement; + } return el.className.baseVal === undefined ? el.className : el.className.baseVal; } @@ -2843,9 +2549,32 @@ function restoreOutline() { _outlineStyle = undefined; off(window, 'keydown', restoreOutline); } + +// @function getSizedParentNode(el: HTMLElement): HTMLElement +// Finds the closest parent node which size (width and height) is not null. +function getSizedParentNode(element) { + do { + element = element.parentNode; + } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body); + return element; +} + +// @function getScale(el: HTMLElement): Object +// Computes the CSS scale currently applied on the element. +// Returns an object with `x` and `y` members as horizontal and vertical scales respectively, +// and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). +function getScale(element) { + var rect = element.getBoundingClientRect(); // Read-only in old browsers. + + return { + x: rect.width / element.offsetWidth || 1, + y: rect.height / element.offsetHeight || 1, + boundingClientRect: rect + }; +} -var DomUtil = Object.freeze({ +var DomUtil = (Object.freeze || Object)({ TRANSFORM: TRANSFORM, TRANSITION: TRANSITION, TRANSITION_END: TRANSITION_END, @@ -2866,12 +2595,336 @@ var DomUtil = Object.freeze({ setTransform: setTransform, setPosition: setPosition, getPosition: getPosition, - get disableTextSelection () { return disableTextSelection; }, - get enableTextSelection () { return enableTextSelection; }, + disableTextSelection: disableTextSelection, + enableTextSelection: enableTextSelection, disableImageDrag: disableImageDrag, enableImageDrag: enableImageDrag, preventOutline: preventOutline, - restoreOutline: restoreOutline + restoreOutline: restoreOutline, + getSizedParentNode: getSizedParentNode, + getScale: getScale +}); + +/* + * @namespace DomEvent + * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally. + */ + +// Inspired by John Resig, Dean Edwards and YUI addEvent implementations. + +// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this +// Adds a listener function (`fn`) to a particular DOM event type of the +// element `el`. You can optionally specify the context of the listener +// (object the `this` keyword will point to). You can also pass several +// space-separated types (e.g. `'click dblclick'`). + +// @alternative +// @function on(el: HTMLElement, eventMap: Object, context?: Object): this +// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` +function on(obj, types, fn, context) { + + if (typeof types === 'object') { + for (var type in types) { + addOne(obj, type, types[type], fn); + } + } else { + types = splitWords(types); + + for (var i = 0, len = types.length; i < len; i++) { + addOne(obj, types[i], fn, context); + } + } + + return this; +} + +var eventsKey = '_leaflet_events'; + +// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this +// Removes a previously added listener function. +// Note that if you passed a custom context to on, you must pass the same +// context to `off` in order to remove the listener. + +// @alternative +// @function off(el: HTMLElement, eventMap: Object, context?: Object): this +// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` +function off(obj, types, fn, context) { + + if (typeof types === 'object') { + for (var type in types) { + removeOne(obj, type, types[type], fn); + } + } else if (types) { + types = splitWords(types); + + for (var i = 0, len = types.length; i < len; i++) { + removeOne(obj, types[i], fn, context); + } + } else { + for (var j in obj[eventsKey]) { + removeOne(obj, j, obj[eventsKey][j]); + } + delete obj[eventsKey]; + } + + return this; +} + +function addOne(obj, type, fn, context) { + var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''); + + if (obj[eventsKey] && obj[eventsKey][id]) { return this; } + + var handler = function (e) { + return fn.call(context || obj, e || window.event); + }; + + var originalHandler = handler; + + if (pointer && type.indexOf('touch') === 0) { + // Needs DomEvent.Pointer.js + addPointerListener(obj, type, handler, id); + + } else if (touch && (type === 'dblclick') && addDoubleTapListener && + !(pointer && chrome)) { + // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener + // See #5180 + addDoubleTapListener(obj, handler, id); + + } else if ('addEventListener' in obj) { + + if (type === 'mousewheel') { + obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false); + + } else if ((type === 'mouseenter') || (type === 'mouseleave')) { + handler = function (e) { + e = e || window.event; + if (isExternalTarget(obj, e)) { + originalHandler(e); + } + }; + obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false); + + } else { + if (type === 'click' && android) { + handler = function (e) { + filterClick(e, originalHandler); + }; + } + obj.addEventListener(type, handler, false); + } + + } else if ('attachEvent' in obj) { + obj.attachEvent('on' + type, handler); + } + + obj[eventsKey] = obj[eventsKey] || {}; + obj[eventsKey][id] = handler; +} + +function removeOne(obj, type, fn, context) { + + var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''), + handler = obj[eventsKey] && obj[eventsKey][id]; + + if (!handler) { return this; } + + if (pointer && type.indexOf('touch') === 0) { + removePointerListener(obj, type, id); + + } else if (touch && (type === 'dblclick') && removeDoubleTapListener && + !(pointer && chrome)) { + removeDoubleTapListener(obj, id); + + } else if ('removeEventListener' in obj) { + + if (type === 'mousewheel') { + obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false); + + } else { + obj.removeEventListener( + type === 'mouseenter' ? 'mouseover' : + type === 'mouseleave' ? 'mouseout' : type, handler, false); + } + + } else if ('detachEvent' in obj) { + obj.detachEvent('on' + type, handler); + } + + obj[eventsKey][id] = null; +} + +// @function stopPropagation(ev: DOMEvent): this +// Stop the given event from propagation to parent elements. Used inside the listener functions: +// ```js +// L.DomEvent.on(div, 'click', function (ev) { +// L.DomEvent.stopPropagation(ev); +// }); +// ``` +function stopPropagation(e) { + + if (e.stopPropagation) { + e.stopPropagation(); + } else if (e.originalEvent) { // In case of Leaflet event. + e.originalEvent._stopped = true; + } else { + e.cancelBubble = true; + } + skipped(e); + + return this; +} + +// @function disableScrollPropagation(el: HTMLElement): this +// Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants). +function disableScrollPropagation(el) { + addOne(el, 'mousewheel', stopPropagation); + return this; +} + +// @function disableClickPropagation(el: HTMLElement): this +// Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`, +// `'mousedown'` and `'touchstart'` events (plus browser variants). +function disableClickPropagation(el) { + on(el, 'mousedown touchstart dblclick', stopPropagation); + addOne(el, 'click', fakeStop); + return this; +} + +// @function preventDefault(ev: DOMEvent): this +// Prevents the default action of the DOM Event `ev` from happening (such as +// following a link in the href of the a element, or doing a POST request +// with page reload when a `` is submitted). +// Use it inside listener functions. +function preventDefault(e) { + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + } + return this; +} + +// @function stop(ev: DOMEvent): this +// Does `stopPropagation` and `preventDefault` at the same time. +function stop(e) { + preventDefault(e); + stopPropagation(e); + return this; +} + +// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point +// Gets normalized mouse position from a DOM event relative to the +// `container` (border excluded) or to the whole page if not specified. +function getMousePosition(e, container) { + if (!container) { + return new Point(e.clientX, e.clientY); + } + + var scale = getScale(container), + offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y) + + return new Point( + // offset.left/top values are in page scale (like clientX/Y), + // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies). + (e.clientX - offset.left) / scale.x - container.clientLeft, + (e.clientY - offset.top) / scale.y - container.clientTop + ); +} + +// Chrome on Win scrolls double the pixels as in other platforms (see #4538), +// and Firefox scrolls device pixels, not CSS pixels +var wheelPxFactor = + (win && chrome) ? 2 * window.devicePixelRatio : + gecko ? window.devicePixelRatio : 1; + +// @function getWheelDelta(ev: DOMEvent): Number +// Gets normalized wheel delta from a mousewheel DOM event, in vertical +// pixels scrolled (negative if scrolling down). +// Events from pointing devices without precise scrolling are mapped to +// a best guess of 60 pixels. +function getWheelDelta(e) { + return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta + (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels + (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines + (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages + (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events + e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels + (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines + e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages + 0; +} + +var skipEvents = {}; + +function fakeStop(e) { + // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e) + skipEvents[e.type] = true; +} + +function skipped(e) { + var events = skipEvents[e.type]; + // reset when checking, as it's only used in map container and propagates outside of the map + skipEvents[e.type] = false; + return events; +} + +// check if element really left/entered the event target (for mouseenter/mouseleave) +function isExternalTarget(el, e) { + + var related = e.relatedTarget; + + if (!related) { return true; } + + try { + while (related && (related !== el)) { + related = related.parentNode; + } + } catch (err) { + return false; + } + return (related !== el); +} + +var lastClick; + +// this is a horrible workaround for a bug in Android where a single touch triggers two click events +function filterClick(e, handler) { + var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)), + elapsed = lastClick && (timeStamp - lastClick); + + // are they closer together than 500ms yet more than 100ms? + // Android typically triggers them ~300ms apart while multiple listeners + // on the same event should be triggered far faster; + // or check if click is simulated on the element, and if it is, reject any non-simulated events + + if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) { + stop(e); + return; + } + lastClick = timeStamp; + + handler(e); +} + + + + +var DomEvent = (Object.freeze || Object)({ + on: on, + off: off, + stopPropagation: stopPropagation, + disableScrollPropagation: disableScrollPropagation, + disableClickPropagation: disableClickPropagation, + preventDefault: preventDefault, + stop: stop, + getMousePosition: getMousePosition, + getWheelDelta: getWheelDelta, + fakeStop: fakeStop, + skipped: skipped, + isExternalTarget: isExternalTarget, + addListener: on, + removeListener: off }); /* @@ -3086,6 +3139,13 @@ var Map = Evented.extend({ initialize: function (id, options) { // (HTMLElement or String, Object) options = setOptions(this, options); + // Make sure to assign internal flags at the beginning, + // to avoid inconsistent state in some edge cases. + this._handlers = []; + this._layers = {}; + this._zoomBoundLayers = {}; + this._sizeChanged = true; + this._initContainer(id); this._initLayout(); @@ -3106,11 +3166,6 @@ var Map = Evented.extend({ this.setView(toLatLng(options.center), options.zoom, {reset: true}); } - this._handlers = []; - this._layers = {}; - this._zoomBoundLayers = {}; - this._sizeChanged = true; - this.callInitHooks(); // don't animate on browsers without hardware-accelerated transitions or old Android/Opera @@ -3385,7 +3440,7 @@ var Map = Evented.extend({ } } - this._moveStart(true); + this._moveStart(true, options.noMoveStart); frame.call(this); return this; @@ -3469,7 +3524,52 @@ var Map = Evented.extend({ return this; }, - // @method invalidateSize(options: Zoom/Pan options): this + // @method panInside(latlng: LatLng, options?: options): this + // Pans the map the minimum amount to make the `latlng` visible. Use + // `padding`, `paddingTopLeft` and `paddingTopRight` options to fit + // the display to more restricted bounds, like [`fitBounds`](#map-fitbounds). + // If `latlng` is already within the (optionally padded) display bounds, + // the map will not be panned. + panInside: function (latlng, options) { + options = options || {}; + + var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]), + paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]), + center = this.getCenter(), + pixelCenter = this.project(center), + pixelPoint = this.project(latlng), + pixelBounds = this.getPixelBounds(), + halfPixelBounds = pixelBounds.getSize().divideBy(2), + paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]); + + if (!paddedBounds.contains(pixelPoint)) { + this._enforcingBounds = true; + var diff = pixelCenter.subtract(pixelPoint), + newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y); + + if (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) { + newCenter.x = pixelCenter.x - diff.x; + if (diff.x > 0) { + newCenter.x += halfPixelBounds.x - paddingTL.x; + } else { + newCenter.x -= halfPixelBounds.x - paddingBR.x; + } + } + if (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) { + newCenter.y = pixelCenter.y - diff.y; + if (diff.y > 0) { + newCenter.y += halfPixelBounds.y - paddingTL.y; + } else { + newCenter.y -= halfPixelBounds.y - paddingBR.y; + } + } + this.panTo(this.unproject(newCenter), options); + this._enforcingBounds = false; + } + return this; + }, + + // @method invalidateSize(options: Zoom/pan options): this // Checks if the map container size changed and updates the map if so — // call it after you've changed the map size dynamically, also animating // pan by default. If `options.pan` is `false`, panning will not occur. @@ -3616,7 +3716,7 @@ var Map = Evented.extend({ var lat = pos.coords.latitude, lng = pos.coords.longitude, latlng = new LatLng(lat, lng), - bounds = latlng.toBounds(pos.coords.accuracy), + bounds = latlng.toBounds(pos.coords.accuracy * 2), options = this._locateOptions; if (options.setView) { @@ -3642,7 +3742,6 @@ var Map = Evented.extend({ this.fire('locationfound', data); }, - // TODO handler.addTo // TODO Appropriate docs section? // @section Other Methods // @method addHandler(name: String, HandlerClass: Function): this @@ -3682,6 +3781,10 @@ var Map = Evented.extend({ this._containerId = undefined; } + if (this._locationWatchId !== undefined) { + this.stopLocate(); + } + this._stop(); remove(this._mapPane); @@ -3689,6 +3792,10 @@ var Map = Evented.extend({ if (this._clearControlPos) { this._clearControlPos(); } + if (this._resizeRequest) { + cancelAnimFrame(this._resizeRequest); + this._resizeRequest = null; + } this._clearHandlers(); @@ -3773,7 +3880,7 @@ var Map = Evented.extend({ this.options.maxZoom; }, - // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number + // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number // Returns the maximum zoom level on which the given bounds fit to the map // view in its entirety. If `inside` (optional) is set to `true`, the method // instead returns the minimum zoom level on which the map view fits into @@ -4098,7 +4205,7 @@ var Map = Evented.extend({ var zoomChanged = this._zoom !== zoom; this - ._moveStart(zoomChanged) + ._moveStart(zoomChanged, false) ._move(center, zoom) ._moveEnd(zoomChanged); @@ -4115,7 +4222,7 @@ var Map = Evented.extend({ } }, - _moveStart: function (zoomChanged) { + _moveStart: function (zoomChanged, noMoveStart) { // @event zoomstart: Event // Fired when the map zoom is about to change (e.g. before zoom animation). // @event movestart: Event @@ -4123,7 +4230,10 @@ var Map = Evented.extend({ if (zoomChanged) { this.fire('zoomstart'); } - return this.fire('movestart'); + if (!noMoveStart) { + this.fire('movestart'); + } + return this; }, _move: function (center, zoom, data) { @@ -4219,9 +4329,15 @@ var Map = Evented.extend({ // this event. Also fired on mobile when the user holds a single touch // for a second (also called long press). // @event keypress: KeyboardEvent - // Fired when the user presses a key from the keyboard while the map is focused. + // Fired when the user presses a key from the keyboard that produces a character value while the map is focused. + // @event keydown: KeyboardEvent + // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event, + // the `keydown` event is fired for keys that produce a character value and for keys + // that do not produce a character value. + // @event keyup: KeyboardEvent + // Fired when the user releases a key from the keyboard while the map is focused. onOff(this._container, 'click dblclick mousedown mouseup ' + - 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this); + 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this); if (this.options.trackResize) { onOff(window, 'resize', this._onResize, this); @@ -4285,7 +4401,7 @@ var Map = Evented.extend({ var type = e.type; - if (type === 'mousedown' || type === 'keypress') { + if (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') { // prevents outline when clicking on keyboard-focusable element preventOutline(e.target || e.srcElement); } @@ -4324,7 +4440,7 @@ var Map = Evented.extend({ originalEvent: e }; - if (e.type !== 'keypress') { + if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') { var isMarker = target.getLatLng && (!target._radius || target._radius <= 10); data.containerPoint = isMarker ? this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e); @@ -4513,20 +4629,23 @@ var Map = Evented.extend({ } }, this); - this.on('load moveend', function () { - var c = this.getCenter(), - z = this.getZoom(); - setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1)); - }, this); + this.on('load moveend', this._animMoveEnd, this); this._on('unload', this._destroyAnimProxy, this); }, _destroyAnimProxy: function () { remove(this._proxy); + this.off('load moveend', this._animMoveEnd, this); delete this._proxy; }, + _animMoveEnd: function () { + var c = this.getCenter(), + z = this.getZoom(); + setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1)); + }, + _catchTransitionEnd: function (e) { if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) { this._onZoomTransitionEnd(); @@ -4556,7 +4675,7 @@ var Map = Evented.extend({ requestAnimFrame(function () { this - ._moveStart(true) + ._moveStart(true, false) ._animateZoom(center, zoom, true); }, this); @@ -4564,6 +4683,8 @@ var Map = Evented.extend({ }, _animateZoom: function (center, zoom, startAnim, noUpdate) { + if (!this._mapPane) { return; } + if (startAnim) { this._animatingZoom = true; @@ -4574,8 +4695,9 @@ var Map = Evented.extend({ addClass(this._mapPane, 'leaflet-zoom-anim'); } + // @section Other Events // @event zoomanim: ZoomAnimEvent - // Fired on every frame of a zoom animation + // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom. this.fire('zoomanim', { center: center, zoom: zoom, @@ -4693,6 +4815,8 @@ var Control = Class.extend({ corner.appendChild(container); } + this._map.on('unload', this.remove, this); + return this; }, @@ -4709,6 +4833,7 @@ var Control = Class.extend({ this.onRemove(this._map); } + this._map.off('unload', this.remove, this); this._map = null; return this; @@ -4931,13 +5056,13 @@ var Layers = Control.extend({ // Expand the control container if collapsed. expand: function () { addClass(this._container, 'leaflet-control-layers-expanded'); - this._form.style.height = null; + this._section.style.height = null; var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50); - if (acceptableHeight < this._form.clientHeight) { - addClass(this._form, 'leaflet-control-layers-scrollbar'); - this._form.style.height = acceptableHeight + 'px'; + if (acceptableHeight < this._section.clientHeight) { + addClass(this._section, 'leaflet-control-layers-scrollbar'); + this._section.style.height = acceptableHeight + 'px'; } else { - removeClass(this._form, 'leaflet-control-layers-scrollbar'); + removeClass(this._section, 'leaflet-control-layers-scrollbar'); } this._checkDisabledLayers(); return this; @@ -4961,7 +5086,7 @@ var Layers = Control.extend({ disableClickPropagation(container); disableScrollPropagation(container); - var form = this._form = create$1('form', className + '-list'); + var section = this._section = create$1('section', className + '-list'); if (collapsed) { this._map.on('click', this.collapse, this); @@ -4989,11 +5114,11 @@ var Layers = Control.extend({ this.expand(); } - this._baseLayersList = create$1('div', className + '-base', form); - this._separator = create$1('div', className + '-separator', form); - this._overlaysList = create$1('div', className + '-overlays', form); + this._baseLayersList = create$1('div', className + '-base', section); + this._separator = create$1('div', className + '-separator', section); + this._overlaysList = create$1('div', className + '-overlays', section); - container.appendChild(form); + container.appendChild(section); }, _getLayer: function (id) { @@ -5106,7 +5231,7 @@ var Layers = Control.extend({ input.className = 'leaflet-control-layers-selector'; input.defaultChecked = checked; } else { - input = this._createRadioElement('leaflet-base-layers', checked); + input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked); } this._layerControlInputs.push(input); @@ -5204,7 +5329,7 @@ var Layers = Control.extend({ // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options) -// Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation. +// Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation. var layers = function (baseLayers, overlays, options) { return new Layers(baseLayers, overlays, options); }; @@ -5330,6 +5455,10 @@ Map.mergeOptions({ Map.addInitHook(function () { if (this.options.zoomControl) { + // @section Controls + // @property zoomControl: Control.Zoom + // The default zoom control (only available if the + // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map). this.zoomControl = new Zoom(); this.addControl(this.zoomControl); } @@ -5487,7 +5616,7 @@ var Attribution = Control.extend({ // @option prefix: String = 'Leaflet' // The HTML text shown before the attributions. Pass `false` to disable. - prefix: 'Leaflet' + prefix: 'Leaflet' }, initialize: function (options) { @@ -5652,6 +5781,14 @@ var Handler = Class.extend({ // Called when the handler is disabled, should remove the event hooks added previously. }); +// @section There is static function which can be called without instantiating L.Handler: +// @function addTo(map: Map, name: String): this +// Adds a new Handler to the given map with the given name. +Handler.addTo = function (map, name) { + map.addHandler(name, this); + return this; +}; + var Mixin = {Events: Events}; /* @@ -5761,10 +5898,14 @@ var Draggable = Evented.extend({ // Fired when a drag is about to start. this.fire('down'); - var first = e.touches ? e.touches[0] : e; + var first = e.touches ? e.touches[0] : e, + sizedParent = getSizedParentNode(this._element); this._startPoint = new Point(first.clientX, first.clientY); + // Cache the scale, so that we can continuously compensate for it during drag (_onMove). + this._parentScale = getScale(sizedParent); + on(document, MOVE[e.type], this._onMove, this); on(document, END[e.type], this._onUp, this); }, @@ -5783,12 +5924,17 @@ var Draggable = Evented.extend({ } var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e), - newPoint = new Point(first.clientX, first.clientY), - offset = newPoint.subtract(this._startPoint); + offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint); if (!offset.x && !offset.y) { return; } if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; } + // We assume that the parent container's position, border and scale do not change for the duration of the drag. + // Therefore there is no need to account for the position and border (they are eliminated by the subtraction) + // and we can use the cached value for the scale. + offset.x /= this._parentScale.x; + offset.y /= this._parentScale.y; + preventDefault(e); if (!this._moved) { @@ -6115,7 +6261,7 @@ function _flat(latlngs) { } -var LineUtil = Object.freeze({ +var LineUtil = (Object.freeze || Object)({ simplify: simplify, pointToSegmentDistance: pointToSegmentDistance, closestPointOnSegment: closestPointOnSegment, @@ -6182,7 +6328,7 @@ function clipPolygon(points, bounds, round) { } -var PolyUtil = Object.freeze({ +var PolyUtil = (Object.freeze || Object)({ clipPolygon: clipPolygon }); @@ -6215,7 +6361,7 @@ var LonLat = { * @namespace Projection * @projection L.Projection.Mercator * - * Elliptical Mercator projection — more complex than Spherical Mercator. Takes into account that Earth is a geoid, not a perfect sphere. Used by the EPSG:3395 CRS. + * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS. */ var Mercator = { @@ -6283,7 +6429,7 @@ var Mercator = { -var index = Object.freeze({ +var index = (Object.freeze || Object)({ LonLat: LonLat, Mercator: Mercator, SphericalMercator: SphericalMercator @@ -6375,7 +6521,7 @@ CRS.Simple = Simple; * @example * * ```js - * var layer = L.Marker(latlng).addTo(map); + * var layer = L.marker(latlng).addTo(map); * layer.addTo(map); * layer.remove(); * ``` @@ -6397,7 +6543,7 @@ var Layer = Evented.extend({ pane: 'overlayPane', // @option attribution: String = null - // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox". + // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. attribution: null, bubblingMouseEvents: true @@ -6934,9 +7080,12 @@ var Icon = Class.extend({ * will be aligned so that this point is at the marker's geographical location. Centered * by default if size is specified, also can be set in CSS with negative margins. * - * @option popupAnchor: Point = null + * @option popupAnchor: Point = [0, 0] * The coordinates of the point from which popups will "open", relative to the icon anchor. * + * @option tooltipAnchor: Point = [0, 0] + * The coordinates of the point from which tooltips will "open", relative to the icon anchor. + * * @option shadowUrl: String = null * The URL to the icon shadow image. If not specified, no shadow image will be created. * @@ -6953,6 +7102,11 @@ var Icon = Class.extend({ * A custom class name to assign to both icon and shadow images. Empty by default. */ + options: { + popupAnchor: [0, 0], + tooltipAnchor: [0, 0] + }, + initialize: function (options) { setOptions(this, options); }, @@ -7149,7 +7303,7 @@ var MarkerDrag = Handler.extend({ map = marker._map, speed = this._marker.options.autoPanSpeed, padding = this._marker.options.autoPanPadding, - iconPos = L.DomUtil.getPosition(marker._icon), + iconPos = getPosition(marker._icon), bounds = map.getPixelBounds(), origin = map.getPixelOrigin(); @@ -7173,7 +7327,7 @@ var MarkerDrag = Handler.extend({ this._draggable._newPos._add(movement); this._draggable._startPos._add(movement); - L.DomUtil.setPosition(marker._icon, this._draggable._newPos); + setPosition(marker._icon, this._draggable._newPos); this._onDrag(e); this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e)); @@ -7205,7 +7359,7 @@ var MarkerDrag = Handler.extend({ _onDrag: function (e) { var marker = this._marker, shadow = marker._shadow, - iconPos = getPosition(marker._icon), + iconPos = getPosition(marker._icon), latlng = marker._map.layerPointToLatLng(iconPos); // update shadow position @@ -7266,22 +7420,6 @@ var Marker = Layer.extend({ // Option inherited from "Interactive layer" abstract class interactive: true, - // @option draggable: Boolean = false - // Whether the marker is draggable with mouse/touch or not. - draggable: false, - - // @option autoPan: Boolean = false - // Set it to `true` if you want the map to do panning animation when marker hits the edges. - autoPan: false, - - // @option autoPanPadding: Point = Point(50, 50) - // Equivalent of setting both top left and bottom right autopan padding to the same value. - autoPanPadding: [50, 50], - - // @option autoPanSpeed: Number = 10 - // Number of pixels the map should move by. - autoPanSpeed: 10, - // @option keyboard: Boolean = true // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. keyboard: true, @@ -7314,10 +7452,32 @@ var Marker = Layer.extend({ // `Map pane` where the markers icon will be added. pane: 'markerPane', + // @option pane: String = 'shadowPane' + // `Map pane` where the markers shadow will be added. + shadowPane: 'shadowPane', + // @option bubblingMouseEvents: Boolean = false // When `true`, a mouse event on this marker will trigger the same event on the map // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). - bubblingMouseEvents: false + bubblingMouseEvents: false, + + // @section Draggable marker options + // @option draggable: Boolean = false + // Whether the marker is draggable with mouse/touch or not. + draggable: false, + + // @option autoPan: Boolean = false + // Whether to pan the map when dragging this marker near its edge or not. + autoPan: false, + + // @option autoPanPadding: Point = Point(50, 50) + // Distance (in pixels to the left/right and to the top/bottom) of the + // map edge to start panning the map. + autoPanPadding: [50, 50], + + // @option autoPanSpeed: Number = 10 + // Number of pixels the map should pan by. + autoPanSpeed: 10 }, /* @section @@ -7388,6 +7548,12 @@ var Marker = Layer.extend({ return this.update(); }, + // @method getIcon: Icon + // Returns the current icon used by the marker + getIcon: function () { + return this.options.icon; + }, + // @method setIcon(icon: Icon): this // Changes the marker icon. setIcon: function (icon) { @@ -7437,8 +7603,9 @@ var Marker = Layer.extend({ if (options.title) { icon.title = options.title; } - if (options.alt) { - icon.alt = options.alt; + + if (icon.tagName === 'IMG') { + icon.alt = options.alt || ''; } } @@ -7482,7 +7649,7 @@ var Marker = Layer.extend({ } this._initInteraction(); if (newShadow && addShadow) { - this.getPane('shadowPane').appendChild(this._shadow); + this.getPane(options.shadowPane).appendChild(this._shadow); } }, @@ -7508,7 +7675,10 @@ var Marker = Layer.extend({ }, _setPos: function (pos) { - setPosition(this._icon, pos); + + if (this._icon) { + setPosition(this._icon, pos); + } if (this._shadow) { setPosition(this._shadow, pos); @@ -7520,7 +7690,9 @@ var Marker = Layer.extend({ }, _updateZIndex: function (offset) { - this._icon.style.zIndex = this._zIndex + offset; + if (this._icon) { + this._icon.style.zIndex = this._zIndex + offset; + } }, _animateZoom: function (opt) { @@ -7566,7 +7738,9 @@ var Marker = Layer.extend({ _updateOpacity: function () { var opacity = this.options.opacity; - setOpacity(this._icon, opacity); + if (this._icon) { + setOpacity(this._icon, opacity); + } if (this._shadow) { setOpacity(this._shadow, opacity); @@ -7582,11 +7756,11 @@ var Marker = Layer.extend({ }, _getPopupAnchor: function () { - return this.options.icon.options.popupAnchor || [0, 0]; + return this.options.icon.options.popupAnchor; }, _getTooltipAnchor: function () { - return this.options.icon.options.tooltipAnchor || [0, 0]; + return this.options.icon.options.tooltipAnchor; } }); @@ -7703,6 +7877,9 @@ var Path = Layer.extend({ setOptions(this, style); if (this._renderer) { this._renderer._updateStyle(this); + if (this.options.stroke && style && style.hasOwnProperty('weight')) { + this._updateBounds(); + } } return this; }, @@ -7737,7 +7914,7 @@ var Path = Layer.extend({ _clickTolerance: function () { // used when doing hit detection for Canvas layers - return (this.options.stroke ? this.options.weight / 2 : 0) + (touch ? 10 : 0); + return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance; } }); @@ -7770,9 +7947,13 @@ var CircleMarker = Path.extend({ // @method setLatLng(latLng: LatLng): this // Sets the position of a circle marker to a new location. setLatLng: function (latlng) { + var oldLatLng = this._latlng; this._latlng = toLatLng(latlng); this.redraw(); - return this.fire('move', {latlng: this._latlng}); + + // @event move: Event + // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. + return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng}); }, // @method getLatLng(): LatLng @@ -8025,7 +8206,7 @@ var Polyline = Path.extend({ return !this._latlngs.length; }, - // @method closestLayerPoint: Point + // @method closestLayerPoint(p: Point): Point // Returns the point closest to `p` on the Polyline. closestLayerPoint: function (p) { var minDistance = Infinity, @@ -8144,14 +8325,19 @@ var Polyline = Path.extend({ this._rings = []; this._projectLatlngs(this._latlngs, this._rings, pxBounds); + if (this._bounds.isValid() && pxBounds.isValid()) { + this._rawPxBounds = pxBounds; + this._updateBounds(); + } + }, + + _updateBounds: function () { var w = this._clickTolerance(), p = new Point(w, w); - - if (this._bounds.isValid() && pxBounds.isValid()) { - pxBounds.min._subtract(p); - pxBounds.max._add(p); - this._pxBounds = pxBounds; - } + this._pxBounds = new Bounds([ + this._rawPxBounds.min.subtract(p), + this._rawPxBounds.max.add(p) + ]); }, // recursively turns latlngs into a set of rings with projected coordinates @@ -8418,7 +8604,7 @@ var Polygon = Polyline.extend({ var inside = false, part, p1, p2, i, j, k, len, len2; - if (!this._pxBounds.contains(p)) { return false; } + if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; } // ray casting algorithm for detecting if point is in polygon for (i = 0, len = this._parts.length; i < len; i++) { @@ -8514,6 +8700,9 @@ var GeoJSON = FeatureGroup.extend({ * @option coordsToLatLng: Function = * * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s. * The default is the `coordsToLatLng` static method. + * + * @option markersInheritOptions: Boolean = false + * Whether default Markers for "Point" type Features inherit from group options. */ initialize: function (geojson, options) { @@ -8563,9 +8752,13 @@ var GeoJSON = FeatureGroup.extend({ return this.addLayer(layer); }, - // @method resetStyle( layer ): this + // @method resetStyle( layer? ): this // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events. + // If `layer` is omitted, the style of all features in the current layer is reset. resetStyle: function (layer) { + if (layer === undefined) { + return this.eachLayer(this.resetStyle, this); + } // reset any custom styles layer.options = extend({}, layer.defaultOptions); this._setLayerStyle(layer, this.options.style); @@ -8581,10 +8774,10 @@ var GeoJSON = FeatureGroup.extend({ }, _setLayerStyle: function (layer, style) { - if (typeof style === 'function') { - style = style(layer.feature); - } if (layer.setStyle) { + if (typeof style === 'function') { + style = style(layer.feature); + } layer.setStyle(style); } } @@ -8613,12 +8806,12 @@ function geometryToLayer(geojson, options) { switch (geometry.type) { case 'Point': latlng = _coordsToLatLng(coords); - return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng); + return _pointToLayer(pointToLayer, geojson, latlng, options); case 'MultiPoint': for (i = 0, len = coords.length; i < len; i++) { latlng = _coordsToLatLng(coords[i]); - layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng)); + layers.push(_pointToLayer(pointToLayer, geojson, latlng, options)); } return new FeatureGroup(layers); @@ -8651,6 +8844,12 @@ function geometryToLayer(geojson, options) { } } +function _pointToLayer(pointToLayerFn, geojson, latlng, options) { + return pointToLayerFn ? + pointToLayerFn(geojson, latlng) : + new Marker(latlng, options && options.markersInheritOptions && options); +} + // @function coordsToLatLng(coords: Array): LatLng // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude) // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points. @@ -8734,19 +8933,26 @@ var PointToGeoJSON = { }; // @namespace Marker -// @method toGeoJSON(): Object +// @section Other methods +// @method toGeoJSON(precision?: Number): Object +// `precision` is the number of decimal places for coordinates. +// The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature). Marker.include(PointToGeoJSON); // @namespace CircleMarker -// @method toGeoJSON(): Object +// @method toGeoJSON(precision?: Number): Object +// `precision` is the number of decimal places for coordinates. +// The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature). Circle.include(PointToGeoJSON); CircleMarker.include(PointToGeoJSON); // @namespace Polyline -// @method toGeoJSON(): Object +// @method toGeoJSON(precision?: Number): Object +// `precision` is the number of decimal places for coordinates. +// The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature). Polyline.include({ toGeoJSON: function (precision) { @@ -8762,7 +8968,9 @@ Polyline.include({ }); // @namespace Polygon -// @method toGeoJSON(): Object +// @method toGeoJSON(precision?: Number): Object +// `precision` is the number of decimal places for coordinates. +// The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature). Polygon.include({ toGeoJSON: function (precision) { @@ -8798,7 +9006,9 @@ LayerGroup.include({ }); }, - // @method toGeoJSON(): Object + // @method toGeoJSON(precision?: Number): Object + // `precision` is the number of decimal places for coordinates. + // The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`). toGeoJSON: function (precision) { @@ -8845,7 +9055,7 @@ LayerGroup.include({ // @namespace GeoJSON // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options) // Creates a GeoJSON layer. Optionally accepts an object in -// [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map +// [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map // (you can alternatively add it later with `addData` method) and an `options` object. function geoJSON(geojson, options) { return new GeoJSON(geojson, options); @@ -8887,8 +9097,10 @@ var ImageOverlay = Layer.extend({ // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered. interactive: false, - // @option crossOrigin: Boolean = false - // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data. + // @option crossOrigin: Boolean|String = false + // Whether the crossOrigin attribute will be added to the image. + // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. + // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. crossOrigin: false, // @option errorOverlayUrl: String = '' @@ -8896,12 +9108,12 @@ var ImageOverlay = Layer.extend({ errorOverlayUrl: '', // @option zIndex: Number = 1 - // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the tile layer. + // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer. zIndex: 1, // @option className: String = '' // A custom class name to assign to the image. Empty by default. - className: '', + className: '' }, initialize: function (url, bounds, options) { // (String, LatLngBounds, Object) @@ -9007,7 +9219,7 @@ var ImageOverlay = Layer.extend({ return events; }, - // @method: setZIndex(value: Number) : this + // @method setZIndex(value: Number): this // Changes the [zIndex](#imageoverlay-zindex) of the image overlay. setZIndex: function (value) { this.options.zIndex = value; @@ -9029,9 +9241,12 @@ var ImageOverlay = Layer.extend({ }, _initImage: function () { - var img = this._image = create$1('img', - 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated ' : '') + - (this.options.className || '')); + var wasElementSupplied = this._url.tagName === 'IMG'; + var img = this._image = wasElementSupplied ? this._url : create$1('img'); + + addClass(img, 'leaflet-image-layer'); + if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); } + if (this.options.className) { addClass(img, this.options.className); } img.onselectstart = falseFn; img.onmousemove = falseFn; @@ -9041,14 +9256,19 @@ var ImageOverlay = Layer.extend({ img.onload = bind(this.fire, this, 'load'); img.onerror = bind(this._overlayOnError, this, 'error'); - if (this.options.crossOrigin) { - img.crossOrigin = ''; + if (this.options.crossOrigin || this.options.crossOrigin === '') { + img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin; } if (this.options.zIndex) { this._updateZIndex(); } + if (wasElementSupplied) { + this._url = img.src; + return; + } + img.src = this._url; img.alt = this.options.alt; }, @@ -9085,7 +9305,7 @@ var ImageOverlay = Layer.extend({ _overlayOnError: function () { // @event error: Event - // Fired when the ImageOverlay layer has loaded its image + // Fired when the ImageOverlay layer fails to load its image this.fire('error'); var errorUrl = this.options.errorOverlayUrl; @@ -9118,7 +9338,7 @@ var imageOverlay = function (url, bounds, options) { * ```js * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm', * videoBounds = [[ 32, -130], [ 13, -100]]; - * L.VideoOverlay(videoUrl, videoBounds ).addTo(map); + * L.videoOverlay(videoUrl, videoBounds ).addTo(map); * ``` */ @@ -9133,7 +9353,12 @@ var VideoOverlay = ImageOverlay.extend({ // @option loop: Boolean = true // Whether the video will loop back to the beginning when played. - loop: true + loop: true, + + // @option keepAspectRatio: Boolean = true + // Whether the video will save aspect ratio after the projection. + // Relevant for supported browsers. Browser compatibility- https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit + keepAspectRatio: true }, _initImage: function () { @@ -9142,6 +9367,7 @@ var VideoOverlay = ImageOverlay.extend({ addClass(vid, 'leaflet-image-layer'); if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); } + if (this.options.className) { addClass(vid, this.options.className); } vid.onselectstart = falseFn; vid.onmousemove = falseFn; @@ -9150,10 +9376,20 @@ var VideoOverlay = ImageOverlay.extend({ // Fired when the video has finished loading the first frame vid.onloadeddata = bind(this.fire, this, 'load'); - if (wasElementSupplied) { return; } + if (wasElementSupplied) { + var sourceElements = vid.getElementsByTagName('source'); + var sources = []; + for (var j = 0; j < sourceElements.length; j++) { + sources.push(sourceElements[j].src); + } + + this._url = (sourceElements.length > 0) ? sources : [vid.src]; + return; + } if (!isArray(this._url)) { this._url = [this._url]; } + if (!this.options.keepAspectRatio && vid.style.hasOwnProperty('objectFit')) { vid.style['objectFit'] = 'fill'; } vid.autoplay = !!this.options.autoplay; vid.loop = !!this.options.loop; for (var i = 0; i < this._url.length; i++) { @@ -9177,6 +9413,53 @@ function videoOverlay(video, bounds, options) { return new VideoOverlay(video, bounds, options); } +/* + * @class SVGOverlay + * @aka L.SVGOverlay + * @inherits ImageOverlay + * + * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`. + * + * An SVG overlay uses the [``](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element. + * + * @example + * + * ```js + * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg"); + * svgElement.setAttribute('viewBox', "0 0 200 200"); + * svgElement.innerHTML = ''; + * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ]; + * L.svgOverlay(svgElement, svgElementBounds).addTo(map); + * ``` + */ + +var SVGOverlay = ImageOverlay.extend({ + _initImage: function () { + var el = this._image = this._url; + + addClass(el, 'leaflet-image-layer'); + if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); } + if (this.options.className) { addClass(el, this.options.className); } + + el.onselectstart = falseFn; + el.onmousemove = falseFn; + } + + // @method getElement(): SVGElement + // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement) + // used by this overlay. +}); + + +// @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options) +// Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to. +// A viewBox attribute is required on the SVG element to zoom in and out properly. + +function svgOverlay(el, bounds, options) { + return new SVGOverlay(el, bounds, options); +} + /* * @class DivOverlay * @inherits Layer @@ -9331,6 +9614,38 @@ var DivOverlay = Layer.extend({ return this; }, + _prepareOpen: function (parent, layer, latlng) { + if (!(layer instanceof Layer)) { + latlng = layer; + layer = parent; + } + + if (layer instanceof FeatureGroup) { + for (var id in parent._layers) { + layer = parent._layers[id]; + break; + } + } + + if (!latlng) { + if (layer.getCenter) { + latlng = layer.getCenter(); + } else if (layer.getLatLng) { + latlng = layer.getLatLng(); + } else { + throw new Error('Unable to get source layer LatLng.'); + } + } + + // set overlay source to this layer + this._source = layer; + + // update the overlay (content, layout, ect...) + this.update(); + + return latlng; + }, + _updateContent: function () { if (!this._content) { return; } @@ -9602,7 +9917,8 @@ var Popup = DivOverlay.extend({ }, _adjustPan: function () { - if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; } + if (!this.options.autoPan) { return; } + if (this._map._panAnim) { this._map._panAnim.stop(); } var map = this._map, marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0, @@ -9784,28 +10100,8 @@ Layer.include({ // @method openPopup(latlng?: LatLng): this // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. openPopup: function (layer, latlng) { - if (!(layer instanceof Layer)) { - latlng = layer; - layer = this; - } - - if (layer instanceof FeatureGroup) { - for (var id in this._layers) { - layer = this._layers[id]; - break; - } - } - - if (!latlng) { - latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng(); - } - if (this._popup && this._map) { - // set popup source to this layer - this._popup._source = layer; - - // update the popup (content, layout, ect...) - this._popup.update(); + latlng = this._popup._prepareOpen(this, layer, latlng); // open the popup on the map this._map.openPopup(this._popup, latlng); @@ -10202,29 +10498,8 @@ Layer.include({ // @method openTooltip(latlng?: LatLng): this // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. openTooltip: function (layer, latlng) { - if (!(layer instanceof Layer)) { - latlng = layer; - layer = this; - } - - if (layer instanceof FeatureGroup) { - for (var id in this._layers) { - layer = this._layers[id]; - break; - } - } - - if (!latlng) { - latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng(); - } - if (this._tooltip && this._map) { - - // set tooltip source to this layer - this._tooltip._source = layer; - - // update the tooltip (content, layout, ect...) - this._tooltip.update(); + latlng = this._tooltip._prepareOpen(this, layer, latlng); // open the tooltip on the map this._map.openTooltip(this._tooltip, latlng); @@ -10335,8 +10610,9 @@ var DivIcon = Icon.extend({ // iconAnchor: (Point), // popupAnchor: (Point), - // @option html: String = '' - // Custom HTML code to put inside the div element, empty by default. + // @option html: String|HTMLElement = '' + // Custom HTML code to put inside the div element, empty by default. Alternatively, + // an instance of `HTMLElement`. html: false, // @option bgPos: Point = [0, 0] @@ -10350,7 +10626,12 @@ var DivIcon = Icon.extend({ var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'), options = this.options; - div.innerHTML = options.html !== false ? options.html : ''; + if (options.html instanceof Element) { + empty(div); + div.appendChild(options.html); + } else { + div.innerHTML = options.html !== false ? options.html : ''; + } if (options.bgPos) { var bgPos = toPoint(options.bgPos); @@ -10540,7 +10821,7 @@ var GridLayer = Layer.extend({ remove(this._container); map._removeZoomLimit(this); this._container = null; - this._tileZoom = null; + this._tileZoom = undefined; }, // @method bringToFront: this @@ -10834,7 +11115,7 @@ var GridLayer = Layer.extend({ } this._removeAllTiles(); - this._tileZoom = null; + this._tileZoom = undefined; }, _retainParent: function (x, y, z, minZoom) { @@ -11136,12 +11417,6 @@ var GridLayer = Layer.extend({ var tile = this._tiles[key]; if (!tile) { return; } - // Cancels any pending http requests associated with the tile - // unless we're on Android's stock browser, - // see https://github.com/Leaflet/Leaflet/issues/137 - if (!androidStock) { - tile.el.setAttribute('src', emptyImageUrl); - } remove(tile.el); delete this._tiles[key]; @@ -11210,8 +11485,6 @@ var GridLayer = Layer.extend({ }, _tileReady: function (coords, err, tile) { - if (!this._map) { return; } - if (err) { // @event tileerror: TileErrorEvent // Fired when there is an error loading a tile. @@ -11301,12 +11574,12 @@ function gridLayer(options) { * @class TileLayer * @inherits GridLayer * @aka L.TileLayer - * Used to load and display tile layers on the map. Extends `GridLayer`. + * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`. * * @example * * ```js - * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map); + * L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA'}).addTo(map); * ``` * * @section URL template @@ -11365,8 +11638,10 @@ var TileLayer = GridLayer.extend({ // If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution. detectRetina: false, - // @option crossOrigin: Boolean = false - // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data. + // @option crossOrigin: Boolean|String = false + // Whether the crossOrigin attribute will be added to the tiles. + // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. + // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. crossOrigin: false }, @@ -11404,7 +11679,13 @@ var TileLayer = GridLayer.extend({ // @method setUrl(url: String, noRedraw?: Boolean): this // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`). + // If the URL does not change, the layer will not be redrawn unless + // the noRedraw parameter is set to false. setUrl: function (url, noRedraw) { + if (this._url === url && noRedraw === undefined) { + noRedraw = true; + } + this._url = url; if (!noRedraw) { @@ -11423,8 +11704,8 @@ var TileLayer = GridLayer.extend({ on(tile, 'load', bind(this._tileOnLoad, this, done, tile)); on(tile, 'error', bind(this._tileOnError, this, done, tile)); - if (this.options.crossOrigin) { - tile.crossOrigin = ''; + if (this.options.crossOrigin || this.options.crossOrigin === '') { + tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin; } /* @@ -11456,7 +11737,7 @@ var TileLayer = GridLayer.extend({ s: this._getSubdomain(coords), x: coords.x, y: coords.y, - z: coords.z ? coords.z : this._getZoomForUrl() + z: this._getZoomForUrl() }; if (this._map && !this._map.options.crs.infinite) { var invertedY = this._globalTileRange.max.y - coords.y; @@ -11525,6 +11806,28 @@ var TileLayer = GridLayer.extend({ } } } + }, + + _removeTile: function (key) { + var tile = this._tiles[key]; + if (!tile) { return; } + + // Cancels any pending http requests associated with the tile + // unless we're on Android's stock browser, + // see https://github.com/Leaflet/Leaflet/issues/137 + if (!androidStock) { + tile.el.setAttribute('src', emptyImageUrl); + } + + return GridLayer.prototype._removeTile.call(this, key); + }, + + _tileReady: function (coords, err, tile) { + if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) { + return; + } + + return GridLayer.prototype._tileReady.call(this, coords, err, tile); } }); @@ -11612,7 +11915,10 @@ var TileLayerWMS = TileLayer.extend({ options = setOptions(this, options); - wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && retina ? 2 : 1); + var realRetina = options.detectRetina && retina ? 2 : 1; + var tileSize = this.getTileSize(); + wmsParams.width = tileSize.x * realRetina; + wmsParams.height = tileSize.y * realRetina; this.wmsParams = wmsParams; }, @@ -11638,7 +11944,7 @@ var TileLayerWMS = TileLayer.extend({ bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ? [min.y, min.x, max.y, max.x] : [min.x, min.y, max.x, max.y]).join(','), - url = L.TileLayer.prototype.getTileUrl.call(this, coords); + url = TileLayer.prototype.getTileUrl.call(this, coords); return url + getParamString(this.wmsParams, url, this.options.uppercase) + (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox; @@ -11696,7 +12002,11 @@ var Renderer = Layer.extend({ // @option padding: Number = 0.1 // How much to extend the clip area around the map view (relative to its size) // e.g. 0.1 would be 10% of map view in each direction - padding: 0.1 + padding: 0.1, + + // @option tolerance: Number = 0 + // How much to extend click tolerance round a path/object on the map + tolerance : 0 }, initialize: function (options) { @@ -11852,7 +12162,7 @@ var Canvas = Renderer.extend({ _initContainer: function () { var container = this._container = document.createElement('canvas'); - on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this); + on(container, 'mousemove', this._onMouseMove, this); on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this); on(container, 'mouseout', this._handleMouseOut, this); @@ -11860,6 +12170,7 @@ var Canvas = Renderer.extend({ }, _destroyContainer: function () { + cancelAnimFrame(this._redrawRequest); delete this._ctx; remove(this._container); off(this._container); @@ -11881,8 +12192,6 @@ var Canvas = Renderer.extend({ _update: function () { if (this._map._animatingZoom && this._bounds) { return; } - this._drawnLayers = {}; - Renderer.prototype._update.call(this); var b = this._bounds, @@ -11954,7 +12263,7 @@ var Canvas = Renderer.extend({ delete layer._order; - delete this._layers[L.stamp(layer)]; + delete this._layers[stamp(layer)]; this._requestRedraw(layer); }, @@ -11976,14 +12285,20 @@ var Canvas = Renderer.extend({ }, _updateDashArray: function (layer) { - if (layer.options.dashArray) { - var parts = layer.options.dashArray.split(','), + if (typeof layer.options.dashArray === 'string') { + var parts = layer.options.dashArray.split(/[, ]+/), dashArray = [], + dashValue, i; for (i = 0; i < parts.length; i++) { - dashArray.push(Number(parts[i])); + dashValue = Number(parts[i]); + // Ignore dash array containing invalid lengths + if (isNaN(dashValue)) { return; } + dashArray.push(dashValue); } layer.options._dashArray = dashArray; + } else { + layer.options._dashArray = layer.options.dashArray; } }, @@ -12061,8 +12376,6 @@ var Canvas = Renderer.extend({ if (!len) { return; } - this._drawnLayers[layer._leaflet_id] = layer; - ctx.beginPath(); for (i = 0; i < len; i++) { @@ -12089,8 +12402,6 @@ var Canvas = Renderer.extend({ r = Math.max(Math.round(layer._radius), 1), s = (Math.max(Math.round(layer._radiusY), 1) || r) / r; - this._drawnLayers[layer._leaflet_id] = layer; - if (s !== 1) { ctx.save(); ctx.scale(1, s); @@ -12161,10 +12472,15 @@ var Canvas = Renderer.extend({ removeClass(this._container, 'leaflet-interactive'); this._fireEvent([layer], e, 'mouseout'); this._hoveredLayer = null; + this._mouseHoverThrottled = false; } }, _handleMouseHover: function (e, point) { + if (this._mouseHoverThrottled) { + return; + } + var layer, candidateHoveredLayer; for (var order = this._drawFirst; order; order = order.next) { @@ -12187,6 +12503,11 @@ var Canvas = Renderer.extend({ if (this._hoveredLayer) { this._fireEvent([this._hoveredLayer], e); } + + this._mouseHoverThrottled = true; + setTimeout(L.bind(function () { + this._mouseHoverThrottled = false; + }, this), 32); }, _fireEvent: function (layers, e, type) { @@ -12195,6 +12516,9 @@ var Canvas = Renderer.extend({ _bringToFront: function (layer) { var order = layer._order; + + if (!order) { return; } + var next = order.next; var prev = order.prev; @@ -12223,6 +12547,9 @@ var Canvas = Renderer.extend({ _bringToBack: function (layer) { var order = layer._order; + + if (!order) { return; } + var next = order.next; var prev = order.prev; @@ -12278,7 +12605,6 @@ var vmlCreate = (function () { /* * @class SVG * - * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case. * * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility * with old versions of Internet Explorer. @@ -12457,6 +12783,7 @@ var SVG = Renderer.extend({ off(this._container); delete this._container; delete this._rootGroup; + delete this._svgSize; }, _onZoomStart: function () { @@ -12619,10 +12946,7 @@ Map.include({ var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer; if (!renderer) { - // @namespace Map; @option preferCanvas: Boolean = false - // Whether `Path`s should be rendered on a `Canvas` renderer. - // By default, all `Path`s are rendered in a `SVG` renderer. - renderer = this._renderer = (this.options.preferCanvas && canvas$1()) || svg$1(); + renderer = this._renderer = this._createRenderer(); } if (!this.hasLayer(renderer)) { @@ -12638,10 +12962,17 @@ Map.include({ var renderer = this._paneRenderers[name]; if (renderer === undefined) { - renderer = (SVG && svg$1({pane: name})) || (Canvas && canvas$1({pane: name})); + renderer = this._createRenderer({pane: name}); this._paneRenderers[name] = renderer; } return renderer; + }, + + _createRenderer: function (options) { + // @namespace Map; @option preferCanvas: Boolean = false + // Whether `Path`s should be rendered on a `Canvas` renderer. + // By default, all `Path`s are rendered in a `SVG` renderer. + return (this.options.preferCanvas && canvas$1(options)) || svg$1(options); } }); @@ -13276,20 +13607,18 @@ var Keyboard = Handler.extend({ offset; if (key in this._panKeys) { + if (!map._panAnim || !map._panAnim._inProgress) { + offset = this._panKeys[key]; + if (e.shiftKey) { + offset = toPoint(offset).multiplyBy(3); + } - if (map._panAnim && map._panAnim._inProgress) { return; } + map.panBy(offset); - offset = this._panKeys[key]; - if (e.shiftKey) { - offset = toPoint(offset).multiplyBy(3); + if (map.options.maxBounds) { + map.panInsideBounds(map.options.maxBounds); + } } - - map.panBy(offset); - - if (map.options.maxBounds) { - map.panInsideBounds(map.options.maxBounds); - } - } else if (key in this._zoomKeys) { map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]); @@ -13611,7 +13940,7 @@ var TouchZoom = Handler.extend({ } if (!this._moved) { - map._moveStart(true); + map._moveStart(true, false); this._moved = true; } @@ -13657,21 +13986,9 @@ Map.ScrollWheelZoom = ScrollWheelZoom; Map.Tap = Tap; Map.TouchZoom = TouchZoom; -// misc - -var oldL = window.L; -function noConflict() { - window.L = oldL; - return this; -} - -// Always export us to window global (see #2364) -window.L = exports; - Object.freeze = freeze; exports.version = version; -exports.noConflict = noConflict; exports.Control = Control; exports.control = control; exports.Browser = Browser; @@ -13714,6 +14031,8 @@ exports.ImageOverlay = ImageOverlay; exports.imageOverlay = imageOverlay; exports.VideoOverlay = VideoOverlay; exports.videoOverlay = videoOverlay; +exports.SVGOverlay = SVGOverlay; +exports.svgOverlay = svgOverlay; exports.DivOverlay = DivOverlay; exports.Popup = Popup; exports.popup = popup; @@ -13748,5 +14067,14 @@ exports.rectangle = rectangle; exports.Map = Map; exports.map = createMap; +var oldL = window.L; +exports.noConflict = function() { + window.L = oldL; + return this; +} + +// Always export us to window global (see #2364) +window.L = exports; + }))); //# sourceMappingURL=leaflet-src.js.map