From 993a7b9c80a51c93c7a70c2cb611bb8edf29c630 Mon Sep 17 00:00:00 2001 From: Philipp Spitzer Date: Sun, 19 Nov 2023 17:09:03 +0100 Subject: [PATCH] Add files generated with "npm run build". --- .gitignore | 1 - dist/style.css | 407 + dist/wrmap.mjs | 31193 +++++++++++++++++++++++++++++++++++++++++++ dist/wrmap.mjs.map | 1 + 4 files changed, 31601 insertions(+), 1 deletion(-) create mode 100644 dist/style.css create mode 100644 dist/wrmap.mjs create mode 100644 dist/wrmap.mjs.map diff --git a/.gitignore b/.gitignore index 3d2bc62..2ccbe46 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ -/dist/ /node_modules/ diff --git a/dist/style.css b/dist/style.css new file mode 100644 index 0000000..5a5d746 --- /dev/null +++ b/dist/style.css @@ -0,0 +1,407 @@ +:root, +:host { + --ol-background-color: white; + --ol-accent-background-color: #F5F5F5; + --ol-subtle-background-color: rgba(128, 128, 128, 0.25); + --ol-partial-background-color: rgba(255, 255, 255, 0.75); + --ol-foreground-color: #333333; + --ol-subtle-foreground-color: #666666; + --ol-brand-color: #00AAFF; +} + +.ol-box { + box-sizing: border-box; + border-radius: 2px; + border: 1.5px solid var(--ol-background-color); + background-color: var(--ol-partial-background-color); +} + +.ol-mouse-position { + top: 8px; + right: 8px; + position: absolute; +} + +.ol-scale-line { + background: var(--ol-partial-background-color); + border-radius: 4px; + bottom: 8px; + left: 8px; + padding: 2px; + position: absolute; +} + +.ol-scale-line-inner { + border: 1px solid var(--ol-subtle-foreground-color); + border-top: none; + color: var(--ol-foreground-color); + font-size: 10px; + text-align: center; + margin: 1px; + will-change: contents, width; + transition: all 0.25s; +} + +.ol-scale-bar { + position: absolute; + bottom: 8px; + left: 8px; +} + +.ol-scale-bar-inner { + display: flex; +} + +.ol-scale-step-marker { + width: 1px; + height: 15px; + background-color: var(--ol-foreground-color); + float: right; + z-index: 10; +} + +.ol-scale-step-text { + position: absolute; + bottom: -5px; + font-size: 10px; + z-index: 11; + color: var(--ol-foreground-color); + text-shadow: -1.5px 0 var(--ol-partial-background-color), 0 1.5px var(--ol-partial-background-color), 1.5px 0 var(--ol-partial-background-color), 0 -1.5px var(--ol-partial-background-color); +} + +.ol-scale-text { + position: absolute; + font-size: 12px; + text-align: center; + bottom: 25px; + color: var(--ol-foreground-color); + text-shadow: -1.5px 0 var(--ol-partial-background-color), 0 1.5px var(--ol-partial-background-color), 1.5px 0 var(--ol-partial-background-color), 0 -1.5px var(--ol-partial-background-color); +} + +.ol-scale-singlebar { + position: relative; + height: 10px; + z-index: 9; + box-sizing: border-box; + border: 1px solid var(--ol-foreground-color); +} + +.ol-scale-singlebar-even { + background-color: var(--ol-subtle-foreground-color); +} + +.ol-scale-singlebar-odd { + background-color: var(--ol-background-color); +} + +.ol-unsupported { + display: none; +} + +.ol-viewport, +.ol-unselectable { + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + -webkit-tap-highlight-color: transparent; +} + +.ol-viewport canvas { + all: unset; + overflow: hidden; +} + +.ol-viewport { + touch-action: none; +} + +.ol-selectable { + -webkit-touch-callout: default; + -webkit-user-select: text; + -moz-user-select: text; + user-select: text; +} + +.ol-grabbing { + cursor: -webkit-grabbing; + cursor: -moz-grabbing; + cursor: grabbing; +} + +.ol-grab { + cursor: move; + cursor: -webkit-grab; + cursor: -moz-grab; + cursor: grab; +} + +.ol-control { + position: absolute; + background-color: var(--ol-subtle-background-color); + border-radius: 4px; +} + +.ol-zoom { + top: .5em; + left: .5em; +} + +.ol-rotate { + top: .5em; + right: .5em; + transition: opacity .25s linear, visibility 0s linear; +} + +.ol-rotate.ol-hidden { + opacity: 0; + visibility: hidden; + transition: opacity .25s linear, visibility 0s linear .25s; +} + +.ol-zoom-extent { + top: 4.643em; + left: .5em; +} + +.ol-full-screen { + right: .5em; + top: .5em; +} + +.ol-control button { + display: block; + margin: 1px; + padding: 0; + color: var(--ol-subtle-foreground-color); + font-weight: bold; + text-decoration: none; + font-size: inherit; + text-align: center; + height: 1.375em; + width: 1.375em; + line-height: .4em; + background-color: var(--ol-background-color); + border: none; + border-radius: 2px; +} + +.ol-control button::-moz-focus-inner { + border: none; + padding: 0; +} + +.ol-zoom-extent button { + line-height: 1.4em; +} + +.ol-compass { + display: block; + font-weight: normal; + will-change: transform; +} + +.ol-touch .ol-control button { + font-size: 1.5em; +} + +.ol-touch .ol-zoom-extent { + top: 5.5em; +} + +.ol-control button:hover, +.ol-control button:focus { + text-decoration: none; + outline: 1px solid var(--ol-subtle-foreground-color); + color: var(--ol-foreground-color); +} + +.ol-zoom .ol-zoom-in { + border-radius: 2px 2px 0 0; +} + +.ol-zoom .ol-zoom-out { + border-radius: 0 0 2px 2px; +} + +.ol-attribution { + text-align: right; + bottom: .5em; + right: .5em; + max-width: calc(100% - 1.3em); + display: flex; + flex-flow: row-reverse; + align-items: center; +} + +.ol-attribution a { + color: var(--ol-subtle-foreground-color); + text-decoration: none; +} + +.ol-attribution ul { + margin: 0; + padding: 1px .5em; + color: var(--ol-foreground-color); + text-shadow: 0 0 2px var(--ol-background-color); + font-size: 12px; +} + +.ol-attribution li { + display: inline; + list-style: none; +} + +.ol-attribution li:not(:last-child):after { + content: " "; +} + +.ol-attribution img { + max-height: 2em; + max-width: inherit; + vertical-align: middle; +} + +.ol-attribution button { + flex-shrink: 0; +} + +.ol-attribution.ol-collapsed ul { + display: none; +} + +.ol-attribution:not(.ol-collapsed) { + background: var(--ol-partial-background-color); +} + +.ol-attribution.ol-uncollapsible { + bottom: 0; + right: 0; + border-radius: 4px 0 0; +} + +.ol-attribution.ol-uncollapsible img { + margin-top: -.2em; + max-height: 1.6em; +} + +.ol-attribution.ol-uncollapsible button { + display: none; +} + +.ol-zoomslider { + top: 4.5em; + left: .5em; + height: 200px; +} + +.ol-zoomslider button { + position: relative; + height: 10px; +} + +.ol-touch .ol-zoomslider { + top: 5.5em; +} + +.ol-overviewmap { + left: 0.5em; + bottom: 0.5em; +} + +.ol-overviewmap.ol-uncollapsible { + bottom: 0; + left: 0; + border-radius: 0 4px 0 0; +} + +.ol-overviewmap .ol-overviewmap-map, +.ol-overviewmap button { + display: block; +} + +.ol-overviewmap .ol-overviewmap-map { + border: 1px solid var(--ol-subtle-foreground-color); + height: 150px; + width: 150px; +} + +.ol-overviewmap:not(.ol-collapsed) button { + bottom: 0; + left: 0; + position: absolute; +} + +.ol-overviewmap.ol-collapsed .ol-overviewmap-map, +.ol-overviewmap.ol-uncollapsible button { + display: none; +} + +.ol-overviewmap:not(.ol-collapsed) { + background: var(--ol-subtle-background-color); +} + +.ol-overviewmap-box { + border: 1.5px dotted var(--ol-subtle-foreground-color); +} + +.ol-overviewmap .ol-overviewmap-box:hover { + cursor: move; +} + +.ol-popup { + position: absolute; + background-color: white; + -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2)); + filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2)); + padding: 15px; + border-radius: 10px; + border: 1px solid #cccccc; + bottom: 12px; + left: -50px; + min-width: 250px; +} + +.ol-popup:after, .ol-popup:before { + top: 100%; + border: solid transparent; + content: " "; + height: 0; + width: 0; + position: absolute; + pointer-events: none; +} + +.ol-popup h2 { + margin-top: 0px; +} + +.ol-popup img { + min-height: 130px; +} + +.ol-popup:after { + border-top-color: white; + border-width: 10px; + left: 48px; + margin-left: -10px; +} + +.ol-popup:before { + border-top-color: #cccccc; + border-width: 11px; + left: 48px; + margin-left: -11px; +} + +.ol-popup-closer { + text-decoration: none; + position: absolute; + top: 2px; + right: 8px; +} + +.ol-popup-closer:after { + content: "✖"; +} + diff --git a/dist/wrmap.mjs b/dist/wrmap.mjs new file mode 100644 index 0000000..b9d2d69 --- /dev/null +++ b/dist/wrmap.mjs @@ -0,0 +1,31193 @@ +const wrmap = ""; +class BaseEvent { + /** + * @param {string} type Type. + */ + constructor(type) { + this.propagationStopped; + this.defaultPrevented; + this.type = type; + this.target = null; + } + /** + * Prevent default. This means that no emulated `click`, `singleclick` or `doubleclick` events + * will be fired. + * @api + */ + preventDefault() { + this.defaultPrevented = true; + } + /** + * Stop event propagation. + * @api + */ + stopPropagation() { + this.propagationStopped = true; + } +} +const Event = BaseEvent; +const ObjectEventType = { + /** + * Triggered when a property is changed. + * @event module:ol/Object.ObjectEvent#propertychange + * @api + */ + PROPERTYCHANGE: "propertychange" +}; +class Disposable { + constructor() { + this.disposed = false; + } + /** + * Clean up. + */ + dispose() { + if (!this.disposed) { + this.disposed = true; + this.disposeInternal(); + } + } + /** + * Extension point for disposable objects. + * @protected + */ + disposeInternal() { + } +} +const Disposable$1 = Disposable; +function binarySearch(haystack, needle, comparator) { + let mid, cmp; + comparator = comparator || ascending; + let low = 0; + let high = haystack.length; + let found = false; + while (low < high) { + mid = low + (high - low >> 1); + cmp = +comparator(haystack[mid], needle); + if (cmp < 0) { + low = mid + 1; + } else { + high = mid; + found = !cmp; + } + } + return found ? low : ~low; +} +function ascending(a, b) { + return a > b ? 1 : a < b ? -1 : 0; +} +function linearFindNearest(arr, target, direction) { + if (arr[0] <= target) { + return 0; + } + const n = arr.length; + if (target <= arr[n - 1]) { + return n - 1; + } + if (typeof direction === "function") { + for (let i = 1; i < n; ++i) { + const candidate = arr[i]; + if (candidate === target) { + return i; + } + if (candidate < target) { + if (direction(target, arr[i - 1], candidate) > 0) { + return i - 1; + } + return i; + } + } + return n - 1; + } + if (direction > 0) { + for (let i = 1; i < n; ++i) { + if (arr[i] < target) { + return i - 1; + } + } + return n - 1; + } + if (direction < 0) { + for (let i = 1; i < n; ++i) { + if (arr[i] <= target) { + return i; + } + } + return n - 1; + } + for (let i = 1; i < n; ++i) { + if (arr[i] == target) { + return i; + } + if (arr[i] < target) { + if (arr[i - 1] - target < target - arr[i]) { + return i - 1; + } + return i; + } + } + return n - 1; +} +function reverseSubArray(arr, begin, end) { + while (begin < end) { + const tmp = arr[begin]; + arr[begin] = arr[end]; + arr[end] = tmp; + ++begin; + --end; + } +} +function extend$2(arr, data) { + const extension = Array.isArray(data) ? data : [data]; + const length = extension.length; + for (let i = 0; i < length; i++) { + arr[arr.length] = extension[i]; + } +} +function equals$2(arr1, arr2) { + const len1 = arr1.length; + if (len1 !== arr2.length) { + return false; + } + for (let i = 0; i < len1; i++) { + if (arr1[i] !== arr2[i]) { + return false; + } + } + return true; +} +function isSorted(arr, func, strict) { + const compare = func || ascending; + return arr.every(function(currentVal, index) { + if (index === 0) { + return true; + } + const res = compare(arr[index - 1], currentVal); + return !(res > 0 || strict && res === 0); + }); +} +function TRUE() { + return true; +} +function FALSE() { + return false; +} +function VOID() { +} +function memoizeOne(fn) { + let called = false; + let lastResult; + let lastArgs; + let lastThis; + return function() { + const nextArgs = Array.prototype.slice.call(arguments); + if (!called || this !== lastThis || !equals$2(nextArgs, lastArgs)) { + called = true; + lastThis = this; + lastArgs = nextArgs; + lastResult = fn.apply(this, arguments); + } + return lastResult; + }; +} +function clear(object) { + for (const property in object) { + delete object[property]; + } +} +function isEmpty$1(object) { + let property; + for (property in object) { + return false; + } + return !property; +} +class Target extends Disposable$1 { + /** + * @param {*} [target] Default event target for dispatched events. + */ + constructor(target) { + super(); + this.eventTarget_ = target; + this.pendingRemovals_ = null; + this.dispatching_ = null; + this.listeners_ = null; + } + /** + * @param {string} type Type. + * @param {import("../events.js").Listener} listener Listener. + */ + addEventListener(type, listener) { + if (!type || !listener) { + return; + } + const listeners = this.listeners_ || (this.listeners_ = {}); + const listenersForType = listeners[type] || (listeners[type] = []); + if (!listenersForType.includes(listener)) { + listenersForType.push(listener); + } + } + /** + * Dispatches an event and calls all listeners listening for events + * of this type. The event parameter can either be a string or an + * Object with a `type` property. + * + * @param {import("./Event.js").default|string} event Event object. + * @return {boolean|undefined} `false` if anyone called preventDefault on the + * event object or if any of the listeners returned false. + * @api + */ + dispatchEvent(event) { + const isString = typeof event === "string"; + const type = isString ? event : event.type; + const listeners = this.listeners_ && this.listeners_[type]; + if (!listeners) { + return; + } + const evt = isString ? new Event(event) : ( + /** @type {Event} */ + event + ); + if (!evt.target) { + evt.target = this.eventTarget_ || this; + } + const dispatching = this.dispatching_ || (this.dispatching_ = {}); + const pendingRemovals = this.pendingRemovals_ || (this.pendingRemovals_ = {}); + if (!(type in dispatching)) { + dispatching[type] = 0; + pendingRemovals[type] = 0; + } + ++dispatching[type]; + let propagate; + for (let i = 0, ii = listeners.length; i < ii; ++i) { + if ("handleEvent" in listeners[i]) { + propagate = /** @type {import("../events.js").ListenerObject} */ + listeners[i].handleEvent(evt); + } else { + propagate = /** @type {import("../events.js").ListenerFunction} */ + listeners[i].call(this, evt); + } + if (propagate === false || evt.propagationStopped) { + propagate = false; + break; + } + } + if (--dispatching[type] === 0) { + let pr = pendingRemovals[type]; + delete pendingRemovals[type]; + while (pr--) { + this.removeEventListener(type, VOID); + } + delete dispatching[type]; + } + return propagate; + } + /** + * Clean up. + */ + disposeInternal() { + this.listeners_ && clear(this.listeners_); + } + /** + * Get the listeners for a specified event type. Listeners are returned in the + * order that they will be called in. + * + * @param {string} type Type. + * @return {Array|undefined} Listeners. + */ + getListeners(type) { + return this.listeners_ && this.listeners_[type] || void 0; + } + /** + * @param {string} [type] Type. If not provided, + * `true` will be returned if this event target has any listeners. + * @return {boolean} Has listeners. + */ + hasListener(type) { + if (!this.listeners_) { + return false; + } + return type ? type in this.listeners_ : Object.keys(this.listeners_).length > 0; + } + /** + * @param {string} type Type. + * @param {import("../events.js").Listener} listener Listener. + */ + removeEventListener(type, listener) { + const listeners = this.listeners_ && this.listeners_[type]; + if (listeners) { + const index = listeners.indexOf(listener); + if (index !== -1) { + if (this.pendingRemovals_ && type in this.pendingRemovals_) { + listeners[index] = VOID; + ++this.pendingRemovals_[type]; + } else { + listeners.splice(index, 1); + if (listeners.length === 0) { + delete this.listeners_[type]; + } + } + } + } + } +} +const EventTarget = Target; +const EventType = { + /** + * Generic change event. Triggered when the revision counter is increased. + * @event module:ol/events/Event~BaseEvent#change + * @api + */ + CHANGE: "change", + /** + * Generic error event. Triggered when an error occurs. + * @event module:ol/events/Event~BaseEvent#error + * @api + */ + ERROR: "error", + BLUR: "blur", + CLEAR: "clear", + CONTEXTMENU: "contextmenu", + CLICK: "click", + DBLCLICK: "dblclick", + DRAGENTER: "dragenter", + DRAGOVER: "dragover", + DROP: "drop", + FOCUS: "focus", + KEYDOWN: "keydown", + KEYPRESS: "keypress", + LOAD: "load", + RESIZE: "resize", + TOUCHMOVE: "touchmove", + WHEEL: "wheel" +}; +function listen(target, type, listener, thisArg, once) { + if (thisArg && thisArg !== target) { + listener = listener.bind(thisArg); + } + if (once) { + const originalListener = listener; + listener = function() { + target.removeEventListener(type, listener); + originalListener.apply(this, arguments); + }; + } + const eventsKey = { + target, + type, + listener + }; + target.addEventListener(type, listener); + return eventsKey; +} +function listenOnce(target, type, listener, thisArg) { + return listen(target, type, listener, thisArg, true); +} +function unlistenByKey(key) { + if (key && key.target) { + key.target.removeEventListener(key.type, key.listener); + clear(key); + } +} +class Observable extends EventTarget { + constructor() { + super(); + this.on = /** @type {ObservableOnSignature} */ + this.onInternal; + this.once = /** @type {ObservableOnSignature} */ + this.onceInternal; + this.un = /** @type {ObservableOnSignature} */ + this.unInternal; + this.revision_ = 0; + } + /** + * Increases the revision counter and dispatches a 'change' event. + * @api + */ + changed() { + ++this.revision_; + this.dispatchEvent(EventType.CHANGE); + } + /** + * Get the version number for this object. Each time the object is modified, + * its version number will be incremented. + * @return {number} Revision. + * @api + */ + getRevision() { + return this.revision_; + } + /** + * @param {string|Array} type Type. + * @param {function((Event|import("./events/Event").default)): ?} listener Listener. + * @return {import("./events.js").EventsKey|Array} Event key. + * @protected + */ + onInternal(type, listener) { + if (Array.isArray(type)) { + const len = type.length; + const keys = new Array(len); + for (let i = 0; i < len; ++i) { + keys[i] = listen(this, type[i], listener); + } + return keys; + } + return listen( + this, + /** @type {string} */ + type, + listener + ); + } + /** + * @param {string|Array} type Type. + * @param {function((Event|import("./events/Event").default)): ?} listener Listener. + * @return {import("./events.js").EventsKey|Array} Event key. + * @protected + */ + onceInternal(type, listener) { + let key; + if (Array.isArray(type)) { + const len = type.length; + key = new Array(len); + for (let i = 0; i < len; ++i) { + key[i] = listenOnce(this, type[i], listener); + } + } else { + key = listenOnce( + this, + /** @type {string} */ + type, + listener + ); + } + listener.ol_key = key; + return key; + } + /** + * Unlisten for a certain type of event. + * @param {string|Array} type Type. + * @param {function((Event|import("./events/Event").default)): ?} listener Listener. + * @protected + */ + unInternal(type, listener) { + const key = ( + /** @type {Object} */ + listener.ol_key + ); + if (key) { + unByKey(key); + } else if (Array.isArray(type)) { + for (let i = 0, ii = type.length; i < ii; ++i) { + this.removeEventListener(type[i], listener); + } + } else { + this.removeEventListener(type, listener); + } + } +} +Observable.prototype.on; +Observable.prototype.once; +Observable.prototype.un; +function unByKey(key) { + if (Array.isArray(key)) { + for (let i = 0, ii = key.length; i < ii; ++i) { + unlistenByKey(key[i]); + } + } else { + unlistenByKey( + /** @type {import("./events.js").EventsKey} */ + key + ); + } +} +const Observable$1 = Observable; +function abstract() { + throw new Error("Unimplemented abstract method."); +} +let uidCounter_ = 0; +function getUid(obj) { + return obj.ol_uid || (obj.ol_uid = String(++uidCounter_)); +} +class ObjectEvent extends Event { + /** + * @param {string} type The event type. + * @param {string} key The property name. + * @param {*} oldValue The old value for `key`. + */ + constructor(type, key, oldValue) { + super(type); + this.key = key; + this.oldValue = oldValue; + } +} +class BaseObject extends Observable$1 { + /** + * @param {Object} [values] An object with key-value pairs. + */ + constructor(values) { + super(); + this.on; + this.once; + this.un; + getUid(this); + this.values_ = null; + if (values !== void 0) { + this.setProperties(values); + } + } + /** + * Gets a value. + * @param {string} key Key name. + * @return {*} Value. + * @api + */ + get(key) { + let value; + if (this.values_ && this.values_.hasOwnProperty(key)) { + value = this.values_[key]; + } + return value; + } + /** + * Get a list of object property names. + * @return {Array} List of property names. + * @api + */ + getKeys() { + return this.values_ && Object.keys(this.values_) || []; + } + /** + * Get an object of all property names and values. + * @return {Object} Object. + * @api + */ + getProperties() { + return this.values_ && Object.assign({}, this.values_) || {}; + } + /** + * Get an object of all property names and values. + * @return {Object?} Object. + */ + getPropertiesInternal() { + return this.values_; + } + /** + * @return {boolean} The object has properties. + */ + hasProperties() { + return !!this.values_; + } + /** + * @param {string} key Key name. + * @param {*} oldValue Old value. + */ + notify(key, oldValue) { + let eventType; + eventType = `change:${key}`; + if (this.hasListener(eventType)) { + this.dispatchEvent(new ObjectEvent(eventType, key, oldValue)); + } + eventType = ObjectEventType.PROPERTYCHANGE; + if (this.hasListener(eventType)) { + this.dispatchEvent(new ObjectEvent(eventType, key, oldValue)); + } + } + /** + * @param {string} key Key name. + * @param {import("./events.js").Listener} listener Listener. + */ + addChangeListener(key, listener) { + this.addEventListener(`change:${key}`, listener); + } + /** + * @param {string} key Key name. + * @param {import("./events.js").Listener} listener Listener. + */ + removeChangeListener(key, listener) { + this.removeEventListener(`change:${key}`, listener); + } + /** + * Sets a value. + * @param {string} key Key name. + * @param {*} value Value. + * @param {boolean} [silent] Update without triggering an event. + * @api + */ + set(key, value, silent) { + const values = this.values_ || (this.values_ = {}); + if (silent) { + values[key] = value; + } else { + const oldValue = values[key]; + values[key] = value; + if (oldValue !== value) { + this.notify(key, oldValue); + } + } + } + /** + * Sets a collection of key-value pairs. Note that this changes any existing + * properties and adds new ones (it does not remove any existing properties). + * @param {Object} values Values. + * @param {boolean} [silent] Update without triggering an event. + * @api + */ + setProperties(values, silent) { + for (const key in values) { + this.set(key, values[key], silent); + } + } + /** + * Apply any properties from another object without triggering events. + * @param {BaseObject} source The source object. + * @protected + */ + applyProperties(source) { + if (!source.values_) { + return; + } + Object.assign(this.values_ || (this.values_ = {}), source.values_); + } + /** + * Unsets a property. + * @param {string} key Key name. + * @param {boolean} [silent] Unset without triggering an event. + * @api + */ + unset(key, silent) { + if (this.values_ && key in this.values_) { + const oldValue = this.values_[key]; + delete this.values_[key]; + if (isEmpty$1(this.values_)) { + this.values_ = null; + } + if (!silent) { + this.notify(key, oldValue); + } + } + } +} +const BaseObject$1 = BaseObject; +const CollectionEventType = { + /** + * Triggered when an item is added to the collection. + * @event module:ol/Collection.CollectionEvent#add + * @api + */ + ADD: "add", + /** + * Triggered when an item is removed from the collection. + * @event module:ol/Collection.CollectionEvent#remove + * @api + */ + REMOVE: "remove" +}; +const Property$3 = { + LENGTH: "length" +}; +class CollectionEvent extends Event { + /** + * @param {import("./CollectionEventType.js").default} type Type. + * @param {T} element Element. + * @param {number} index The index of the added or removed element. + */ + constructor(type, element, index) { + super(type); + this.element = element; + this.index = index; + } +} +class Collection extends BaseObject$1 { + /** + * @param {Array} [array] Array. + * @param {Options} [options] Collection options. + */ + constructor(array, options) { + super(); + this.on; + this.once; + this.un; + options = options || {}; + this.unique_ = !!options.unique; + this.array_ = array ? array : []; + if (this.unique_) { + for (let i = 0, ii = this.array_.length; i < ii; ++i) { + this.assertUnique_(this.array_[i], i); + } + } + this.updateLength_(); + } + /** + * Remove all elements from the collection. + * @api + */ + clear() { + while (this.getLength() > 0) { + this.pop(); + } + } + /** + * Add elements to the collection. This pushes each item in the provided array + * to the end of the collection. + * @param {!Array} arr Array. + * @return {Collection} This collection. + * @api + */ + extend(arr) { + for (let i = 0, ii = arr.length; i < ii; ++i) { + this.push(arr[i]); + } + return this; + } + /** + * Iterate over each element, calling the provided callback. + * @param {function(T, number, Array): *} f The function to call + * for every element. This function takes 3 arguments (the element, the + * index and the array). The return value is ignored. + * @api + */ + forEach(f) { + const array = this.array_; + for (let i = 0, ii = array.length; i < ii; ++i) { + f(array[i], i, array); + } + } + /** + * Get a reference to the underlying Array object. Warning: if the array + * is mutated, no events will be dispatched by the collection, and the + * collection's "length" property won't be in sync with the actual length + * of the array. + * @return {!Array} Array. + * @api + */ + getArray() { + return this.array_; + } + /** + * Get the element at the provided index. + * @param {number} index Index. + * @return {T} Element. + * @api + */ + item(index) { + return this.array_[index]; + } + /** + * Get the length of this collection. + * @return {number} The length of the array. + * @observable + * @api + */ + getLength() { + return this.get(Property$3.LENGTH); + } + /** + * Insert an element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api + */ + insertAt(index, elem) { + if (index < 0 || index > this.getLength()) { + throw new Error("Index out of bounds: " + index); + } + if (this.unique_) { + this.assertUnique_(elem); + } + this.array_.splice(index, 0, elem); + this.updateLength_(); + this.dispatchEvent( + new CollectionEvent(CollectionEventType.ADD, elem, index) + ); + } + /** + * Remove the last element of the collection and return it. + * Return `undefined` if the collection is empty. + * @return {T|undefined} Element. + * @api + */ + pop() { + return this.removeAt(this.getLength() - 1); + } + /** + * Insert the provided element at the end of the collection. + * @param {T} elem Element. + * @return {number} New length of the collection. + * @api + */ + push(elem) { + if (this.unique_) { + this.assertUnique_(elem); + } + const n = this.getLength(); + this.insertAt(n, elem); + return this.getLength(); + } + /** + * Remove the first occurrence of an element from the collection. + * @param {T} elem Element. + * @return {T|undefined} The removed element or undefined if none found. + * @api + */ + remove(elem) { + const arr = this.array_; + for (let i = 0, ii = arr.length; i < ii; ++i) { + if (arr[i] === elem) { + return this.removeAt(i); + } + } + return void 0; + } + /** + * Remove the element at the provided index and return it. + * Return `undefined` if the collection does not contain this index. + * @param {number} index Index. + * @return {T|undefined} Value. + * @api + */ + removeAt(index) { + if (index < 0 || index >= this.getLength()) { + return void 0; + } + const prev = this.array_[index]; + this.array_.splice(index, 1); + this.updateLength_(); + this.dispatchEvent( + /** @type {CollectionEvent} */ + new CollectionEvent(CollectionEventType.REMOVE, prev, index) + ); + return prev; + } + /** + * Set the element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api + */ + setAt(index, elem) { + const n = this.getLength(); + if (index >= n) { + this.insertAt(index, elem); + return; + } + if (index < 0) { + throw new Error("Index out of bounds: " + index); + } + if (this.unique_) { + this.assertUnique_(elem, index); + } + const prev = this.array_[index]; + this.array_[index] = elem; + this.dispatchEvent( + /** @type {CollectionEvent} */ + new CollectionEvent(CollectionEventType.REMOVE, prev, index) + ); + this.dispatchEvent( + /** @type {CollectionEvent} */ + new CollectionEvent(CollectionEventType.ADD, elem, index) + ); + } + /** + * @private + */ + updateLength_() { + this.set(Property$3.LENGTH, this.array_.length); + } + /** + * @private + * @param {T} elem Element. + * @param {number} [except] Optional index to ignore. + */ + assertUnique_(elem, except) { + for (let i = 0, ii = this.array_.length; i < ii; ++i) { + if (this.array_[i] === elem && i !== except) { + throw new Error("Duplicate item added to a unique collection"); + } + } + } +} +const Collection$1 = Collection; +const ua = typeof navigator !== "undefined" && typeof navigator.userAgent !== "undefined" ? navigator.userAgent.toLowerCase() : ""; +const FIREFOX = ua.includes("firefox"); +const SAFARI = ua.includes("safari") && !ua.includes("chrom"); +SAFARI && (ua.includes("version/15.4") || /cpu (os|iphone os) 15_4 like mac os x/.test(ua)); +const WEBKIT = ua.includes("webkit") && !ua.includes("edge"); +const MAC = ua.includes("macintosh"); +const DEVICE_PIXEL_RATIO = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1; +const WORKER_OFFSCREEN_CANVAS = typeof WorkerGlobalScope !== "undefined" && typeof OffscreenCanvas !== "undefined" && self instanceof WorkerGlobalScope; +const IMAGE_DECODE = typeof Image !== "undefined" && Image.prototype.decode; +const PASSIVE_EVENT_LISTENERS = function() { + let passive = false; + try { + const options = Object.defineProperty({}, "passive", { + get: function() { + passive = true; + } + }); + window.addEventListener("_", null, options); + window.removeEventListener("_", null, options); + } catch (error) { + } + return passive; +}(); +function assert(assertion, errorMessage) { + if (!assertion) { + throw new Error(errorMessage); + } +} +new Array(6); +function create() { + return [1, 0, 0, 1, 0, 0]; +} +function set(transform2, a, b, c, d, e, f) { + transform2[0] = a; + transform2[1] = b; + transform2[2] = c; + transform2[3] = d; + transform2[4] = e; + transform2[5] = f; + return transform2; +} +function setFromArray(transform1, transform2) { + transform1[0] = transform2[0]; + transform1[1] = transform2[1]; + transform1[2] = transform2[2]; + transform1[3] = transform2[3]; + transform1[4] = transform2[4]; + transform1[5] = transform2[5]; + return transform1; +} +function apply(transform2, coordinate) { + const x = coordinate[0]; + const y = coordinate[1]; + coordinate[0] = transform2[0] * x + transform2[2] * y + transform2[4]; + coordinate[1] = transform2[1] * x + transform2[3] * y + transform2[5]; + return coordinate; +} +function makeScale(target, x, y) { + return set(target, x, 0, 0, y, 0, 0); +} +function compose(transform2, dx1, dy1, sx, sy, angle, dx2, dy2) { + const sin = Math.sin(angle); + const cos = Math.cos(angle); + transform2[0] = sx * cos; + transform2[1] = sy * sin; + transform2[2] = -sx * sin; + transform2[3] = sy * cos; + transform2[4] = dx2 * sx * cos - dy2 * sx * sin + dx1; + transform2[5] = dx2 * sy * sin + dy2 * sy * cos + dy1; + return transform2; +} +function makeInverse(target, source) { + const det = determinant(source); + assert(det !== 0, "Transformation matrix cannot be inverted"); + const a = source[0]; + const b = source[1]; + const c = source[2]; + const d = source[3]; + const e = source[4]; + const f = source[5]; + target[0] = d / det; + target[1] = -b / det; + target[2] = -c / det; + target[3] = a / det; + target[4] = (c * f - d * e) / det; + target[5] = -(a * f - b * e) / det; + return target; +} +function determinant(mat) { + return mat[0] * mat[3] - mat[1] * mat[2]; +} +let transformStringDiv; +function toString$1(mat) { + const transformString = "matrix(" + mat.join(", ") + ")"; + if (WORKER_OFFSCREEN_CANVAS) { + return transformString; + } + const node = transformStringDiv || (transformStringDiv = document.createElement("div")); + node.style.transform = transformString; + return node.style.transform; +} +const Relationship = { + UNKNOWN: 0, + INTERSECTING: 1, + ABOVE: 2, + RIGHT: 4, + BELOW: 8, + LEFT: 16 +}; +function boundingExtent(coordinates2) { + const extent = createEmpty(); + for (let i = 0, ii = coordinates2.length; i < ii; ++i) { + extendCoordinate(extent, coordinates2[i]); + } + return extent; +} +function _boundingExtentXYs(xs, ys, dest) { + const minX = Math.min.apply(null, xs); + const minY = Math.min.apply(null, ys); + const maxX = Math.max.apply(null, xs); + const maxY = Math.max.apply(null, ys); + return createOrUpdate$2(minX, minY, maxX, maxY, dest); +} +function buffer(extent, value, dest) { + if (dest) { + dest[0] = extent[0] - value; + dest[1] = extent[1] - value; + dest[2] = extent[2] + value; + dest[3] = extent[3] + value; + return dest; + } + return [ + extent[0] - value, + extent[1] - value, + extent[2] + value, + extent[3] + value + ]; +} +function clone(extent, dest) { + if (dest) { + dest[0] = extent[0]; + dest[1] = extent[1]; + dest[2] = extent[2]; + dest[3] = extent[3]; + return dest; + } + return extent.slice(); +} +function closestSquaredDistanceXY(extent, x, y) { + let dx, dy; + if (x < extent[0]) { + dx = extent[0] - x; + } else if (extent[2] < x) { + dx = x - extent[2]; + } else { + dx = 0; + } + if (y < extent[1]) { + dy = extent[1] - y; + } else if (extent[3] < y) { + dy = y - extent[3]; + } else { + dy = 0; + } + return dx * dx + dy * dy; +} +function containsCoordinate(extent, coordinate) { + return containsXY(extent, coordinate[0], coordinate[1]); +} +function containsExtent(extent1, extent2) { + return extent1[0] <= extent2[0] && extent2[2] <= extent1[2] && extent1[1] <= extent2[1] && extent2[3] <= extent1[3]; +} +function containsXY(extent, x, y) { + return extent[0] <= x && x <= extent[2] && extent[1] <= y && y <= extent[3]; +} +function coordinateRelationship(extent, coordinate) { + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const x = coordinate[0]; + const y = coordinate[1]; + let relationship = Relationship.UNKNOWN; + if (x < minX) { + relationship = relationship | Relationship.LEFT; + } else if (x > maxX) { + relationship = relationship | Relationship.RIGHT; + } + if (y < minY) { + relationship = relationship | Relationship.BELOW; + } else if (y > maxY) { + relationship = relationship | Relationship.ABOVE; + } + if (relationship === Relationship.UNKNOWN) { + relationship = Relationship.INTERSECTING; + } + return relationship; +} +function createEmpty() { + return [Infinity, Infinity, -Infinity, -Infinity]; +} +function createOrUpdate$2(minX, minY, maxX, maxY, dest) { + if (dest) { + dest[0] = minX; + dest[1] = minY; + dest[2] = maxX; + dest[3] = maxY; + return dest; + } + return [minX, minY, maxX, maxY]; +} +function createOrUpdateEmpty(dest) { + return createOrUpdate$2(Infinity, Infinity, -Infinity, -Infinity, dest); +} +function createOrUpdateFromCoordinate(coordinate, dest) { + const x = coordinate[0]; + const y = coordinate[1]; + return createOrUpdate$2(x, y, x, y, dest); +} +function createOrUpdateFromFlatCoordinates(flatCoordinates, offset, end, stride, dest) { + const extent = createOrUpdateEmpty(dest); + return extendFlatCoordinates(extent, flatCoordinates, offset, end, stride); +} +function equals$1(extent1, extent2) { + return extent1[0] == extent2[0] && extent1[2] == extent2[2] && extent1[1] == extent2[1] && extent1[3] == extent2[3]; +} +function extend$1(extent1, extent2) { + if (extent2[0] < extent1[0]) { + extent1[0] = extent2[0]; + } + if (extent2[2] > extent1[2]) { + extent1[2] = extent2[2]; + } + if (extent2[1] < extent1[1]) { + extent1[1] = extent2[1]; + } + if (extent2[3] > extent1[3]) { + extent1[3] = extent2[3]; + } + return extent1; +} +function extendCoordinate(extent, coordinate) { + if (coordinate[0] < extent[0]) { + extent[0] = coordinate[0]; + } + if (coordinate[0] > extent[2]) { + extent[2] = coordinate[0]; + } + if (coordinate[1] < extent[1]) { + extent[1] = coordinate[1]; + } + if (coordinate[1] > extent[3]) { + extent[3] = coordinate[1]; + } +} +function extendFlatCoordinates(extent, flatCoordinates, offset, end, stride) { + for (; offset < end; offset += stride) { + extendXY(extent, flatCoordinates[offset], flatCoordinates[offset + 1]); + } + return extent; +} +function extendXY(extent, x, y) { + extent[0] = Math.min(extent[0], x); + extent[1] = Math.min(extent[1], y); + extent[2] = Math.max(extent[2], x); + extent[3] = Math.max(extent[3], y); +} +function forEachCorner(extent, callback) { + let val; + val = callback(getBottomLeft(extent)); + if (val) { + return val; + } + val = callback(getBottomRight(extent)); + if (val) { + return val; + } + val = callback(getTopRight(extent)); + if (val) { + return val; + } + val = callback(getTopLeft(extent)); + if (val) { + return val; + } + return false; +} +function getArea(extent) { + let area = 0; + if (!isEmpty(extent)) { + area = getWidth(extent) * getHeight(extent); + } + return area; +} +function getBottomLeft(extent) { + return [extent[0], extent[1]]; +} +function getBottomRight(extent) { + return [extent[2], extent[1]]; +} +function getCenter(extent) { + return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2]; +} +function getCorner(extent, corner) { + let coordinate; + if (corner === "bottom-left") { + coordinate = getBottomLeft(extent); + } else if (corner === "bottom-right") { + coordinate = getBottomRight(extent); + } else if (corner === "top-left") { + coordinate = getTopLeft(extent); + } else if (corner === "top-right") { + coordinate = getTopRight(extent); + } else { + throw new Error("Invalid corner"); + } + return coordinate; +} +function getForViewAndSize(center, resolution, rotation, size, dest) { + const [x0, y0, x1, y1, x2, y2, x3, y3] = getRotatedViewport( + center, + resolution, + rotation, + size + ); + return createOrUpdate$2( + Math.min(x0, x1, x2, x3), + Math.min(y0, y1, y2, y3), + Math.max(x0, x1, x2, x3), + Math.max(y0, y1, y2, y3), + dest + ); +} +function getRotatedViewport(center, resolution, rotation, size) { + const dx = resolution * size[0] / 2; + const dy = resolution * size[1] / 2; + const cosRotation = Math.cos(rotation); + const sinRotation = Math.sin(rotation); + const xCos = dx * cosRotation; + const xSin = dx * sinRotation; + const yCos = dy * cosRotation; + const ySin = dy * sinRotation; + const x = center[0]; + const y = center[1]; + return [ + x - xCos + ySin, + y - xSin - yCos, + x - xCos - ySin, + y - xSin + yCos, + x + xCos - ySin, + y + xSin + yCos, + x + xCos + ySin, + y + xSin - yCos, + x - xCos + ySin, + y - xSin - yCos + ]; +} +function getHeight(extent) { + return extent[3] - extent[1]; +} +function getIntersection(extent1, extent2, dest) { + const intersection = dest ? dest : createEmpty(); + if (intersects$1(extent1, extent2)) { + if (extent1[0] > extent2[0]) { + intersection[0] = extent1[0]; + } else { + intersection[0] = extent2[0]; + } + if (extent1[1] > extent2[1]) { + intersection[1] = extent1[1]; + } else { + intersection[1] = extent2[1]; + } + if (extent1[2] < extent2[2]) { + intersection[2] = extent1[2]; + } else { + intersection[2] = extent2[2]; + } + if (extent1[3] < extent2[3]) { + intersection[3] = extent1[3]; + } else { + intersection[3] = extent2[3]; + } + } else { + createOrUpdateEmpty(intersection); + } + return intersection; +} +function getTopLeft(extent) { + return [extent[0], extent[3]]; +} +function getTopRight(extent) { + return [extent[2], extent[3]]; +} +function getWidth(extent) { + return extent[2] - extent[0]; +} +function intersects$1(extent1, extent2) { + return extent1[0] <= extent2[2] && extent1[2] >= extent2[0] && extent1[1] <= extent2[3] && extent1[3] >= extent2[1]; +} +function isEmpty(extent) { + return extent[2] < extent[0] || extent[3] < extent[1]; +} +function returnOrUpdate(extent, dest) { + if (dest) { + dest[0] = extent[0]; + dest[1] = extent[1]; + dest[2] = extent[2]; + dest[3] = extent[3]; + return dest; + } + return extent; +} +function intersectsSegment(extent, start, end) { + let intersects2 = false; + const startRel = coordinateRelationship(extent, start); + const endRel = coordinateRelationship(extent, end); + if (startRel === Relationship.INTERSECTING || endRel === Relationship.INTERSECTING) { + intersects2 = true; + } else { + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const startX = start[0]; + const startY = start[1]; + const endX = end[0]; + const endY = end[1]; + const slope = (endY - startY) / (endX - startX); + let x, y; + if (!!(endRel & Relationship.ABOVE) && !(startRel & Relationship.ABOVE)) { + x = endX - (endY - maxY) / slope; + intersects2 = x >= minX && x <= maxX; + } + if (!intersects2 && !!(endRel & Relationship.RIGHT) && !(startRel & Relationship.RIGHT)) { + y = endY - (endX - maxX) * slope; + intersects2 = y >= minY && y <= maxY; + } + if (!intersects2 && !!(endRel & Relationship.BELOW) && !(startRel & Relationship.BELOW)) { + x = endX - (endY - minY) / slope; + intersects2 = x >= minX && x <= maxX; + } + if (!intersects2 && !!(endRel & Relationship.LEFT) && !(startRel & Relationship.LEFT)) { + y = endY - (endX - minX) * slope; + intersects2 = y >= minY && y <= maxY; + } + } + return intersects2; +} +function applyTransform(extent, transformFn, dest, stops) { + if (isEmpty(extent)) { + return createOrUpdateEmpty(dest); + } + let coordinates2 = []; + if (stops > 1) { + const width = extent[2] - extent[0]; + const height = extent[3] - extent[1]; + for (let i = 0; i < stops; ++i) { + coordinates2.push( + extent[0] + width * i / stops, + extent[1], + extent[2], + extent[1] + height * i / stops, + extent[2] - width * i / stops, + extent[3], + extent[0], + extent[3] - height * i / stops + ); + } + } else { + coordinates2 = [ + extent[0], + extent[1], + extent[2], + extent[1], + extent[2], + extent[3], + extent[0], + extent[3] + ]; + } + transformFn(coordinates2, coordinates2, 2); + const xs = []; + const ys = []; + for (let i = 0, l = coordinates2.length; i < l; i += 2) { + xs.push(coordinates2[i]); + ys.push(coordinates2[i + 1]); + } + return _boundingExtentXYs(xs, ys, dest); +} +function wrapX$2(extent, projection) { + const projectionExtent = projection.getExtent(); + const center = getCenter(extent); + if (projection.canWrapX() && (center[0] < projectionExtent[0] || center[0] >= projectionExtent[2])) { + const worldWidth = getWidth(projectionExtent); + const worldsAway = Math.floor( + (center[0] - projectionExtent[0]) / worldWidth + ); + const offset = worldsAway * worldWidth; + extent[0] -= offset; + extent[2] -= offset; + } + return extent; +} +function wrapAndSliceX(extent, projection) { + if (projection.canWrapX()) { + const projectionExtent = projection.getExtent(); + if (!isFinite(extent[0]) || !isFinite(extent[2])) { + return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]]; + } + wrapX$2(extent, projection); + const worldWidth = getWidth(projectionExtent); + if (getWidth(extent) > worldWidth) { + return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]]; + } + if (extent[0] < projectionExtent[0]) { + return [ + [extent[0] + worldWidth, extent[1], projectionExtent[2], extent[3]], + [projectionExtent[0], extent[1], extent[2], extent[3]] + ]; + } + if (extent[2] > projectionExtent[2]) { + return [ + [extent[0], extent[1], projectionExtent[2], extent[3]], + [projectionExtent[0], extent[1], extent[2] - worldWidth, extent[3]] + ]; + } + } + return [extent]; +} +function clamp(value, min, max) { + return Math.min(Math.max(value, min), max); +} +function squaredSegmentDistance(x, y, x1, y1, x2, y2) { + const dx = x2 - x1; + const dy = y2 - y1; + if (dx !== 0 || dy !== 0) { + const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); + if (t > 1) { + x1 = x2; + y1 = y2; + } else if (t > 0) { + x1 += dx * t; + y1 += dy * t; + } + } + return squaredDistance(x, y, x1, y1); +} +function squaredDistance(x1, y1, x2, y2) { + const dx = x2 - x1; + const dy = y2 - y1; + return dx * dx + dy * dy; +} +function solveLinearSystem(mat) { + const n = mat.length; + for (let i = 0; i < n; i++) { + let maxRow = i; + let maxEl = Math.abs(mat[i][i]); + for (let r = i + 1; r < n; r++) { + const absValue = Math.abs(mat[r][i]); + if (absValue > maxEl) { + maxEl = absValue; + maxRow = r; + } + } + if (maxEl === 0) { + return null; + } + const tmp = mat[maxRow]; + mat[maxRow] = mat[i]; + mat[i] = tmp; + for (let j = i + 1; j < n; j++) { + const coef = -mat[j][i] / mat[i][i]; + for (let k = i; k < n + 1; k++) { + if (i == k) { + mat[j][k] = 0; + } else { + mat[j][k] += coef * mat[i][k]; + } + } + } + } + const x = new Array(n); + for (let l = n - 1; l >= 0; l--) { + x[l] = mat[l][n] / mat[l][l]; + for (let m = l - 1; m >= 0; m--) { + mat[m][n] -= mat[m][l] * x[l]; + } + } + return x; +} +function toRadians(angleInDegrees) { + return angleInDegrees * Math.PI / 180; +} +function modulo(a, b) { + const r = a % b; + return r * b < 0 ? r + b : r; +} +function lerp(a, b, x) { + return a + x * (b - a); +} +function toFixed(n, decimals) { + const factor = Math.pow(10, decimals); + return Math.round(n * factor) / factor; +} +function floor(n, decimals) { + return Math.floor(toFixed(n, decimals)); +} +function ceil(n, decimals) { + return Math.ceil(toFixed(n, decimals)); +} +const HEX_COLOR_RE_ = /^#([a-f0-9]{3}|[a-f0-9]{4}(?:[a-f0-9]{2}){0,2})$/i; +const NAMED_COLOR_RE_ = /^([a-z]*)$|^hsla?\(.*\)$/i; +function asString(color) { + if (typeof color === "string") { + return color; + } + return toString(color); +} +function fromNamed(color) { + const el = document.createElement("div"); + el.style.color = color; + if (el.style.color !== "") { + document.body.appendChild(el); + const rgb = getComputedStyle(el).color; + document.body.removeChild(el); + return rgb; + } + return ""; +} +const fromString = function() { + const MAX_CACHE_SIZE = 1024; + const cache2 = {}; + let cacheSize = 0; + return ( + /** + * @param {string} s String. + * @return {Color} Color. + */ + function(s) { + let color; + if (cache2.hasOwnProperty(s)) { + color = cache2[s]; + } else { + if (cacheSize >= MAX_CACHE_SIZE) { + let i = 0; + for (const key in cache2) { + if ((i++ & 3) === 0) { + delete cache2[key]; + --cacheSize; + } + } + } + color = fromStringInternal_(s); + cache2[s] = color; + ++cacheSize; + } + return color; + } + ); +}(); +function asArray(color) { + if (Array.isArray(color)) { + return color; + } + return fromString(color); +} +function fromStringInternal_(s) { + let r, g, b, a, color; + if (NAMED_COLOR_RE_.exec(s)) { + s = fromNamed(s); + } + if (HEX_COLOR_RE_.exec(s)) { + const n = s.length - 1; + let d; + if (n <= 4) { + d = 1; + } else { + d = 2; + } + const hasAlpha = n === 4 || n === 8; + r = parseInt(s.substr(1 + 0 * d, d), 16); + g = parseInt(s.substr(1 + 1 * d, d), 16); + b = parseInt(s.substr(1 + 2 * d, d), 16); + if (hasAlpha) { + a = parseInt(s.substr(1 + 3 * d, d), 16); + } else { + a = 255; + } + if (d == 1) { + r = (r << 4) + r; + g = (g << 4) + g; + b = (b << 4) + b; + if (hasAlpha) { + a = (a << 4) + a; + } + } + color = [r, g, b, a / 255]; + } else if (s.startsWith("rgba(")) { + color = s.slice(5, -1).split(",").map(Number); + normalize(color); + } else if (s.startsWith("rgb(")) { + color = s.slice(4, -1).split(",").map(Number); + color.push(1); + normalize(color); + } else { + throw new Error("Invalid color"); + } + return color; +} +function normalize(color) { + color[0] = clamp(color[0] + 0.5 | 0, 0, 255); + color[1] = clamp(color[1] + 0.5 | 0, 0, 255); + color[2] = clamp(color[2] + 0.5 | 0, 0, 255); + color[3] = clamp(color[3], 0, 1); + return color; +} +function toString(color) { + let r = color[0]; + if (r != (r | 0)) { + r = r + 0.5 | 0; + } + let g = color[1]; + if (g != (g | 0)) { + g = g + 0.5 | 0; + } + let b = color[2]; + if (b != (b | 0)) { + b = b + 0.5 | 0; + } + const a = color[3] === void 0 ? 1 : Math.round(color[3] * 100) / 100; + return "rgba(" + r + "," + g + "," + b + "," + a + ")"; +} +class IconImageCache { + constructor() { + this.cache_ = {}; + this.cacheSize_ = 0; + this.maxCacheSize_ = 32; + } + /** + * FIXME empty description for jsdoc + */ + clear() { + this.cache_ = {}; + this.cacheSize_ = 0; + } + /** + * @return {boolean} Can expire cache. + */ + canExpireCache() { + return this.cacheSize_ > this.maxCacheSize_; + } + /** + * FIXME empty description for jsdoc + */ + expire() { + if (this.canExpireCache()) { + let i = 0; + for (const key in this.cache_) { + const iconImage = this.cache_[key]; + if ((i++ & 3) === 0 && !iconImage.hasListener()) { + delete this.cache_[key]; + --this.cacheSize_; + } + } + } + } + /** + * @param {string} src Src. + * @param {?string} crossOrigin Cross origin. + * @param {import("../color.js").Color} color Color. + * @return {import("./IconImage.js").default} Icon image. + */ + get(src, crossOrigin, color) { + const key = getKey$1(src, crossOrigin, color); + return key in this.cache_ ? this.cache_[key] : null; + } + /** + * @param {string} src Src. + * @param {?string} crossOrigin Cross origin. + * @param {import("../color.js").Color} color Color. + * @param {import("./IconImage.js").default} iconImage Icon image. + */ + set(src, crossOrigin, color, iconImage) { + const key = getKey$1(src, crossOrigin, color); + this.cache_[key] = iconImage; + ++this.cacheSize_; + } + /** + * Set the cache size of the icon cache. Default is `32`. Change this value when + * your map uses more than 32 different icon images and you are not caching icon + * styles on the application level. + * @param {number} maxCacheSize Cache max size. + * @api + */ + setSize(maxCacheSize) { + this.maxCacheSize_ = maxCacheSize; + this.expire(); + } +} +function getKey$1(src, crossOrigin, color) { + const colorString = color ? asString(color) : "null"; + return crossOrigin + ":" + src + ":" + colorString; +} +const shared = new IconImageCache(); +const LayerProperty = { + OPACITY: "opacity", + VISIBLE: "visible", + EXTENT: "extent", + Z_INDEX: "zIndex", + MAX_RESOLUTION: "maxResolution", + MIN_RESOLUTION: "minResolution", + MAX_ZOOM: "maxZoom", + MIN_ZOOM: "minZoom", + SOURCE: "source", + MAP: "map" +}; +class BaseLayer extends BaseObject$1 { + /** + * @param {Options} options Layer options. + */ + constructor(options) { + super(); + this.on; + this.once; + this.un; + this.background_ = options.background; + const properties = Object.assign({}, options); + if (typeof options.properties === "object") { + delete properties.properties; + Object.assign(properties, options.properties); + } + properties[LayerProperty.OPACITY] = options.opacity !== void 0 ? options.opacity : 1; + assert( + typeof properties[LayerProperty.OPACITY] === "number", + "Layer opacity must be a number" + ); + properties[LayerProperty.VISIBLE] = options.visible !== void 0 ? options.visible : true; + properties[LayerProperty.Z_INDEX] = options.zIndex; + properties[LayerProperty.MAX_RESOLUTION] = options.maxResolution !== void 0 ? options.maxResolution : Infinity; + properties[LayerProperty.MIN_RESOLUTION] = options.minResolution !== void 0 ? options.minResolution : 0; + properties[LayerProperty.MIN_ZOOM] = options.minZoom !== void 0 ? options.minZoom : -Infinity; + properties[LayerProperty.MAX_ZOOM] = options.maxZoom !== void 0 ? options.maxZoom : Infinity; + this.className_ = properties.className !== void 0 ? properties.className : "ol-layer"; + delete properties.className; + this.setProperties(properties); + this.state_ = null; + } + /** + * Get the background for this layer. + * @return {BackgroundColor|false} Layer background. + */ + getBackground() { + return this.background_; + } + /** + * @return {string} CSS class name. + */ + getClassName() { + return this.className_; + } + /** + * This method is not meant to be called by layers or layer renderers because the state + * is incorrect if the layer is included in a layer group. + * + * @param {boolean} [managed] Layer is managed. + * @return {import("./Layer.js").State} Layer state. + */ + getLayerState(managed) { + const state = this.state_ || /** @type {?} */ + { + layer: this, + managed: managed === void 0 ? true : managed + }; + const zIndex = this.getZIndex(); + state.opacity = clamp(Math.round(this.getOpacity() * 100) / 100, 0, 1); + state.visible = this.getVisible(); + state.extent = this.getExtent(); + state.zIndex = zIndex === void 0 && !state.managed ? Infinity : zIndex; + state.maxResolution = this.getMaxResolution(); + state.minResolution = Math.max(this.getMinResolution(), 0); + state.minZoom = this.getMinZoom(); + state.maxZoom = this.getMaxZoom(); + this.state_ = state; + return state; + } + /** + * @abstract + * @param {Array} [array] Array of layers (to be + * modified in place). + * @return {Array} Array of layers. + */ + getLayersArray(array) { + return abstract(); + } + /** + * @abstract + * @param {Array} [states] Optional list of layer + * states (to be modified in place). + * @return {Array} List of layer states. + */ + getLayerStatesArray(states) { + return abstract(); + } + /** + * Return the {@link module:ol/extent~Extent extent} of the layer or `undefined` if it + * will be visible regardless of extent. + * @return {import("../extent.js").Extent|undefined} The layer extent. + * @observable + * @api + */ + getExtent() { + return ( + /** @type {import("../extent.js").Extent|undefined} */ + this.get(LayerProperty.EXTENT) + ); + } + /** + * Return the maximum resolution of the layer. Returns Infinity if + * the layer has no maximum resolution set. + * @return {number} The maximum resolution of the layer. + * @observable + * @api + */ + getMaxResolution() { + return ( + /** @type {number} */ + this.get(LayerProperty.MAX_RESOLUTION) + ); + } + /** + * Return the minimum resolution of the layer. Returns 0 if + * the layer has no minimum resolution set. + * @return {number} The minimum resolution of the layer. + * @observable + * @api + */ + getMinResolution() { + return ( + /** @type {number} */ + this.get(LayerProperty.MIN_RESOLUTION) + ); + } + /** + * Return the minimum zoom level of the layer. Returns -Infinity if + * the layer has no minimum zoom set. + * @return {number} The minimum zoom level of the layer. + * @observable + * @api + */ + getMinZoom() { + return ( + /** @type {number} */ + this.get(LayerProperty.MIN_ZOOM) + ); + } + /** + * Return the maximum zoom level of the layer. Returns Infinity if + * the layer has no maximum zoom set. + * @return {number} The maximum zoom level of the layer. + * @observable + * @api + */ + getMaxZoom() { + return ( + /** @type {number} */ + this.get(LayerProperty.MAX_ZOOM) + ); + } + /** + * Return the opacity of the layer (between 0 and 1). + * @return {number} The opacity of the layer. + * @observable + * @api + */ + getOpacity() { + return ( + /** @type {number} */ + this.get(LayerProperty.OPACITY) + ); + } + /** + * @abstract + * @return {import("../source/Source.js").State} Source state. + */ + getSourceState() { + return abstract(); + } + /** + * Return the value of this layer's `visible` property. To find out whether the layer + * is visible on a map, use `isVisible()` instead. + * @return {boolean} The value of the `visible` property of the layer. + * @observable + * @api + */ + getVisible() { + return ( + /** @type {boolean} */ + this.get(LayerProperty.VISIBLE) + ); + } + /** + * Return the Z-index of the layer, which is used to order layers before + * rendering. Returns undefined if the layer is unmanaged. + * @return {number|undefined} The Z-index of the layer. + * @observable + * @api + */ + getZIndex() { + return ( + /** @type {number|undefined} */ + this.get(LayerProperty.Z_INDEX) + ); + } + /** + * Sets the background color. + * @param {BackgroundColor} [background] Background color. + */ + setBackground(background) { + this.background_ = background; + this.changed(); + } + /** + * Set the extent at which the layer is visible. If `undefined`, the layer + * will be visible at all extents. + * @param {import("../extent.js").Extent|undefined} extent The extent of the layer. + * @observable + * @api + */ + setExtent(extent) { + this.set(LayerProperty.EXTENT, extent); + } + /** + * Set the maximum resolution at which the layer is visible. + * @param {number} maxResolution The maximum resolution of the layer. + * @observable + * @api + */ + setMaxResolution(maxResolution) { + this.set(LayerProperty.MAX_RESOLUTION, maxResolution); + } + /** + * Set the minimum resolution at which the layer is visible. + * @param {number} minResolution The minimum resolution of the layer. + * @observable + * @api + */ + setMinResolution(minResolution) { + this.set(LayerProperty.MIN_RESOLUTION, minResolution); + } + /** + * Set the maximum zoom (exclusive) at which the layer is visible. + * Note that the zoom levels for layer visibility are based on the + * view zoom level, which may be different from a tile source zoom level. + * @param {number} maxZoom The maximum zoom of the layer. + * @observable + * @api + */ + setMaxZoom(maxZoom) { + this.set(LayerProperty.MAX_ZOOM, maxZoom); + } + /** + * Set the minimum zoom (inclusive) at which the layer is visible. + * Note that the zoom levels for layer visibility are based on the + * view zoom level, which may be different from a tile source zoom level. + * @param {number} minZoom The minimum zoom of the layer. + * @observable + * @api + */ + setMinZoom(minZoom) { + this.set(LayerProperty.MIN_ZOOM, minZoom); + } + /** + * Set the opacity of the layer, allowed values range from 0 to 1. + * @param {number} opacity The opacity of the layer. + * @observable + * @api + */ + setOpacity(opacity) { + assert(typeof opacity === "number", "Layer opacity must be a number"); + this.set(LayerProperty.OPACITY, opacity); + } + /** + * Set the visibility of the layer (`true` or `false`). + * @param {boolean} visible The visibility of the layer. + * @observable + * @api + */ + setVisible(visible) { + this.set(LayerProperty.VISIBLE, visible); + } + /** + * Set Z-index of the layer, which is used to order layers before rendering. + * The default Z-index is 0. + * @param {number} zindex The z-index of the layer. + * @observable + * @api + */ + setZIndex(zindex) { + this.set(LayerProperty.Z_INDEX, zindex); + } + /** + * Clean up. + */ + disposeInternal() { + if (this.state_) { + this.state_.layer = null; + this.state_ = null; + } + super.disposeInternal(); + } +} +const BaseLayer$1 = BaseLayer; +const RenderEventType = { + /** + * Triggered before a layer is rendered. + * @event module:ol/render/Event~RenderEvent#prerender + * @api + */ + PRERENDER: "prerender", + /** + * Triggered after a layer is rendered. + * @event module:ol/render/Event~RenderEvent#postrender + * @api + */ + POSTRENDER: "postrender", + /** + * Triggered before layers are composed. When dispatched by the map, the event object will not have + * a `context` set. When dispatched by a layer, the event object will have a `context` set. Only + * WebGL layers currently dispatch this event. + * @event module:ol/render/Event~RenderEvent#precompose + * @api + */ + PRECOMPOSE: "precompose", + /** + * Triggered after layers are composed. When dispatched by the map, the event object will not have + * a `context` set. When dispatched by a layer, the event object will have a `context` set. Only + * WebGL layers currently dispatch this event. + * @event module:ol/render/Event~RenderEvent#postcompose + * @api + */ + POSTCOMPOSE: "postcompose", + /** + * Triggered when rendering is complete, i.e. all sources and tiles have + * finished loading for the current viewport, and all tiles are faded in. + * The event object will not have a `context` set. + * @event module:ol/render/Event~RenderEvent#rendercomplete + * @api + */ + RENDERCOMPLETE: "rendercomplete" +}; +const ViewHint = { + ANIMATING: 0, + INTERACTING: 1 +}; +const ViewProperty = { + CENTER: "center", + RESOLUTION: "resolution", + ROTATION: "rotation" +}; +const DEFAULT_MAX_ZOOM = 42; +const DEFAULT_TILE_SIZE = 256; +const METERS_PER_UNIT$1 = { + // use the radius of the Normal sphere + "radians": 6370997 / (2 * Math.PI), + "degrees": 2 * Math.PI * 6370997 / 360, + "ft": 0.3048, + "m": 1, + "us-ft": 1200 / 3937 +}; +class Projection { + /** + * @param {Options} options Projection options. + */ + constructor(options) { + this.code_ = options.code; + this.units_ = /** @type {import("./Units.js").Units} */ + options.units; + this.extent_ = options.extent !== void 0 ? options.extent : null; + this.worldExtent_ = options.worldExtent !== void 0 ? options.worldExtent : null; + this.axisOrientation_ = options.axisOrientation !== void 0 ? options.axisOrientation : "enu"; + this.global_ = options.global !== void 0 ? options.global : false; + this.canWrapX_ = !!(this.global_ && this.extent_); + this.getPointResolutionFunc_ = options.getPointResolution; + this.defaultTileGrid_ = null; + this.metersPerUnit_ = options.metersPerUnit; + } + /** + * @return {boolean} The projection is suitable for wrapping the x-axis + */ + canWrapX() { + return this.canWrapX_; + } + /** + * Get the code for this projection, e.g. 'EPSG:4326'. + * @return {string} Code. + * @api + */ + getCode() { + return this.code_; + } + /** + * Get the validity extent for this projection. + * @return {import("../extent.js").Extent} Extent. + * @api + */ + getExtent() { + return this.extent_; + } + /** + * Get the units of this projection. + * @return {import("./Units.js").Units} Units. + * @api + */ + getUnits() { + return this.units_; + } + /** + * Get the amount of meters per unit of this projection. If the projection is + * not configured with `metersPerUnit` or a units identifier, the return is + * `undefined`. + * @return {number|undefined} Meters. + * @api + */ + getMetersPerUnit() { + return this.metersPerUnit_ || METERS_PER_UNIT$1[this.units_]; + } + /** + * Get the world extent for this projection. + * @return {import("../extent.js").Extent} Extent. + * @api + */ + getWorldExtent() { + return this.worldExtent_; + } + /** + * Get the axis orientation of this projection. + * Example values are: + * enu - the default easting, northing, elevation. + * neu - northing, easting, up - useful for "lat/long" geographic coordinates, + * or south orientated transverse mercator. + * wnu - westing, northing, up - some planetary coordinate systems have + * "west positive" coordinate systems + * @return {string} Axis orientation. + * @api + */ + getAxisOrientation() { + return this.axisOrientation_; + } + /** + * Is this projection a global projection which spans the whole world? + * @return {boolean} Whether the projection is global. + * @api + */ + isGlobal() { + return this.global_; + } + /** + * Set if the projection is a global projection which spans the whole world + * @param {boolean} global Whether the projection is global. + * @api + */ + setGlobal(global) { + this.global_ = global; + this.canWrapX_ = !!(global && this.extent_); + } + /** + * @return {import("../tilegrid/TileGrid.js").default} The default tile grid. + */ + getDefaultTileGrid() { + return this.defaultTileGrid_; + } + /** + * @param {import("../tilegrid/TileGrid.js").default} tileGrid The default tile grid. + */ + setDefaultTileGrid(tileGrid) { + this.defaultTileGrid_ = tileGrid; + } + /** + * Set the validity extent for this projection. + * @param {import("../extent.js").Extent} extent Extent. + * @api + */ + setExtent(extent) { + this.extent_ = extent; + this.canWrapX_ = !!(this.global_ && extent); + } + /** + * Set the world extent for this projection. + * @param {import("../extent.js").Extent} worldExtent World extent + * [minlon, minlat, maxlon, maxlat]. + * @api + */ + setWorldExtent(worldExtent) { + this.worldExtent_ = worldExtent; + } + /** + * Set the getPointResolution function (see {@link module:ol/proj.getPointResolution} + * for this projection. + * @param {function(number, import("../coordinate.js").Coordinate):number} func Function + * @api + */ + setGetPointResolution(func) { + this.getPointResolutionFunc_ = func; + } + /** + * Get the custom point resolution function for this projection (if set). + * @return {function(number, import("../coordinate.js").Coordinate):number|undefined} The custom point + * resolution function (if set). + */ + getPointResolutionFunc() { + return this.getPointResolutionFunc_; + } +} +const Projection$1 = Projection; +const RADIUS$1 = 6378137; +const HALF_SIZE = Math.PI * RADIUS$1; +const EXTENT$1 = [-HALF_SIZE, -HALF_SIZE, HALF_SIZE, HALF_SIZE]; +const WORLD_EXTENT = [-180, -85, 180, 85]; +const MAX_SAFE_Y = RADIUS$1 * Math.log(Math.tan(Math.PI / 2)); +class EPSG3857Projection extends Projection$1 { + /** + * @param {string} code Code. + */ + constructor(code) { + super({ + code, + units: "m", + extent: EXTENT$1, + global: true, + worldExtent: WORLD_EXTENT, + getPointResolution: function(resolution, point) { + return resolution / Math.cosh(point[1] / RADIUS$1); + } + }); + } +} +const PROJECTIONS$1 = [ + new EPSG3857Projection("EPSG:3857"), + new EPSG3857Projection("EPSG:102100"), + new EPSG3857Projection("EPSG:102113"), + new EPSG3857Projection("EPSG:900913"), + new EPSG3857Projection("http://www.opengis.net/def/crs/EPSG/0/3857"), + new EPSG3857Projection("http://www.opengis.net/gml/srs/epsg.xml#3857") +]; +function fromEPSG4326(input, output, dimension) { + const length = input.length; + dimension = dimension > 1 ? dimension : 2; + if (output === void 0) { + if (dimension > 2) { + output = input.slice(); + } else { + output = new Array(length); + } + } + for (let i = 0; i < length; i += dimension) { + output[i] = HALF_SIZE * input[i] / 180; + let y = RADIUS$1 * Math.log(Math.tan(Math.PI * (+input[i + 1] + 90) / 360)); + if (y > MAX_SAFE_Y) { + y = MAX_SAFE_Y; + } else if (y < -MAX_SAFE_Y) { + y = -MAX_SAFE_Y; + } + output[i + 1] = y; + } + return output; +} +function toEPSG4326(input, output, dimension) { + const length = input.length; + dimension = dimension > 1 ? dimension : 2; + if (output === void 0) { + if (dimension > 2) { + output = input.slice(); + } else { + output = new Array(length); + } + } + for (let i = 0; i < length; i += dimension) { + output[i] = 180 * input[i] / HALF_SIZE; + output[i + 1] = 360 * Math.atan(Math.exp(input[i + 1] / RADIUS$1)) / Math.PI - 90; + } + return output; +} +const RADIUS = 6378137; +const EXTENT = [-180, -90, 180, 90]; +const METERS_PER_UNIT = Math.PI * RADIUS / 180; +class EPSG4326Projection extends Projection$1 { + /** + * @param {string} code Code. + * @param {string} [axisOrientation] Axis orientation. + */ + constructor(code, axisOrientation) { + super({ + code, + units: "degrees", + extent: EXTENT, + axisOrientation, + global: true, + metersPerUnit: METERS_PER_UNIT, + worldExtent: EXTENT + }); + } +} +const PROJECTIONS = [ + new EPSG4326Projection("CRS:84"), + new EPSG4326Projection("EPSG:4326", "neu"), + new EPSG4326Projection("urn:ogc:def:crs:OGC:1.3:CRS84"), + new EPSG4326Projection("urn:ogc:def:crs:OGC:2:84"), + new EPSG4326Projection("http://www.opengis.net/def/crs/OGC/1.3/CRS84"), + new EPSG4326Projection("http://www.opengis.net/gml/srs/epsg.xml#4326", "neu"), + new EPSG4326Projection("http://www.opengis.net/def/crs/EPSG/0/4326", "neu") +]; +let cache = {}; +function get$3(code) { + return cache[code] || cache[code.replace(/urn:(x-)?ogc:def:crs:EPSG:(.*:)?(\w+)$/, "EPSG:$3")] || null; +} +function add$2(code, projection) { + cache[code] = projection; +} +let transforms = {}; +function add$1(source, destination, transformFn) { + const sourceCode = source.getCode(); + const destinationCode = destination.getCode(); + if (!(sourceCode in transforms)) { + transforms[sourceCode] = {}; + } + transforms[sourceCode][destinationCode] = transformFn; +} +function get$2(sourceCode, destinationCode) { + let transform2; + if (sourceCode in transforms && destinationCode in transforms[sourceCode]) { + transform2 = transforms[sourceCode][destinationCode]; + } + return transform2; +} +function add(coordinate, delta) { + coordinate[0] += +delta[0]; + coordinate[1] += +delta[1]; + return coordinate; +} +function equals(coordinate1, coordinate2) { + let equals2 = true; + for (let i = coordinate1.length - 1; i >= 0; --i) { + if (coordinate1[i] != coordinate2[i]) { + equals2 = false; + break; + } + } + return equals2; +} +function rotate$1(coordinate, angle) { + const cosAngle = Math.cos(angle); + const sinAngle = Math.sin(angle); + const x = coordinate[0] * cosAngle - coordinate[1] * sinAngle; + const y = coordinate[1] * cosAngle + coordinate[0] * sinAngle; + coordinate[0] = x; + coordinate[1] = y; + return coordinate; +} +function scale$2(coordinate, scale2) { + coordinate[0] *= scale2; + coordinate[1] *= scale2; + return coordinate; +} +function wrapX$1(coordinate, projection) { + if (projection.canWrapX()) { + const worldWidth = getWidth(projection.getExtent()); + const worldsAway = getWorldsAway(coordinate, projection, worldWidth); + if (worldsAway) { + coordinate[0] -= worldsAway * worldWidth; + } + } + return coordinate; +} +function getWorldsAway(coordinate, projection, sourceExtentWidth) { + const projectionExtent = projection.getExtent(); + let worldsAway = 0; + if (projection.canWrapX() && (coordinate[0] < projectionExtent[0] || coordinate[0] > projectionExtent[2])) { + sourceExtentWidth = sourceExtentWidth || getWidth(projectionExtent); + worldsAway = Math.floor( + (coordinate[0] - projectionExtent[0]) / sourceExtentWidth + ); + } + return worldsAway; +} +const DEFAULT_RADIUS = 63710088e-1; +function getDistance(c1, c2, radius) { + radius = radius || DEFAULT_RADIUS; + const lat1 = toRadians(c1[1]); + const lat2 = toRadians(c2[1]); + const deltaLatBy2 = (lat2 - lat1) / 2; + const deltaLonBy2 = toRadians(c2[0] - c1[0]) / 2; + const a = Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) + Math.sin(deltaLonBy2) * Math.sin(deltaLonBy2) * Math.cos(lat1) * Math.cos(lat2); + return 2 * radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); +} +const levels = { + info: 1, + warn: 2, + error: 3, + none: 4 +}; +let level = levels.info; +function warn(...args) { + if (level > levels.warn) { + return; + } + console.warn(...args); +} +let showCoordinateWarning = true; +function disableCoordinateWarning(disable2) { + const hide = disable2 === void 0 ? true : disable2; + showCoordinateWarning = !hide; +} +function cloneTransform(input, output) { + if (output !== void 0) { + for (let i = 0, ii = input.length; i < ii; ++i) { + output[i] = input[i]; + } + output = output; + } else { + output = input.slice(); + } + return output; +} +function identityTransform(input, output) { + if (output !== void 0 && input !== output) { + for (let i = 0, ii = input.length; i < ii; ++i) { + output[i] = input[i]; + } + input = output; + } + return input; +} +function addProjection(projection) { + add$2(projection.getCode(), projection); + add$1(projection, projection, cloneTransform); +} +function addProjections(projections) { + projections.forEach(addProjection); +} +function get$1(projectionLike) { + return typeof projectionLike === "string" ? get$3( + /** @type {string} */ + projectionLike + ) : ( + /** @type {Projection} */ + projectionLike || null + ); +} +function getPointResolution(projection, resolution, point, units) { + projection = get$1(projection); + let pointResolution; + const getter = projection.getPointResolutionFunc(); + if (getter) { + pointResolution = getter(resolution, point); + if (units && units !== projection.getUnits()) { + const metersPerUnit = projection.getMetersPerUnit(); + if (metersPerUnit) { + pointResolution = pointResolution * metersPerUnit / METERS_PER_UNIT$1[units]; + } + } + } else { + const projUnits = projection.getUnits(); + if (projUnits == "degrees" && !units || units == "degrees") { + pointResolution = resolution; + } else { + const toEPSG43262 = getTransformFromProjections( + projection, + get$1("EPSG:4326") + ); + if (toEPSG43262 === identityTransform && projUnits !== "degrees") { + pointResolution = resolution * projection.getMetersPerUnit(); + } else { + let vertices = [ + point[0] - resolution / 2, + point[1], + point[0] + resolution / 2, + point[1], + point[0], + point[1] - resolution / 2, + point[0], + point[1] + resolution / 2 + ]; + vertices = toEPSG43262(vertices, vertices, 2); + const width = getDistance(vertices.slice(0, 2), vertices.slice(2, 4)); + const height = getDistance(vertices.slice(4, 6), vertices.slice(6, 8)); + pointResolution = (width + height) / 2; + } + const metersPerUnit = units ? METERS_PER_UNIT$1[units] : projection.getMetersPerUnit(); + if (metersPerUnit !== void 0) { + pointResolution /= metersPerUnit; + } + } + } + return pointResolution; +} +function addEquivalentProjections(projections) { + addProjections(projections); + projections.forEach(function(source) { + projections.forEach(function(destination) { + if (source !== destination) { + add$1(source, destination, cloneTransform); + } + }); + }); +} +function addEquivalentTransforms(projections1, projections2, forwardTransform, inverseTransform) { + projections1.forEach(function(projection1) { + projections2.forEach(function(projection2) { + add$1(projection1, projection2, forwardTransform); + add$1(projection2, projection1, inverseTransform); + }); + }); +} +function createProjection(projection, defaultCode) { + if (!projection) { + return get$1(defaultCode); + } + if (typeof projection === "string") { + return get$1(projection); + } + return ( + /** @type {Projection} */ + projection + ); +} +function fromLonLat(coordinate, projection) { + disableCoordinateWarning(); + return transform( + coordinate, + "EPSG:4326", + projection !== void 0 ? projection : "EPSG:3857" + ); +} +function equivalent(projection1, projection2) { + if (projection1 === projection2) { + return true; + } + const equalUnits = projection1.getUnits() === projection2.getUnits(); + if (projection1.getCode() === projection2.getCode()) { + return equalUnits; + } + const transformFunc = getTransformFromProjections(projection1, projection2); + return transformFunc === cloneTransform && equalUnits; +} +function getTransformFromProjections(sourceProjection, destinationProjection) { + const sourceCode = sourceProjection.getCode(); + const destinationCode = destinationProjection.getCode(); + let transformFunc = get$2(sourceCode, destinationCode); + if (!transformFunc) { + transformFunc = identityTransform; + } + return transformFunc; +} +function getTransform(source, destination) { + const sourceProjection = get$1(source); + const destinationProjection = get$1(destination); + return getTransformFromProjections(sourceProjection, destinationProjection); +} +function transform(coordinate, source, destination) { + const transformFunc = getTransform(source, destination); + return transformFunc(coordinate, void 0, coordinate.length); +} +function transformExtent(extent, source, destination, stops) { + const transformFunc = getTransform(source, destination); + return applyTransform(extent, transformFunc, void 0, stops); +} +function toUserCoordinate(coordinate, sourceProjection) { + { + return coordinate; + } +} +function fromUserCoordinate(coordinate, destProjection) { + { + if (showCoordinateWarning && !equals(coordinate, [0, 0]) && coordinate[0] >= -180 && coordinate[0] <= 180 && coordinate[1] >= -90 && coordinate[1] <= 90) { + showCoordinateWarning = false; + warn( + "Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates." + ); + } + return coordinate; + } +} +function toUserExtent(extent, sourceProjection) { + { + return extent; + } +} +function fromUserExtent(extent, destProjection) { + { + return extent; + } +} +function addCommon() { + addEquivalentProjections(PROJECTIONS$1); + addEquivalentProjections(PROJECTIONS); + addEquivalentTransforms( + PROJECTIONS, + PROJECTIONS$1, + fromEPSG4326, + toEPSG4326 + ); +} +addCommon(); +function createExtent(extent, onlyCenter, smooth) { + return ( + /** + * @param {import("./coordinate.js").Coordinate|undefined} center Center. + * @param {number|undefined} resolution Resolution. + * @param {import("./size.js").Size} size Viewport size; unused if `onlyCenter` was specified. + * @param {boolean} [isMoving] True if an interaction or animation is in progress. + * @param {Array} [centerShift] Shift between map center and viewport center. + * @return {import("./coordinate.js").Coordinate|undefined} Center. + */ + function(center, resolution, size, isMoving, centerShift) { + if (!center) { + return void 0; + } + if (!resolution && !onlyCenter) { + return center; + } + const viewWidth = onlyCenter ? 0 : size[0] * resolution; + const viewHeight = onlyCenter ? 0 : size[1] * resolution; + const shiftX = centerShift ? centerShift[0] : 0; + const shiftY = centerShift ? centerShift[1] : 0; + let minX = extent[0] + viewWidth / 2 + shiftX; + let maxX = extent[2] - viewWidth / 2 + shiftX; + let minY = extent[1] + viewHeight / 2 + shiftY; + let maxY = extent[3] - viewHeight / 2 + shiftY; + if (minX > maxX) { + minX = (maxX + minX) / 2; + maxX = minX; + } + if (minY > maxY) { + minY = (maxY + minY) / 2; + maxY = minY; + } + let x = clamp(center[0], minX, maxX); + let y = clamp(center[1], minY, maxY); + if (isMoving && smooth && resolution) { + const ratio = 30 * resolution; + x += -ratio * Math.log(1 + Math.max(0, minX - center[0]) / ratio) + ratio * Math.log(1 + Math.max(0, center[0] - maxX) / ratio); + y += -ratio * Math.log(1 + Math.max(0, minY - center[1]) / ratio) + ratio * Math.log(1 + Math.max(0, center[1] - maxY) / ratio); + } + return [x, y]; + } + ); +} +function none$1(center) { + return center; +} +function getViewportClampedResolution(resolution, maxExtent, viewportSize, showFullExtent) { + const xResolution = getWidth(maxExtent) / viewportSize[0]; + const yResolution = getHeight(maxExtent) / viewportSize[1]; + if (showFullExtent) { + return Math.min(resolution, Math.max(xResolution, yResolution)); + } + return Math.min(resolution, Math.min(xResolution, yResolution)); +} +function getSmoothClampedResolution(resolution, maxResolution, minResolution) { + let result = Math.min(resolution, maxResolution); + const ratio = 50; + result *= Math.log(1 + ratio * Math.max(0, resolution / maxResolution - 1)) / ratio + 1; + if (minResolution) { + result = Math.max(result, minResolution); + result /= Math.log(1 + ratio * Math.max(0, minResolution / resolution - 1)) / ratio + 1; + } + return clamp(result, minResolution / 2, maxResolution * 2); +} +function createSnapToResolutions(resolutions, smooth, maxExtent, showFullExtent) { + smooth = smooth !== void 0 ? smooth : true; + return ( + /** + * @param {number|undefined} resolution Resolution. + * @param {number} direction Direction. + * @param {import("./size.js").Size} size Viewport size. + * @param {boolean} [isMoving] True if an interaction or animation is in progress. + * @return {number|undefined} Resolution. + */ + function(resolution, direction, size, isMoving) { + if (resolution !== void 0) { + const maxResolution = resolutions[0]; + const minResolution = resolutions[resolutions.length - 1]; + const cappedMaxRes = maxExtent ? getViewportClampedResolution( + maxResolution, + maxExtent, + size, + showFullExtent + ) : maxResolution; + if (isMoving) { + if (!smooth) { + return clamp(resolution, minResolution, cappedMaxRes); + } + return getSmoothClampedResolution( + resolution, + cappedMaxRes, + minResolution + ); + } + const capped = Math.min(cappedMaxRes, resolution); + const z = Math.floor(linearFindNearest(resolutions, capped, direction)); + if (resolutions[z] > cappedMaxRes && z < resolutions.length - 1) { + return resolutions[z + 1]; + } + return resolutions[z]; + } + return void 0; + } + ); +} +function createSnapToPower(power, maxResolution, minResolution, smooth, maxExtent, showFullExtent) { + smooth = smooth !== void 0 ? smooth : true; + minResolution = minResolution !== void 0 ? minResolution : 0; + return ( + /** + * @param {number|undefined} resolution Resolution. + * @param {number} direction Direction. + * @param {import("./size.js").Size} size Viewport size. + * @param {boolean} [isMoving] True if an interaction or animation is in progress. + * @return {number|undefined} Resolution. + */ + function(resolution, direction, size, isMoving) { + if (resolution !== void 0) { + const cappedMaxRes = maxExtent ? getViewportClampedResolution( + maxResolution, + maxExtent, + size, + showFullExtent + ) : maxResolution; + if (isMoving) { + if (!smooth) { + return clamp(resolution, minResolution, cappedMaxRes); + } + return getSmoothClampedResolution( + resolution, + cappedMaxRes, + minResolution + ); + } + const tolerance = 1e-9; + const minZoomLevel = Math.ceil( + Math.log(maxResolution / cappedMaxRes) / Math.log(power) - tolerance + ); + const offset = -direction * (0.5 - tolerance) + 0.5; + const capped = Math.min(cappedMaxRes, resolution); + const cappedZoomLevel = Math.floor( + Math.log(maxResolution / capped) / Math.log(power) + offset + ); + const zoomLevel = Math.max(minZoomLevel, cappedZoomLevel); + const newResolution = maxResolution / Math.pow(power, zoomLevel); + return clamp(newResolution, minResolution, cappedMaxRes); + } + return void 0; + } + ); +} +function createMinMaxResolution(maxResolution, minResolution, smooth, maxExtent, showFullExtent) { + smooth = smooth !== void 0 ? smooth : true; + return ( + /** + * @param {number|undefined} resolution Resolution. + * @param {number} direction Direction. + * @param {import("./size.js").Size} size Viewport size. + * @param {boolean} [isMoving] True if an interaction or animation is in progress. + * @return {number|undefined} Resolution. + */ + function(resolution, direction, size, isMoving) { + if (resolution !== void 0) { + const cappedMaxRes = maxExtent ? getViewportClampedResolution( + maxResolution, + maxExtent, + size, + showFullExtent + ) : maxResolution; + if (!smooth || !isMoving) { + return clamp(resolution, minResolution, cappedMaxRes); + } + return getSmoothClampedResolution( + resolution, + cappedMaxRes, + minResolution + ); + } + return void 0; + } + ); +} +function disable(rotation) { + if (rotation !== void 0) { + return 0; + } + return void 0; +} +function none(rotation) { + if (rotation !== void 0) { + return rotation; + } + return void 0; +} +function createSnapToN(n) { + const theta = 2 * Math.PI / n; + return ( + /** + * @param {number|undefined} rotation Rotation. + * @param {boolean} [isMoving] True if an interaction or animation is in progress. + * @return {number|undefined} Rotation. + */ + function(rotation, isMoving) { + if (isMoving) { + return rotation; + } + if (rotation !== void 0) { + rotation = Math.floor(rotation / theta + 0.5) * theta; + return rotation; + } + return void 0; + } + ); +} +function createSnapToZero(tolerance) { + tolerance = tolerance || toRadians(5); + return ( + /** + * @param {number|undefined} rotation Rotation. + * @param {boolean} [isMoving] True if an interaction or animation is in progress. + * @return {number|undefined} Rotation. + */ + function(rotation, isMoving) { + if (isMoving) { + return rotation; + } + if (rotation !== void 0) { + if (Math.abs(rotation) <= tolerance) { + return 0; + } + return rotation; + } + return void 0; + } + ); +} +function easeIn(t) { + return Math.pow(t, 3); +} +function easeOut(t) { + return 1 - easeIn(1 - t); +} +function inAndOut(t) { + return 3 * t * t - 2 * t * t * t; +} +function linear(t) { + return t; +} +function transform2D(flatCoordinates, offset, end, stride, transform2, dest) { + dest = dest ? dest : []; + let i = 0; + for (let j = offset; j < end; j += stride) { + const x = flatCoordinates[j]; + const y = flatCoordinates[j + 1]; + dest[i++] = transform2[0] * x + transform2[2] * y + transform2[4]; + dest[i++] = transform2[1] * x + transform2[3] * y + transform2[5]; + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} +function rotate(flatCoordinates, offset, end, stride, angle, anchor, dest) { + dest = dest ? dest : []; + const cos = Math.cos(angle); + const sin = Math.sin(angle); + const anchorX = anchor[0]; + const anchorY = anchor[1]; + let i = 0; + for (let j = offset; j < end; j += stride) { + const deltaX = flatCoordinates[j] - anchorX; + const deltaY = flatCoordinates[j + 1] - anchorY; + dest[i++] = anchorX + deltaX * cos - deltaY * sin; + dest[i++] = anchorY + deltaX * sin + deltaY * cos; + for (let k = j + 2; k < j + stride; ++k) { + dest[i++] = flatCoordinates[k]; + } + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} +function scale$1(flatCoordinates, offset, end, stride, sx, sy, anchor, dest) { + dest = dest ? dest : []; + const anchorX = anchor[0]; + const anchorY = anchor[1]; + let i = 0; + for (let j = offset; j < end; j += stride) { + const deltaX = flatCoordinates[j] - anchorX; + const deltaY = flatCoordinates[j + 1] - anchorY; + dest[i++] = anchorX + sx * deltaX; + dest[i++] = anchorY + sy * deltaY; + for (let k = j + 2; k < j + stride; ++k) { + dest[i++] = flatCoordinates[k]; + } + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} +function translate(flatCoordinates, offset, end, stride, deltaX, deltaY, dest) { + dest = dest ? dest : []; + let i = 0; + for (let j = offset; j < end; j += stride) { + dest[i++] = flatCoordinates[j] + deltaX; + dest[i++] = flatCoordinates[j + 1] + deltaY; + for (let k = j + 2; k < j + stride; ++k) { + dest[i++] = flatCoordinates[k]; + } + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} +const tmpTransform = create(); +class Geometry extends BaseObject$1 { + constructor() { + super(); + this.extent_ = createEmpty(); + this.extentRevision_ = -1; + this.simplifiedGeometryMaxMinSquaredTolerance = 0; + this.simplifiedGeometryRevision = 0; + this.simplifyTransformedInternal = memoizeOne(function(revision, squaredTolerance, transform2) { + if (!transform2) { + return this.getSimplifiedGeometry(squaredTolerance); + } + const clone2 = this.clone(); + clone2.applyTransform(transform2); + return clone2.getSimplifiedGeometry(squaredTolerance); + }); + } + /** + * Get a transformed and simplified version of the geometry. + * @abstract + * @param {number} squaredTolerance Squared tolerance. + * @param {import("../proj.js").TransformFunction} [transform] Optional transform function. + * @return {Geometry} Simplified geometry. + */ + simplifyTransformed(squaredTolerance, transform2) { + return this.simplifyTransformedInternal( + this.getRevision(), + squaredTolerance, + transform2 + ); + } + /** + * Make a complete copy of the geometry. + * @abstract + * @return {!Geometry} Clone. + */ + clone() { + return abstract(); + } + /** + * @abstract + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + return abstract(); + } + /** + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ + containsXY(x, y) { + const coord = this.getClosestPoint([x, y]); + return coord[0] === x && coord[1] === y; + } + /** + * Return the closest point of the geometry to the passed point as + * {@link module:ol/coordinate~Coordinate coordinate}. + * @param {import("../coordinate.js").Coordinate} point Point. + * @param {import("../coordinate.js").Coordinate} [closestPoint] Closest point. + * @return {import("../coordinate.js").Coordinate} Closest point. + * @api + */ + getClosestPoint(point, closestPoint) { + closestPoint = closestPoint ? closestPoint : [NaN, NaN]; + this.closestPointXY(point[0], point[1], closestPoint, Infinity); + return closestPoint; + } + /** + * Returns true if this geometry includes the specified coordinate. If the + * coordinate is on the boundary of the geometry, returns false. + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @return {boolean} Contains coordinate. + * @api + */ + intersectsCoordinate(coordinate) { + return this.containsXY(coordinate[0], coordinate[1]); + } + /** + * @abstract + * @param {import("../extent.js").Extent} extent Extent. + * @protected + * @return {import("../extent.js").Extent} extent Extent. + */ + computeExtent(extent) { + return abstract(); + } + /** + * Get the extent of the geometry. + * @param {import("../extent.js").Extent} [extent] Extent. + * @return {import("../extent.js").Extent} extent Extent. + * @api + */ + getExtent(extent) { + if (this.extentRevision_ != this.getRevision()) { + const extent2 = this.computeExtent(this.extent_); + if (isNaN(extent2[0]) || isNaN(extent2[1])) { + createOrUpdateEmpty(extent2); + } + this.extentRevision_ = this.getRevision(); + } + return returnOrUpdate(this.extent_, extent); + } + /** + * Rotate the geometry around a given coordinate. This modifies the geometry + * coordinates in place. + * @abstract + * @param {number} angle Rotation angle in radians. + * @param {import("../coordinate.js").Coordinate} anchor The rotation center. + * @api + */ + rotate(angle, anchor) { + abstract(); + } + /** + * Scale the geometry (with an optional origin). This modifies the geometry + * coordinates in place. + * @abstract + * @param {number} sx The scaling factor in the x-direction. + * @param {number} [sy] The scaling factor in the y-direction (defaults to sx). + * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center + * of the geometry extent). + * @api + */ + scale(sx, sy, anchor) { + abstract(); + } + /** + * Create a simplified version of this geometry. For linestrings, this uses + * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm) + * algorithm. For polygons, a quantization-based + * simplification is used to preserve topology. + * @param {number} tolerance The tolerance distance for simplification. + * @return {Geometry} A new, simplified version of the original geometry. + * @api + */ + simplify(tolerance) { + return this.getSimplifiedGeometry(tolerance * tolerance); + } + /** + * Create a simplified version of this geometry using the Douglas Peucker + * algorithm. + * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm. + * @abstract + * @param {number} squaredTolerance Squared tolerance. + * @return {Geometry} Simplified geometry. + */ + getSimplifiedGeometry(squaredTolerance) { + return abstract(); + } + /** + * Get the type of this geometry. + * @abstract + * @return {Type} Geometry type. + */ + getType() { + return abstract(); + } + /** + * Apply a transform function to the coordinates of the geometry. + * The geometry is modified in place. + * If you do not want the geometry modified in place, first `clone()` it and + * then use this function on the clone. + * @abstract + * @param {import("../proj.js").TransformFunction} transformFn Transform function. + * Called with a flat array of geometry coordinates. + */ + applyTransform(transformFn) { + abstract(); + } + /** + * Test if the geometry and the passed extent intersect. + * @abstract + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + */ + intersectsExtent(extent) { + return abstract(); + } + /** + * Translate the geometry. This modifies the geometry coordinates in place. If + * instead you want a new geometry, first `clone()` this geometry. + * @abstract + * @param {number} deltaX Delta X. + * @param {number} deltaY Delta Y. + * @api + */ + translate(deltaX, deltaY) { + abstract(); + } + /** + * Transform each coordinate of the geometry from one coordinate reference + * system to another. The geometry is modified in place. + * For example, a line will be transformed to a line and a circle to a circle. + * If you do not want the geometry modified in place, first `clone()` it and + * then use this function on the clone. + * + * @param {import("../proj.js").ProjectionLike} source The current projection. Can be a + * string identifier or a {@link module:ol/proj/Projection~Projection} object. + * @param {import("../proj.js").ProjectionLike} destination The desired projection. Can be a + * string identifier or a {@link module:ol/proj/Projection~Projection} object. + * @return {Geometry} This geometry. Note that original geometry is + * modified in place. + * @api + */ + transform(source, destination) { + const sourceProj = get$1(source); + const transformFn = sourceProj.getUnits() == "tile-pixels" ? function(inCoordinates, outCoordinates, stride) { + const pixelExtent = sourceProj.getExtent(); + const projectedExtent = sourceProj.getWorldExtent(); + const scale2 = getHeight(projectedExtent) / getHeight(pixelExtent); + compose( + tmpTransform, + projectedExtent[0], + projectedExtent[3], + scale2, + -scale2, + 0, + 0, + 0 + ); + transform2D( + inCoordinates, + 0, + inCoordinates.length, + stride, + tmpTransform, + outCoordinates + ); + return getTransform(sourceProj, destination)( + inCoordinates, + outCoordinates, + stride + ); + } : getTransform(sourceProj, destination); + this.applyTransform(transformFn); + return this; + } +} +const Geometry$1 = Geometry; +class SimpleGeometry extends Geometry$1 { + constructor() { + super(); + this.layout = "XY"; + this.stride = 2; + this.flatCoordinates = null; + } + /** + * @param {import("../extent.js").Extent} extent Extent. + * @protected + * @return {import("../extent.js").Extent} extent Extent. + */ + computeExtent(extent) { + return createOrUpdateFromFlatCoordinates( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + extent + ); + } + /** + * @abstract + * @return {Array<*> | null} Coordinates. + */ + getCoordinates() { + return abstract(); + } + /** + * Return the first coordinate of the geometry. + * @return {import("../coordinate.js").Coordinate} First coordinate. + * @api + */ + getFirstCoordinate() { + return this.flatCoordinates.slice(0, this.stride); + } + /** + * @return {Array} Flat coordinates. + */ + getFlatCoordinates() { + return this.flatCoordinates; + } + /** + * Return the last coordinate of the geometry. + * @return {import("../coordinate.js").Coordinate} Last point. + * @api + */ + getLastCoordinate() { + return this.flatCoordinates.slice( + this.flatCoordinates.length - this.stride + ); + } + /** + * Return the {@link import("./Geometry.js").GeometryLayout layout} of the geometry. + * @return {import("./Geometry.js").GeometryLayout} Layout. + * @api + */ + getLayout() { + return this.layout; + } + /** + * Create a simplified version of this geometry using the Douglas Peucker algorithm. + * @param {number} squaredTolerance Squared tolerance. + * @return {SimpleGeometry} Simplified geometry. + */ + getSimplifiedGeometry(squaredTolerance) { + if (this.simplifiedGeometryRevision !== this.getRevision()) { + this.simplifiedGeometryMaxMinSquaredTolerance = 0; + this.simplifiedGeometryRevision = this.getRevision(); + } + if (squaredTolerance < 0 || this.simplifiedGeometryMaxMinSquaredTolerance !== 0 && squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance) { + return this; + } + const simplifiedGeometry = this.getSimplifiedGeometryInternal(squaredTolerance); + const simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates(); + if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) { + return simplifiedGeometry; + } + this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance; + return this; + } + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {SimpleGeometry} Simplified geometry. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + return this; + } + /** + * @return {number} Stride. + */ + getStride() { + return this.stride; + } + /** + * @param {import("./Geometry.js").GeometryLayout} layout Layout. + * @param {Array} flatCoordinates Flat coordinates. + */ + setFlatCoordinates(layout, flatCoordinates) { + this.stride = getStrideForLayout(layout); + this.layout = layout; + this.flatCoordinates = flatCoordinates; + } + /** + * @abstract + * @param {!Array<*>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + setCoordinates(coordinates2, layout) { + abstract(); + } + /** + * @param {import("./Geometry.js").GeometryLayout|undefined} layout Layout. + * @param {Array<*>} coordinates Coordinates. + * @param {number} nesting Nesting. + * @protected + */ + setLayout(layout, coordinates2, nesting) { + let stride; + if (layout) { + stride = getStrideForLayout(layout); + } else { + for (let i = 0; i < nesting; ++i) { + if (coordinates2.length === 0) { + this.layout = "XY"; + this.stride = 2; + return; + } + coordinates2 = /** @type {Array} */ + coordinates2[0]; + } + stride = coordinates2.length; + layout = getLayoutForStride(stride); + } + this.layout = layout; + this.stride = stride; + } + /** + * Apply a transform function to the coordinates of the geometry. + * The geometry is modified in place. + * If you do not want the geometry modified in place, first `clone()` it and + * then use this function on the clone. + * @param {import("../proj.js").TransformFunction} transformFn Transform function. + * Called with a flat array of geometry coordinates. + * @api + */ + applyTransform(transformFn) { + if (this.flatCoordinates) { + transformFn(this.flatCoordinates, this.flatCoordinates, this.stride); + this.changed(); + } + } + /** + * Rotate the geometry around a given coordinate. This modifies the geometry + * coordinates in place. + * @param {number} angle Rotation angle in counter-clockwise radians. + * @param {import("../coordinate.js").Coordinate} anchor The rotation center. + * @api + */ + rotate(angle, anchor) { + const flatCoordinates = this.getFlatCoordinates(); + if (flatCoordinates) { + const stride = this.getStride(); + rotate( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + angle, + anchor, + flatCoordinates + ); + this.changed(); + } + } + /** + * Scale the geometry (with an optional origin). This modifies the geometry + * coordinates in place. + * @param {number} sx The scaling factor in the x-direction. + * @param {number} [sy] The scaling factor in the y-direction (defaults to sx). + * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center + * of the geometry extent). + * @api + */ + scale(sx, sy, anchor) { + if (sy === void 0) { + sy = sx; + } + if (!anchor) { + anchor = getCenter(this.getExtent()); + } + const flatCoordinates = this.getFlatCoordinates(); + if (flatCoordinates) { + const stride = this.getStride(); + scale$1( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + sx, + sy, + anchor, + flatCoordinates + ); + this.changed(); + } + } + /** + * Translate the geometry. This modifies the geometry coordinates in place. If + * instead you want a new geometry, first `clone()` this geometry. + * @param {number} deltaX Delta X. + * @param {number} deltaY Delta Y. + * @api + */ + translate(deltaX, deltaY) { + const flatCoordinates = this.getFlatCoordinates(); + if (flatCoordinates) { + const stride = this.getStride(); + translate( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + deltaX, + deltaY, + flatCoordinates + ); + this.changed(); + } + } +} +function getLayoutForStride(stride) { + let layout; + if (stride == 2) { + layout = "XY"; + } else if (stride == 3) { + layout = "XYZ"; + } else if (stride == 4) { + layout = "XYZM"; + } + return ( + /** @type {import("./Geometry.js").GeometryLayout} */ + layout + ); +} +function getStrideForLayout(layout) { + let stride; + if (layout == "XY") { + stride = 2; + } else if (layout == "XYZ" || layout == "XYM") { + stride = 3; + } else if (layout == "XYZM") { + stride = 4; + } + return ( + /** @type {number} */ + stride + ); +} +function transformGeom2D(simpleGeometry, transform2, dest) { + const flatCoordinates = simpleGeometry.getFlatCoordinates(); + if (!flatCoordinates) { + return null; + } + const stride = simpleGeometry.getStride(); + return transform2D( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + transform2, + dest + ); +} +const SimpleGeometry$1 = SimpleGeometry; +function assignClosest(flatCoordinates, offset1, offset2, stride, x, y, closestPoint) { + const x1 = flatCoordinates[offset1]; + const y1 = flatCoordinates[offset1 + 1]; + const dx = flatCoordinates[offset2] - x1; + const dy = flatCoordinates[offset2 + 1] - y1; + let offset; + if (dx === 0 && dy === 0) { + offset = offset1; + } else { + const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); + if (t > 1) { + offset = offset2; + } else if (t > 0) { + for (let i = 0; i < stride; ++i) { + closestPoint[i] = lerp( + flatCoordinates[offset1 + i], + flatCoordinates[offset2 + i], + t + ); + } + closestPoint.length = stride; + return; + } else { + offset = offset1; + } + } + for (let i = 0; i < stride; ++i) { + closestPoint[i] = flatCoordinates[offset + i]; + } + closestPoint.length = stride; +} +function maxSquaredDelta(flatCoordinates, offset, end, stride, max) { + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + for (offset += stride; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + const squaredDelta = squaredDistance(x1, y1, x2, y2); + if (squaredDelta > max) { + max = squaredDelta; + } + x1 = x2; + y1 = y2; + } + return max; +} +function arrayMaxSquaredDelta(flatCoordinates, offset, ends, stride, max) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + max = maxSquaredDelta(flatCoordinates, offset, end, stride, max); + offset = end; + } + return max; +} +function multiArrayMaxSquaredDelta(flatCoordinates, offset, endss, stride, max) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + max = arrayMaxSquaredDelta(flatCoordinates, offset, ends, stride, max); + offset = ends[ends.length - 1]; + } + return max; +} +function assignClosestPoint(flatCoordinates, offset, end, stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint) { + if (offset == end) { + return minSquaredDistance; + } + let i, squaredDistance$1; + if (maxDelta === 0) { + squaredDistance$1 = squaredDistance( + x, + y, + flatCoordinates[offset], + flatCoordinates[offset + 1] + ); + if (squaredDistance$1 < minSquaredDistance) { + for (i = 0; i < stride; ++i) { + closestPoint[i] = flatCoordinates[offset + i]; + } + closestPoint.length = stride; + return squaredDistance$1; + } + return minSquaredDistance; + } + tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN]; + let index = offset + stride; + while (index < end) { + assignClosest( + flatCoordinates, + index - stride, + index, + stride, + x, + y, + tmpPoint + ); + squaredDistance$1 = squaredDistance(x, y, tmpPoint[0], tmpPoint[1]); + if (squaredDistance$1 < minSquaredDistance) { + minSquaredDistance = squaredDistance$1; + for (i = 0; i < stride; ++i) { + closestPoint[i] = tmpPoint[i]; + } + closestPoint.length = stride; + index += stride; + } else { + index += stride * Math.max( + (Math.sqrt(squaredDistance$1) - Math.sqrt(minSquaredDistance)) / maxDelta | 0, + 1 + ); + } + } + if (isRing) { + assignClosest( + flatCoordinates, + end - stride, + offset, + stride, + x, + y, + tmpPoint + ); + squaredDistance$1 = squaredDistance(x, y, tmpPoint[0], tmpPoint[1]); + if (squaredDistance$1 < minSquaredDistance) { + minSquaredDistance = squaredDistance$1; + for (i = 0; i < stride; ++i) { + closestPoint[i] = tmpPoint[i]; + } + closestPoint.length = stride; + } + } + return minSquaredDistance; +} +function assignClosestArrayPoint(flatCoordinates, offset, ends, stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint) { + tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN]; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + minSquaredDistance = assignClosestPoint( + flatCoordinates, + offset, + end, + stride, + maxDelta, + isRing, + x, + y, + closestPoint, + minSquaredDistance, + tmpPoint + ); + offset = end; + } + return minSquaredDistance; +} +function assignClosestMultiArrayPoint(flatCoordinates, offset, endss, stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint) { + tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN]; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + minSquaredDistance = assignClosestArrayPoint( + flatCoordinates, + offset, + ends, + stride, + maxDelta, + isRing, + x, + y, + closestPoint, + minSquaredDistance, + tmpPoint + ); + offset = ends[ends.length - 1]; + } + return minSquaredDistance; +} +function deflateCoordinate(flatCoordinates, offset, coordinate, stride) { + for (let i = 0, ii = coordinate.length; i < ii; ++i) { + flatCoordinates[offset++] = coordinate[i]; + } + return offset; +} +function deflateCoordinates(flatCoordinates, offset, coordinates2, stride) { + for (let i = 0, ii = coordinates2.length; i < ii; ++i) { + const coordinate = coordinates2[i]; + for (let j = 0; j < stride; ++j) { + flatCoordinates[offset++] = coordinate[j]; + } + } + return offset; +} +function deflateCoordinatesArray(flatCoordinates, offset, coordinatess, stride, ends) { + ends = ends ? ends : []; + let i = 0; + for (let j = 0, jj = coordinatess.length; j < jj; ++j) { + const end = deflateCoordinates( + flatCoordinates, + offset, + coordinatess[j], + stride + ); + ends[i++] = end; + offset = end; + } + ends.length = i; + return ends; +} +function deflateMultiCoordinatesArray(flatCoordinates, offset, coordinatesss, stride, endss) { + endss = endss ? endss : []; + let i = 0; + for (let j = 0, jj = coordinatesss.length; j < jj; ++j) { + const ends = deflateCoordinatesArray( + flatCoordinates, + offset, + coordinatesss[j], + stride, + endss[i] + ); + if (ends.length === 0) { + ends[0] = offset; + } + endss[i++] = ends; + offset = ends[ends.length - 1]; + } + endss.length = i; + return endss; +} +function douglasPeucker(flatCoordinates, offset, end, stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset) { + const n = (end - offset) / stride; + if (n < 3) { + for (; offset < end; offset += stride) { + simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset]; + simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset + 1]; + } + return simplifiedOffset; + } + const markers = new Array(n); + markers[0] = 1; + markers[n - 1] = 1; + const stack = [offset, end - stride]; + let index = 0; + while (stack.length > 0) { + const last = stack.pop(); + const first = stack.pop(); + let maxSquaredDistance = 0; + const x1 = flatCoordinates[first]; + const y1 = flatCoordinates[first + 1]; + const x2 = flatCoordinates[last]; + const y2 = flatCoordinates[last + 1]; + for (let i = first + stride; i < last; i += stride) { + const x = flatCoordinates[i]; + const y = flatCoordinates[i + 1]; + const squaredDistance2 = squaredSegmentDistance(x, y, x1, y1, x2, y2); + if (squaredDistance2 > maxSquaredDistance) { + index = i; + maxSquaredDistance = squaredDistance2; + } + } + if (maxSquaredDistance > squaredTolerance) { + markers[(index - offset) / stride] = 1; + if (first + stride < index) { + stack.push(first, index); + } + if (index + stride < last) { + stack.push(index, last); + } + } + } + for (let i = 0; i < n; ++i) { + if (markers[i]) { + simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset + i * stride]; + simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset + i * stride + 1]; + } + } + return simplifiedOffset; +} +function douglasPeuckerArray(flatCoordinates, offset, ends, stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + simplifiedOffset = douglasPeucker( + flatCoordinates, + offset, + end, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + simplifiedOffset + ); + simplifiedEnds.push(simplifiedOffset); + offset = end; + } + return simplifiedOffset; +} +function snap(value, tolerance) { + return tolerance * Math.round(value / tolerance); +} +function quantize(flatCoordinates, offset, end, stride, tolerance, simplifiedFlatCoordinates, simplifiedOffset) { + if (offset == end) { + return simplifiedOffset; + } + let x1 = snap(flatCoordinates[offset], tolerance); + let y1 = snap(flatCoordinates[offset + 1], tolerance); + offset += stride; + simplifiedFlatCoordinates[simplifiedOffset++] = x1; + simplifiedFlatCoordinates[simplifiedOffset++] = y1; + let x2, y2; + do { + x2 = snap(flatCoordinates[offset], tolerance); + y2 = snap(flatCoordinates[offset + 1], tolerance); + offset += stride; + if (offset == end) { + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + return simplifiedOffset; + } + } while (x2 == x1 && y2 == y1); + while (offset < end) { + const x3 = snap(flatCoordinates[offset], tolerance); + const y3 = snap(flatCoordinates[offset + 1], tolerance); + offset += stride; + if (x3 == x2 && y3 == y2) { + continue; + } + const dx1 = x2 - x1; + const dy1 = y2 - y1; + const dx2 = x3 - x1; + const dy2 = y3 - y1; + if (dx1 * dy2 == dy1 * dx2 && (dx1 < 0 && dx2 < dx1 || dx1 == dx2 || dx1 > 0 && dx2 > dx1) && (dy1 < 0 && dy2 < dy1 || dy1 == dy2 || dy1 > 0 && dy2 > dy1)) { + x2 = x3; + y2 = y3; + continue; + } + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + x1 = x2; + y1 = y2; + x2 = x3; + y2 = y3; + } + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + return simplifiedOffset; +} +function quantizeArray(flatCoordinates, offset, ends, stride, tolerance, simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + simplifiedOffset = quantize( + flatCoordinates, + offset, + end, + stride, + tolerance, + simplifiedFlatCoordinates, + simplifiedOffset + ); + simplifiedEnds.push(simplifiedOffset); + offset = end; + } + return simplifiedOffset; +} +function quantizeMultiArray(flatCoordinates, offset, endss, stride, tolerance, simplifiedFlatCoordinates, simplifiedOffset, simplifiedEndss) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + const simplifiedEnds = []; + simplifiedOffset = quantizeArray( + flatCoordinates, + offset, + ends, + stride, + tolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + simplifiedEnds + ); + simplifiedEndss.push(simplifiedEnds); + offset = ends[ends.length - 1]; + } + return simplifiedOffset; +} +function inflateCoordinates(flatCoordinates, offset, end, stride, coordinates2) { + coordinates2 = coordinates2 !== void 0 ? coordinates2 : []; + let i = 0; + for (let j = offset; j < end; j += stride) { + coordinates2[i++] = flatCoordinates.slice(j, j + stride); + } + coordinates2.length = i; + return coordinates2; +} +function inflateCoordinatesArray(flatCoordinates, offset, ends, stride, coordinatess) { + coordinatess = coordinatess !== void 0 ? coordinatess : []; + let i = 0; + for (let j = 0, jj = ends.length; j < jj; ++j) { + const end = ends[j]; + coordinatess[i++] = inflateCoordinates( + flatCoordinates, + offset, + end, + stride, + coordinatess[i] + ); + offset = end; + } + coordinatess.length = i; + return coordinatess; +} +function inflateMultiCoordinatesArray(flatCoordinates, offset, endss, stride, coordinatesss) { + coordinatesss = coordinatesss !== void 0 ? coordinatesss : []; + let i = 0; + for (let j = 0, jj = endss.length; j < jj; ++j) { + const ends = endss[j]; + coordinatesss[i++] = ends.length === 1 && ends[0] === offset ? [] : inflateCoordinatesArray( + flatCoordinates, + offset, + ends, + stride, + coordinatesss[i] + ); + offset = ends[ends.length - 1]; + } + coordinatesss.length = i; + return coordinatesss; +} +function linearRing(flatCoordinates, offset, end, stride) { + let twiceArea = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; + for (; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + twiceArea += y1 * x2 - x1 * y2; + x1 = x2; + y1 = y2; + } + return twiceArea / 2; +} +function linearRings(flatCoordinates, offset, ends, stride) { + let area = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + area += linearRing(flatCoordinates, offset, end, stride); + offset = end; + } + return area; +} +function linearRingss$1(flatCoordinates, offset, endss, stride) { + let area = 0; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + area += linearRings(flatCoordinates, offset, ends, stride); + offset = ends[ends.length - 1]; + } + return area; +} +class LinearRing extends SimpleGeometry$1 { + /** + * @param {Array|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates2, layout) { + super(); + this.maxDelta_ = -1; + this.maxDeltaRevision_ = -1; + if (layout !== void 0 && !Array.isArray(coordinates2[0])) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ + coordinates2 + ); + } else { + this.setCoordinates( + /** @type {Array} */ + coordinates2, + layout + ); + } + } + /** + * Make a complete copy of the geometry. + * @return {!LinearRing} Clone. + * @api + */ + clone() { + return new LinearRing(this.flatCoordinates.slice(), this.layout); + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + maxSquaredDelta( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + 0 + ) + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return assignClosestPoint( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + this.maxDelta_, + true, + x, + y, + closestPoint, + minSquaredDistance + ); + } + /** + * Return the area of the linear ring on projected plane. + * @return {number} Area (on projected plane). + * @api + */ + getArea() { + return linearRing( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride + ); + } + /** + * Return the coordinates of the linear ring. + * @return {Array} Coordinates. + * @api + */ + getCoordinates() { + return inflateCoordinates( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride + ); + } + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {LinearRing} Simplified LinearRing. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + const simplifiedFlatCoordinates = []; + simplifiedFlatCoordinates.length = douglasPeucker( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0 + ); + return new LinearRing(simplifiedFlatCoordinates, "XY"); + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "LinearRing"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return false; + } + /** + * Set the coordinates of the linear ring. + * @param {!Array} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates2, layout) { + this.setLayout(layout, coordinates2, 1); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = deflateCoordinates( + this.flatCoordinates, + 0, + coordinates2, + this.stride + ); + this.changed(); + } +} +const LinearRing$1 = LinearRing; +class Point extends SimpleGeometry$1 { + /** + * @param {import("../coordinate.js").Coordinate} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates2, layout) { + super(); + this.setCoordinates(coordinates2, layout); + } + /** + * Make a complete copy of the geometry. + * @return {!Point} Clone. + * @api + */ + clone() { + const point = new Point(this.flatCoordinates.slice(), this.layout); + point.applyProperties(this); + return point; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + const flatCoordinates = this.flatCoordinates; + const squaredDistance$1 = squaredDistance( + x, + y, + flatCoordinates[0], + flatCoordinates[1] + ); + if (squaredDistance$1 < minSquaredDistance) { + const stride = this.stride; + for (let i = 0; i < stride; ++i) { + closestPoint[i] = flatCoordinates[i]; + } + closestPoint.length = stride; + return squaredDistance$1; + } + return minSquaredDistance; + } + /** + * Return the coordinate of the point. + * @return {import("../coordinate.js").Coordinate} Coordinates. + * @api + */ + getCoordinates() { + return !this.flatCoordinates ? [] : this.flatCoordinates.slice(); + } + /** + * @param {import("../extent.js").Extent} extent Extent. + * @protected + * @return {import("../extent.js").Extent} extent Extent. + */ + computeExtent(extent) { + return createOrUpdateFromCoordinate(this.flatCoordinates, extent); + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "Point"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return containsXY(extent, this.flatCoordinates[0], this.flatCoordinates[1]); + } + /** + * @param {!Array<*>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates2, layout) { + this.setLayout(layout, coordinates2, 0); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = deflateCoordinate( + this.flatCoordinates, + 0, + coordinates2, + this.stride + ); + this.changed(); + } +} +const OlPoint = Point; +function linearRingContainsExtent(flatCoordinates, offset, end, stride, extent) { + const outside = forEachCorner( + extent, + /** + * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate. + * @return {boolean} Contains (x, y). + */ + function(coordinate) { + return !linearRingContainsXY( + flatCoordinates, + offset, + end, + stride, + coordinate[0], + coordinate[1] + ); + } + ); + return !outside; +} +function linearRingContainsXY(flatCoordinates, offset, end, stride, x, y) { + let wn = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; + for (; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + if (y1 <= y) { + if (y2 > y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) > 0) { + wn++; + } + } else if (y2 <= y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) < 0) { + wn--; + } + x1 = x2; + y1 = y2; + } + return wn !== 0; +} +function linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y) { + if (ends.length === 0) { + return false; + } + if (!linearRingContainsXY(flatCoordinates, offset, ends[0], stride, x, y)) { + return false; + } + for (let i = 1, ii = ends.length; i < ii; ++i) { + if (linearRingContainsXY(flatCoordinates, ends[i - 1], ends[i], stride, x, y)) { + return false; + } + } + return true; +} +function linearRingssContainsXY(flatCoordinates, offset, endss, stride, x, y) { + if (endss.length === 0) { + return false; + } + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) { + return true; + } + offset = ends[ends.length - 1]; + } + return false; +} +function getInteriorPointOfArray(flatCoordinates, offset, ends, stride, flatCenters, flatCentersOffset, dest) { + let i, ii, x, x1, x2, y1, y2; + const y = flatCenters[flatCentersOffset + 1]; + const intersections = []; + for (let r = 0, rr = ends.length; r < rr; ++r) { + const end = ends[r]; + x1 = flatCoordinates[end - stride]; + y1 = flatCoordinates[end - stride + 1]; + for (i = offset; i < end; i += stride) { + x2 = flatCoordinates[i]; + y2 = flatCoordinates[i + 1]; + if (y <= y1 && y2 <= y || y1 <= y && y <= y2) { + x = (y - y1) / (y2 - y1) * (x2 - x1) + x1; + intersections.push(x); + } + x1 = x2; + y1 = y2; + } + } + let pointX = NaN; + let maxSegmentLength = -Infinity; + intersections.sort(ascending); + x1 = intersections[0]; + for (i = 1, ii = intersections.length; i < ii; ++i) { + x2 = intersections[i]; + const segmentLength = Math.abs(x2 - x1); + if (segmentLength > maxSegmentLength) { + x = (x1 + x2) / 2; + if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) { + pointX = x; + maxSegmentLength = segmentLength; + } + } + x1 = x2; + } + if (isNaN(pointX)) { + pointX = flatCenters[flatCentersOffset]; + } + if (dest) { + dest.push(pointX, y, maxSegmentLength); + return dest; + } + return [pointX, y, maxSegmentLength]; +} +function getInteriorPointsOfMultiArray(flatCoordinates, offset, endss, stride, flatCenters) { + let interiorPoints = []; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + interiorPoints = getInteriorPointOfArray( + flatCoordinates, + offset, + ends, + stride, + flatCenters, + 2 * i, + interiorPoints + ); + offset = ends[ends.length - 1]; + } + return interiorPoints; +} +function forEach(flatCoordinates, offset, end, stride, callback) { + let ret; + offset += stride; + for (; offset < end; offset += stride) { + ret = callback( + flatCoordinates.slice(offset - stride, offset), + flatCoordinates.slice(offset, offset + stride) + ); + if (ret) { + return ret; + } + } + return false; +} +function intersectsLineString(flatCoordinates, offset, end, stride, extent) { + const coordinatesExtent = extendFlatCoordinates( + createEmpty(), + flatCoordinates, + offset, + end, + stride + ); + if (!intersects$1(extent, coordinatesExtent)) { + return false; + } + if (containsExtent(extent, coordinatesExtent)) { + return true; + } + if (coordinatesExtent[0] >= extent[0] && coordinatesExtent[2] <= extent[2]) { + return true; + } + if (coordinatesExtent[1] >= extent[1] && coordinatesExtent[3] <= extent[3]) { + return true; + } + return forEach( + flatCoordinates, + offset, + end, + stride, + /** + * @param {import("../../coordinate.js").Coordinate} point1 Start point. + * @param {import("../../coordinate.js").Coordinate} point2 End point. + * @return {boolean} `true` if the segment and the extent intersect, + * `false` otherwise. + */ + function(point1, point2) { + return intersectsSegment(extent, point1, point2); + } + ); +} +function intersectsLineStringArray(flatCoordinates, offset, ends, stride, extent) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + if (intersectsLineString(flatCoordinates, offset, ends[i], stride, extent)) { + return true; + } + offset = ends[i]; + } + return false; +} +function intersectsLinearRing(flatCoordinates, offset, end, stride, extent) { + if (intersectsLineString(flatCoordinates, offset, end, stride, extent)) { + return true; + } + if (linearRingContainsXY( + flatCoordinates, + offset, + end, + stride, + extent[0], + extent[1] + )) { + return true; + } + if (linearRingContainsXY( + flatCoordinates, + offset, + end, + stride, + extent[0], + extent[3] + )) { + return true; + } + if (linearRingContainsXY( + flatCoordinates, + offset, + end, + stride, + extent[2], + extent[1] + )) { + return true; + } + if (linearRingContainsXY( + flatCoordinates, + offset, + end, + stride, + extent[2], + extent[3] + )) { + return true; + } + return false; +} +function intersectsLinearRingArray(flatCoordinates, offset, ends, stride, extent) { + if (!intersectsLinearRing(flatCoordinates, offset, ends[0], stride, extent)) { + return false; + } + if (ends.length === 1) { + return true; + } + for (let i = 1, ii = ends.length; i < ii; ++i) { + if (linearRingContainsExtent( + flatCoordinates, + ends[i - 1], + ends[i], + stride, + extent + )) { + if (!intersectsLineString( + flatCoordinates, + ends[i - 1], + ends[i], + stride, + extent + )) { + return false; + } + } + } + return true; +} +function intersectsLinearRingMultiArray(flatCoordinates, offset, endss, stride, extent) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + if (intersectsLinearRingArray(flatCoordinates, offset, ends, stride, extent)) { + return true; + } + offset = ends[ends.length - 1]; + } + return false; +} +function coordinates(flatCoordinates, offset, end, stride) { + while (offset < end - stride) { + for (let i = 0; i < stride; ++i) { + const tmp = flatCoordinates[offset + i]; + flatCoordinates[offset + i] = flatCoordinates[end - stride + i]; + flatCoordinates[end - stride + i] = tmp; + } + offset += stride; + end -= stride; + } +} +function linearRingIsClockwise(flatCoordinates, offset, end, stride) { + let edge = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; + for (; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + edge += (x2 - x1) * (y2 + y1); + x1 = x2; + y1 = y2; + } + return edge === 0 ? void 0 : edge > 0; +} +function linearRingsAreOriented(flatCoordinates, offset, ends, stride, right) { + right = right !== void 0 ? right : false; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const isClockwise = linearRingIsClockwise( + flatCoordinates, + offset, + end, + stride + ); + if (i === 0) { + if (right && isClockwise || !right && !isClockwise) { + return false; + } + } else { + if (right && !isClockwise || !right && isClockwise) { + return false; + } + } + offset = end; + } + return true; +} +function linearRingssAreOriented(flatCoordinates, offset, endss, stride, right) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + if (!linearRingsAreOriented(flatCoordinates, offset, ends, stride, right)) { + return false; + } + if (ends.length) { + offset = ends[ends.length - 1]; + } + } + return true; +} +function orientLinearRings(flatCoordinates, offset, ends, stride, right) { + right = right !== void 0 ? right : false; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const isClockwise = linearRingIsClockwise( + flatCoordinates, + offset, + end, + stride + ); + const reverse = i === 0 ? right && isClockwise || !right && !isClockwise : right && !isClockwise || !right && isClockwise; + if (reverse) { + coordinates(flatCoordinates, offset, end, stride); + } + offset = end; + } + return offset; +} +function orientLinearRingsArray(flatCoordinates, offset, endss, stride, right) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + offset = orientLinearRings( + flatCoordinates, + offset, + endss[i], + stride, + right + ); + } + return offset; +} +class Polygon extends SimpleGeometry$1 { + /** + * @param {!Array>|!Array} coordinates + * Array of linear rings that define the polygon. The first linear ring of the + * array defines the outer-boundary or surface of the polygon. Each subsequent + * linear ring defines a hole in the surface of the polygon. A linear ring is + * an array of vertices' coordinates where the first coordinate and the last are + * equivalent. (For internal use, flat coordinates in combination with + * `layout` and `ends` are also accepted.) + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @param {Array} [ends] Ends (for internal use with flat coordinates). + */ + constructor(coordinates2, layout, ends) { + super(); + this.ends_ = []; + this.flatInteriorPointRevision_ = -1; + this.flatInteriorPoint_ = null; + this.maxDelta_ = -1; + this.maxDeltaRevision_ = -1; + this.orientedRevision_ = -1; + this.orientedFlatCoordinates_ = null; + if (layout !== void 0 && ends) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ + coordinates2 + ); + this.ends_ = ends; + } else { + this.setCoordinates( + /** @type {Array>} */ + coordinates2, + layout + ); + } + } + /** + * Append the passed linear ring to this polygon. + * @param {LinearRing} linearRing Linear ring. + * @api + */ + appendLinearRing(linearRing2) { + if (!this.flatCoordinates) { + this.flatCoordinates = linearRing2.getFlatCoordinates().slice(); + } else { + extend$2(this.flatCoordinates, linearRing2.getFlatCoordinates()); + } + this.ends_.push(this.flatCoordinates.length); + this.changed(); + } + /** + * Make a complete copy of the geometry. + * @return {!Polygon} Clone. + * @api + */ + clone() { + const polygon = new Polygon( + this.flatCoordinates.slice(), + this.layout, + this.ends_.slice() + ); + polygon.applyProperties(this); + return polygon; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + arrayMaxSquaredDelta( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + 0 + ) + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return assignClosestArrayPoint( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + this.maxDelta_, + true, + x, + y, + closestPoint, + minSquaredDistance + ); + } + /** + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ + containsXY(x, y) { + return linearRingsContainsXY( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride, + x, + y + ); + } + /** + * Return the area of the polygon on projected plane. + * @return {number} Area (on projected plane). + * @api + */ + getArea() { + return linearRings( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride + ); + } + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for polygons. + * + * @param {boolean} [right] Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @return {Array>} Coordinates. + * @api + */ + getCoordinates(right) { + let flatCoordinates; + if (right !== void 0) { + flatCoordinates = this.getOrientedFlatCoordinates().slice(); + orientLinearRings(flatCoordinates, 0, this.ends_, this.stride, right); + } else { + flatCoordinates = this.flatCoordinates; + } + return inflateCoordinatesArray(flatCoordinates, 0, this.ends_, this.stride); + } + /** + * @return {Array} Ends. + */ + getEnds() { + return this.ends_; + } + /** + * @return {Array} Interior point. + */ + getFlatInteriorPoint() { + if (this.flatInteriorPointRevision_ != this.getRevision()) { + const flatCenter = getCenter(this.getExtent()); + this.flatInteriorPoint_ = getInteriorPointOfArray( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride, + flatCenter, + 0 + ); + this.flatInteriorPointRevision_ = this.getRevision(); + } + return this.flatInteriorPoint_; + } + /** + * Return an interior point of the polygon. + * @return {Point} Interior point as XYM coordinate, where M is the + * length of the horizontal intersection that the point belongs to. + * @api + */ + getInteriorPoint() { + return new OlPoint(this.getFlatInteriorPoint(), "XYM"); + } + /** + * Return the number of rings of the polygon, this includes the exterior + * ring and any interior rings. + * + * @return {number} Number of rings. + * @api + */ + getLinearRingCount() { + return this.ends_.length; + } + /** + * Return the Nth linear ring of the polygon geometry. Return `null` if the + * given index is out of range. + * The exterior linear ring is available at index `0` and the interior rings + * at index `1` and beyond. + * + * @param {number} index Index. + * @return {LinearRing|null} Linear ring. + * @api + */ + getLinearRing(index) { + if (index < 0 || this.ends_.length <= index) { + return null; + } + return new LinearRing$1( + this.flatCoordinates.slice( + index === 0 ? 0 : this.ends_[index - 1], + this.ends_[index] + ), + this.layout + ); + } + /** + * Return the linear rings of the polygon. + * @return {Array} Linear rings. + * @api + */ + getLinearRings() { + const layout = this.layout; + const flatCoordinates = this.flatCoordinates; + const ends = this.ends_; + const linearRings2 = []; + let offset = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const linearRing2 = new LinearRing$1( + flatCoordinates.slice(offset, end), + layout + ); + linearRings2.push(linearRing2); + offset = end; + } + return linearRings2; + } + /** + * @return {Array} Oriented flat coordinates. + */ + getOrientedFlatCoordinates() { + if (this.orientedRevision_ != this.getRevision()) { + const flatCoordinates = this.flatCoordinates; + if (linearRingsAreOriented(flatCoordinates, 0, this.ends_, this.stride)) { + this.orientedFlatCoordinates_ = flatCoordinates; + } else { + this.orientedFlatCoordinates_ = flatCoordinates.slice(); + this.orientedFlatCoordinates_.length = orientLinearRings( + this.orientedFlatCoordinates_, + 0, + this.ends_, + this.stride + ); + } + this.orientedRevision_ = this.getRevision(); + } + return this.orientedFlatCoordinates_; + } + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {Polygon} Simplified Polygon. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + const simplifiedFlatCoordinates = []; + const simplifiedEnds = []; + simplifiedFlatCoordinates.length = quantizeArray( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + Math.sqrt(squaredTolerance), + simplifiedFlatCoordinates, + 0, + simplifiedEnds + ); + return new Polygon(simplifiedFlatCoordinates, "XY", simplifiedEnds); + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "Polygon"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return intersectsLinearRingArray( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride, + extent + ); + } + /** + * Set the coordinates of the polygon. + * @param {!Array>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates2, layout) { + this.setLayout(layout, coordinates2, 2); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + const ends = deflateCoordinatesArray( + this.flatCoordinates, + 0, + coordinates2, + this.stride, + this.ends_ + ); + this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1]; + this.changed(); + } +} +const Polygon$1 = Polygon; +function fromExtent(extent) { + if (isEmpty(extent)) { + throw new Error("Cannot create polygon from empty extent"); + } + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const flatCoordinates = [ + minX, + minY, + minX, + maxY, + maxX, + maxY, + maxX, + minY, + minX, + minY + ]; + return new Polygon(flatCoordinates, "XY", [flatCoordinates.length]); +} +const DEFAULT_MIN_ZOOM = 0; +class View extends BaseObject$1 { + /** + * @param {ViewOptions} [options] View options. + */ + constructor(options) { + super(); + this.on; + this.once; + this.un; + options = Object.assign({}, options); + this.hints_ = [0, 0]; + this.animations_ = []; + this.updateAnimationKey_; + this.projection_ = createProjection(options.projection, "EPSG:3857"); + this.viewportSize_ = [100, 100]; + this.targetCenter_ = null; + this.targetResolution_; + this.targetRotation_; + this.nextCenter_ = null; + this.nextResolution_; + this.nextRotation_; + this.cancelAnchor_ = void 0; + if (options.projection) { + disableCoordinateWarning(); + } + if (options.center) { + options.center = fromUserCoordinate(options.center, this.projection_); + } + if (options.extent) { + options.extent = fromUserExtent(options.extent, this.projection_); + } + this.applyOptions_(options); + } + /** + * Set up the view with the given options. + * @param {ViewOptions} options View options. + */ + applyOptions_(options) { + const properties = Object.assign({}, options); + for (const key in ViewProperty) { + delete properties[key]; + } + this.setProperties(properties, true); + const resolutionConstraintInfo = createResolutionConstraint(options); + this.maxResolution_ = resolutionConstraintInfo.maxResolution; + this.minResolution_ = resolutionConstraintInfo.minResolution; + this.zoomFactor_ = resolutionConstraintInfo.zoomFactor; + this.resolutions_ = options.resolutions; + this.padding_ = options.padding; + this.minZoom_ = resolutionConstraintInfo.minZoom; + const centerConstraint = createCenterConstraint(options); + const resolutionConstraint = resolutionConstraintInfo.constraint; + const rotationConstraint = createRotationConstraint(options); + this.constraints_ = { + center: centerConstraint, + resolution: resolutionConstraint, + rotation: rotationConstraint + }; + this.setRotation(options.rotation !== void 0 ? options.rotation : 0); + this.setCenterInternal( + options.center !== void 0 ? options.center : null + ); + if (options.resolution !== void 0) { + this.setResolution(options.resolution); + } else if (options.zoom !== void 0) { + this.setZoom(options.zoom); + } + } + /** + * Padding (in css pixels). + * If the map viewport is partially covered with other content (overlays) along + * its edges, this setting allows to shift the center of the viewport away from that + * content. The order of the values in the array is top, right, bottom, left. + * The default is no padding, which is equivalent to `[0, 0, 0, 0]`. + * @type {Array|undefined} + * @api + */ + get padding() { + return this.padding_; + } + set padding(padding) { + let oldPadding = this.padding_; + this.padding_ = padding; + const center = this.getCenterInternal(); + if (center) { + const newPadding = padding || [0, 0, 0, 0]; + oldPadding = oldPadding || [0, 0, 0, 0]; + const resolution = this.getResolution(); + const offsetX = resolution / 2 * (newPadding[3] - oldPadding[3] + oldPadding[1] - newPadding[1]); + const offsetY = resolution / 2 * (newPadding[0] - oldPadding[0] + oldPadding[2] - newPadding[2]); + this.setCenterInternal([center[0] + offsetX, center[1] - offsetY]); + } + } + /** + * Get an updated version of the view options used to construct the view. The + * current resolution (or zoom), center, and rotation are applied to any stored + * options. The provided options can be used to apply new min/max zoom or + * resolution limits. + * @param {ViewOptions} newOptions New options to be applied. + * @return {ViewOptions} New options updated with the current view state. + */ + getUpdatedOptions_(newOptions) { + const options = this.getProperties(); + if (options.resolution !== void 0) { + options.resolution = this.getResolution(); + } else { + options.zoom = this.getZoom(); + } + options.center = this.getCenterInternal(); + options.rotation = this.getRotation(); + return Object.assign({}, options, newOptions); + } + /** + * Animate the view. The view's center, zoom (or resolution), and rotation + * can be animated for smooth transitions between view states. For example, + * to animate the view to a new zoom level: + * + * view.animate({zoom: view.getZoom() + 1}); + * + * By default, the animation lasts one second and uses in-and-out easing. You + * can customize this behavior by including `duration` (in milliseconds) and + * `easing` options (see {@link module:ol/easing}). + * + * To chain together multiple animations, call the method with multiple + * animation objects. For example, to first zoom and then pan: + * + * view.animate({zoom: 10}, {center: [0, 0]}); + * + * If you provide a function as the last argument to the animate method, it + * will get called at the end of an animation series. The callback will be + * called with `true` if the animation series completed on its own or `false` + * if it was cancelled. + * + * Animations are cancelled by user interactions (e.g. dragging the map) or by + * calling `view.setCenter()`, `view.setResolution()`, or `view.setRotation()` + * (or another method that calls one of these). + * + * @param {...(AnimationOptions|function(boolean): void)} var_args Animation + * options. Multiple animations can be run in series by passing multiple + * options objects. To run multiple animations in parallel, call the method + * multiple times. An optional callback can be provided as a final + * argument. The callback will be called with a boolean indicating whether + * the animation completed without being cancelled. + * @api + */ + animate(var_args) { + if (this.isDef() && !this.getAnimating()) { + this.resolveConstraints(0); + } + const args = new Array(arguments.length); + for (let i = 0; i < args.length; ++i) { + let options = arguments[i]; + if (options.center) { + options = Object.assign({}, options); + options.center = fromUserCoordinate( + options.center, + this.getProjection() + ); + } + if (options.anchor) { + options = Object.assign({}, options); + options.anchor = fromUserCoordinate( + options.anchor, + this.getProjection() + ); + } + args[i] = options; + } + this.animateInternal.apply(this, args); + } + /** + * @param {...(AnimationOptions|function(boolean): void)} var_args Animation options. + */ + animateInternal(var_args) { + let animationCount = arguments.length; + let callback; + if (animationCount > 1 && typeof arguments[animationCount - 1] === "function") { + callback = arguments[animationCount - 1]; + --animationCount; + } + let i = 0; + for (; i < animationCount && !this.isDef(); ++i) { + const state = arguments[i]; + if (state.center) { + this.setCenterInternal(state.center); + } + if (state.zoom !== void 0) { + this.setZoom(state.zoom); + } else if (state.resolution) { + this.setResolution(state.resolution); + } + if (state.rotation !== void 0) { + this.setRotation(state.rotation); + } + } + if (i === animationCount) { + if (callback) { + animationCallback(callback, true); + } + return; + } + let start = Date.now(); + let center = this.targetCenter_.slice(); + let resolution = this.targetResolution_; + let rotation = this.targetRotation_; + const series = []; + for (; i < animationCount; ++i) { + const options = ( + /** @type {AnimationOptions} */ + arguments[i] + ); + const animation = { + start, + complete: false, + anchor: options.anchor, + duration: options.duration !== void 0 ? options.duration : 1e3, + easing: options.easing || inAndOut, + callback + }; + if (options.center) { + animation.sourceCenter = center; + animation.targetCenter = options.center.slice(); + center = animation.targetCenter; + } + if (options.zoom !== void 0) { + animation.sourceResolution = resolution; + animation.targetResolution = this.getResolutionForZoom(options.zoom); + resolution = animation.targetResolution; + } else if (options.resolution) { + animation.sourceResolution = resolution; + animation.targetResolution = options.resolution; + resolution = animation.targetResolution; + } + if (options.rotation !== void 0) { + animation.sourceRotation = rotation; + const delta = modulo(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI; + animation.targetRotation = rotation + delta; + rotation = animation.targetRotation; + } + if (isNoopAnimation(animation)) { + animation.complete = true; + } else { + start += animation.duration; + } + series.push(animation); + } + this.animations_.push(series); + this.setHint(ViewHint.ANIMATING, 1); + this.updateAnimations_(); + } + /** + * Determine if the view is being animated. + * @return {boolean} The view is being animated. + * @api + */ + getAnimating() { + return this.hints_[ViewHint.ANIMATING] > 0; + } + /** + * Determine if the user is interacting with the view, such as panning or zooming. + * @return {boolean} The view is being interacted with. + * @api + */ + getInteracting() { + return this.hints_[ViewHint.INTERACTING] > 0; + } + /** + * Cancel any ongoing animations. + * @api + */ + cancelAnimations() { + this.setHint(ViewHint.ANIMATING, -this.hints_[ViewHint.ANIMATING]); + let anchor; + for (let i = 0, ii = this.animations_.length; i < ii; ++i) { + const series = this.animations_[i]; + if (series[0].callback) { + animationCallback(series[0].callback, false); + } + if (!anchor) { + for (let j = 0, jj = series.length; j < jj; ++j) { + const animation = series[j]; + if (!animation.complete) { + anchor = animation.anchor; + break; + } + } + } + } + this.animations_.length = 0; + this.cancelAnchor_ = anchor; + this.nextCenter_ = null; + this.nextResolution_ = NaN; + this.nextRotation_ = NaN; + } + /** + * Update all animations. + */ + updateAnimations_() { + if (this.updateAnimationKey_ !== void 0) { + cancelAnimationFrame(this.updateAnimationKey_); + this.updateAnimationKey_ = void 0; + } + if (!this.getAnimating()) { + return; + } + const now = Date.now(); + let more = false; + for (let i = this.animations_.length - 1; i >= 0; --i) { + const series = this.animations_[i]; + let seriesComplete = true; + for (let j = 0, jj = series.length; j < jj; ++j) { + const animation = series[j]; + if (animation.complete) { + continue; + } + const elapsed = now - animation.start; + let fraction = animation.duration > 0 ? elapsed / animation.duration : 1; + if (fraction >= 1) { + animation.complete = true; + fraction = 1; + } else { + seriesComplete = false; + } + const progress = animation.easing(fraction); + if (animation.sourceCenter) { + const x0 = animation.sourceCenter[0]; + const y0 = animation.sourceCenter[1]; + const x1 = animation.targetCenter[0]; + const y1 = animation.targetCenter[1]; + this.nextCenter_ = animation.targetCenter; + const x = x0 + progress * (x1 - x0); + const y = y0 + progress * (y1 - y0); + this.targetCenter_ = [x, y]; + } + if (animation.sourceResolution && animation.targetResolution) { + const resolution = progress === 1 ? animation.targetResolution : animation.sourceResolution + progress * (animation.targetResolution - animation.sourceResolution); + if (animation.anchor) { + const size = this.getViewportSize_(this.getRotation()); + const constrainedResolution = this.constraints_.resolution( + resolution, + 0, + size, + true + ); + this.targetCenter_ = this.calculateCenterZoom( + constrainedResolution, + animation.anchor + ); + } + this.nextResolution_ = animation.targetResolution; + this.targetResolution_ = resolution; + this.applyTargetState_(true); + } + if (animation.sourceRotation !== void 0 && animation.targetRotation !== void 0) { + const rotation = progress === 1 ? modulo(animation.targetRotation + Math.PI, 2 * Math.PI) - Math.PI : animation.sourceRotation + progress * (animation.targetRotation - animation.sourceRotation); + if (animation.anchor) { + const constrainedRotation = this.constraints_.rotation( + rotation, + true + ); + this.targetCenter_ = this.calculateCenterRotate( + constrainedRotation, + animation.anchor + ); + } + this.nextRotation_ = animation.targetRotation; + this.targetRotation_ = rotation; + } + this.applyTargetState_(true); + more = true; + if (!animation.complete) { + break; + } + } + if (seriesComplete) { + this.animations_[i] = null; + this.setHint(ViewHint.ANIMATING, -1); + this.nextCenter_ = null; + this.nextResolution_ = NaN; + this.nextRotation_ = NaN; + const callback = series[0].callback; + if (callback) { + animationCallback(callback, true); + } + } + } + this.animations_ = this.animations_.filter(Boolean); + if (more && this.updateAnimationKey_ === void 0) { + this.updateAnimationKey_ = requestAnimationFrame( + this.updateAnimations_.bind(this) + ); + } + } + /** + * @param {number} rotation Target rotation. + * @param {import("./coordinate.js").Coordinate} anchor Rotation anchor. + * @return {import("./coordinate.js").Coordinate|undefined} Center for rotation and anchor. + */ + calculateCenterRotate(rotation, anchor) { + let center; + const currentCenter = this.getCenterInternal(); + if (currentCenter !== void 0) { + center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]]; + rotate$1(center, rotation - this.getRotation()); + add(center, anchor); + } + return center; + } + /** + * @param {number} resolution Target resolution. + * @param {import("./coordinate.js").Coordinate} anchor Zoom anchor. + * @return {import("./coordinate.js").Coordinate|undefined} Center for resolution and anchor. + */ + calculateCenterZoom(resolution, anchor) { + let center; + const currentCenter = this.getCenterInternal(); + const currentResolution = this.getResolution(); + if (currentCenter !== void 0 && currentResolution !== void 0) { + const x = anchor[0] - resolution * (anchor[0] - currentCenter[0]) / currentResolution; + const y = anchor[1] - resolution * (anchor[1] - currentCenter[1]) / currentResolution; + center = [x, y]; + } + return center; + } + /** + * Returns the current viewport size. + * @private + * @param {number} [rotation] Take into account the rotation of the viewport when giving the size + * @return {import("./size.js").Size} Viewport size or `[100, 100]` when no viewport is found. + */ + getViewportSize_(rotation) { + const size = this.viewportSize_; + if (rotation) { + const w = size[0]; + const h = size[1]; + return [ + Math.abs(w * Math.cos(rotation)) + Math.abs(h * Math.sin(rotation)), + Math.abs(w * Math.sin(rotation)) + Math.abs(h * Math.cos(rotation)) + ]; + } + return size; + } + /** + * Stores the viewport size on the view. The viewport size is not read every time from the DOM + * to avoid performance hit and layout reflow. + * This should be done on map size change. + * Note: the constraints are not resolved during an animation to avoid stopping it + * @param {import("./size.js").Size} [size] Viewport size; if undefined, [100, 100] is assumed + */ + setViewportSize(size) { + this.viewportSize_ = Array.isArray(size) ? size.slice() : [100, 100]; + if (!this.getAnimating()) { + this.resolveConstraints(0); + } + } + /** + * Get the view center. + * @return {import("./coordinate.js").Coordinate|undefined} The center of the view. + * @observable + * @api + */ + getCenter() { + const center = this.getCenterInternal(); + if (!center) { + return center; + } + return toUserCoordinate(center, this.getProjection()); + } + /** + * Get the view center without transforming to user projection. + * @return {import("./coordinate.js").Coordinate|undefined} The center of the view. + */ + getCenterInternal() { + return ( + /** @type {import("./coordinate.js").Coordinate|undefined} */ + this.get(ViewProperty.CENTER) + ); + } + /** + * @return {Constraints} Constraints. + */ + getConstraints() { + return this.constraints_; + } + /** + * @return {boolean} Resolution constraint is set + */ + getConstrainResolution() { + return this.get("constrainResolution"); + } + /** + * @param {Array} [hints] Destination array. + * @return {Array} Hint. + */ + getHints(hints) { + if (hints !== void 0) { + hints[0] = this.hints_[0]; + hints[1] = this.hints_[1]; + return hints; + } + return this.hints_.slice(); + } + /** + * Calculate the extent for the current view state and the passed size. + * The size is the pixel dimensions of the box into which the calculated extent + * should fit. In most cases you want to get the extent of the entire map, + * that is `map.getSize()`. + * @param {import("./size.js").Size} [size] Box pixel size. If not provided, the size + * of the map that uses this view will be used. + * @return {import("./extent.js").Extent} Extent. + * @api + */ + calculateExtent(size) { + const extent = this.calculateExtentInternal(size); + return toUserExtent(extent, this.getProjection()); + } + /** + * @param {import("./size.js").Size} [size] Box pixel size. If not provided, + * the map's last known viewport size will be used. + * @return {import("./extent.js").Extent} Extent. + */ + calculateExtentInternal(size) { + size = size || this.getViewportSizeMinusPadding_(); + const center = ( + /** @type {!import("./coordinate.js").Coordinate} */ + this.getCenterInternal() + ); + assert(center, "The view center is not defined"); + const resolution = ( + /** @type {!number} */ + this.getResolution() + ); + assert(resolution !== void 0, "The view resolution is not defined"); + const rotation = ( + /** @type {!number} */ + this.getRotation() + ); + assert(rotation !== void 0, "The view rotation is not defined"); + return getForViewAndSize(center, resolution, rotation, size); + } + /** + * Get the maximum resolution of the view. + * @return {number} The maximum resolution of the view. + * @api + */ + getMaxResolution() { + return this.maxResolution_; + } + /** + * Get the minimum resolution of the view. + * @return {number} The minimum resolution of the view. + * @api + */ + getMinResolution() { + return this.minResolution_; + } + /** + * Get the maximum zoom level for the view. + * @return {number} The maximum zoom level. + * @api + */ + getMaxZoom() { + return ( + /** @type {number} */ + this.getZoomForResolution(this.minResolution_) + ); + } + /** + * Set a new maximum zoom level for the view. + * @param {number} zoom The maximum zoom level. + * @api + */ + setMaxZoom(zoom) { + this.applyOptions_(this.getUpdatedOptions_({ maxZoom: zoom })); + } + /** + * Get the minimum zoom level for the view. + * @return {number} The minimum zoom level. + * @api + */ + getMinZoom() { + return ( + /** @type {number} */ + this.getZoomForResolution(this.maxResolution_) + ); + } + /** + * Set a new minimum zoom level for the view. + * @param {number} zoom The minimum zoom level. + * @api + */ + setMinZoom(zoom) { + this.applyOptions_(this.getUpdatedOptions_({ minZoom: zoom })); + } + /** + * Set whether the view should allow intermediary zoom levels. + * @param {boolean} enabled Whether the resolution is constrained. + * @api + */ + setConstrainResolution(enabled) { + this.applyOptions_(this.getUpdatedOptions_({ constrainResolution: enabled })); + } + /** + * Get the view projection. + * @return {import("./proj/Projection.js").default} The projection of the view. + * @api + */ + getProjection() { + return this.projection_; + } + /** + * Get the view resolution. + * @return {number|undefined} The resolution of the view. + * @observable + * @api + */ + getResolution() { + return ( + /** @type {number|undefined} */ + this.get(ViewProperty.RESOLUTION) + ); + } + /** + * Get the resolutions for the view. This returns the array of resolutions + * passed to the constructor of the View, or undefined if none were given. + * @return {Array|undefined} The resolutions of the view. + * @api + */ + getResolutions() { + return this.resolutions_; + } + /** + * Get the resolution for a provided extent (in map units) and size (in pixels). + * @param {import("./extent.js").Extent} extent Extent. + * @param {import("./size.js").Size} [size] Box pixel size. + * @return {number} The resolution at which the provided extent will render at + * the given size. + * @api + */ + getResolutionForExtent(extent, size) { + return this.getResolutionForExtentInternal( + fromUserExtent(extent, this.getProjection()), + size + ); + } + /** + * Get the resolution for a provided extent (in map units) and size (in pixels). + * @param {import("./extent.js").Extent} extent Extent. + * @param {import("./size.js").Size} [size] Box pixel size. + * @return {number} The resolution at which the provided extent will render at + * the given size. + */ + getResolutionForExtentInternal(extent, size) { + size = size || this.getViewportSizeMinusPadding_(); + const xResolution = getWidth(extent) / size[0]; + const yResolution = getHeight(extent) / size[1]; + return Math.max(xResolution, yResolution); + } + /** + * Return a function that returns a value between 0 and 1 for a + * resolution. Exponential scaling is assumed. + * @param {number} [power] Power. + * @return {function(number): number} Resolution for value function. + */ + getResolutionForValueFunction(power) { + power = power || 2; + const maxResolution = this.getConstrainedResolution(this.maxResolution_); + const minResolution = this.minResolution_; + const max = Math.log(maxResolution / minResolution) / Math.log(power); + return ( + /** + * @param {number} value Value. + * @return {number} Resolution. + */ + function(value) { + const resolution = maxResolution / Math.pow(power, value * max); + return resolution; + } + ); + } + /** + * Get the view rotation. + * @return {number} The rotation of the view in radians. + * @observable + * @api + */ + getRotation() { + return ( + /** @type {number} */ + this.get(ViewProperty.ROTATION) + ); + } + /** + * Return a function that returns a resolution for a value between + * 0 and 1. Exponential scaling is assumed. + * @param {number} [power] Power. + * @return {function(number): number} Value for resolution function. + */ + getValueForResolutionFunction(power) { + const logPower = Math.log(power || 2); + const maxResolution = this.getConstrainedResolution(this.maxResolution_); + const minResolution = this.minResolution_; + const max = Math.log(maxResolution / minResolution) / logPower; + return ( + /** + * @param {number} resolution Resolution. + * @return {number} Value. + */ + function(resolution) { + const value = Math.log(maxResolution / resolution) / logPower / max; + return value; + } + ); + } + /** + * Returns the size of the viewport minus padding. + * @private + * @param {number} [rotation] Take into account the rotation of the viewport when giving the size + * @return {import("./size.js").Size} Viewport size reduced by the padding. + */ + getViewportSizeMinusPadding_(rotation) { + let size = this.getViewportSize_(rotation); + const padding = this.padding_; + if (padding) { + size = [ + size[0] - padding[1] - padding[3], + size[1] - padding[0] - padding[2] + ]; + } + return size; + } + /** + * @return {State} View state. + */ + getState() { + const projection = this.getProjection(); + const resolution = this.getResolution(); + const rotation = this.getRotation(); + let center = ( + /** @type {import("./coordinate.js").Coordinate} */ + this.getCenterInternal() + ); + const padding = this.padding_; + if (padding) { + const reducedSize = this.getViewportSizeMinusPadding_(); + center = calculateCenterOn( + center, + this.getViewportSize_(), + [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]], + resolution, + rotation + ); + } + return { + center: center.slice(0), + projection: projection !== void 0 ? projection : null, + resolution, + nextCenter: this.nextCenter_, + nextResolution: this.nextResolution_, + nextRotation: this.nextRotation_, + rotation, + zoom: this.getZoom() + }; + } + /** + * @return {ViewStateLayerStateExtent} Like `FrameState`, but just `viewState` and `extent`. + */ + getViewStateAndExtent() { + return { + viewState: this.getState(), + extent: this.calculateExtent() + }; + } + /** + * Get the current zoom level. This method may return non-integer zoom levels + * if the view does not constrain the resolution, or if an interaction or + * animation is underway. + * @return {number|undefined} Zoom. + * @api + */ + getZoom() { + let zoom; + const resolution = this.getResolution(); + if (resolution !== void 0) { + zoom = this.getZoomForResolution(resolution); + } + return zoom; + } + /** + * Get the zoom level for a resolution. + * @param {number} resolution The resolution. + * @return {number|undefined} The zoom level for the provided resolution. + * @api + */ + getZoomForResolution(resolution) { + let offset = this.minZoom_ || 0; + let max, zoomFactor; + if (this.resolutions_) { + const nearest = linearFindNearest(this.resolutions_, resolution, 1); + offset = nearest; + max = this.resolutions_[nearest]; + if (nearest == this.resolutions_.length - 1) { + zoomFactor = 2; + } else { + zoomFactor = max / this.resolutions_[nearest + 1]; + } + } else { + max = this.maxResolution_; + zoomFactor = this.zoomFactor_; + } + return offset + Math.log(max / resolution) / Math.log(zoomFactor); + } + /** + * Get the resolution for a zoom level. + * @param {number} zoom Zoom level. + * @return {number} The view resolution for the provided zoom level. + * @api + */ + getResolutionForZoom(zoom) { + if (this.resolutions_) { + if (this.resolutions_.length <= 1) { + return 0; + } + const baseLevel = clamp( + Math.floor(zoom), + 0, + this.resolutions_.length - 2 + ); + const zoomFactor = this.resolutions_[baseLevel] / this.resolutions_[baseLevel + 1]; + return this.resolutions_[baseLevel] / Math.pow(zoomFactor, clamp(zoom - baseLevel, 0, 1)); + } + return this.maxResolution_ / Math.pow(this.zoomFactor_, zoom - this.minZoom_); + } + /** + * Fit the given geometry or extent based on the given map size and border. + * The size is pixel dimensions of the box to fit the extent into. + * In most cases you will want to use the map size, that is `map.getSize()`. + * Takes care of the map angle. + * @param {import("./geom/SimpleGeometry.js").default|import("./extent.js").Extent} geometryOrExtent The geometry or + * extent to fit the view to. + * @param {FitOptions} [options] Options. + * @api + */ + fit(geometryOrExtent, options) { + let geometry; + assert( + Array.isArray(geometryOrExtent) || typeof /** @type {?} */ + geometryOrExtent.getSimplifiedGeometry === "function", + "Invalid extent or geometry provided as `geometry`" + ); + if (Array.isArray(geometryOrExtent)) { + assert( + !isEmpty(geometryOrExtent), + "Cannot fit empty extent provided as `geometry`" + ); + const extent = fromUserExtent(geometryOrExtent, this.getProjection()); + geometry = fromExtent(extent); + } else if (geometryOrExtent.getType() === "Circle") { + const extent = fromUserExtent( + geometryOrExtent.getExtent(), + this.getProjection() + ); + geometry = fromExtent(extent); + geometry.rotate(this.getRotation(), getCenter(extent)); + } else { + { + geometry = geometryOrExtent; + } + } + this.fitInternal(geometry, options); + } + /** + * Calculate rotated extent + * @param {import("./geom/SimpleGeometry.js").default} geometry The geometry. + * @return {import("./extent").Extent} The rotated extent for the geometry. + */ + rotatedExtentForGeometry(geometry) { + const rotation = this.getRotation(); + const cosAngle = Math.cos(rotation); + const sinAngle = Math.sin(-rotation); + const coords = geometry.getFlatCoordinates(); + const stride = geometry.getStride(); + let minRotX = Infinity; + let minRotY = Infinity; + let maxRotX = -Infinity; + let maxRotY = -Infinity; + for (let i = 0, ii = coords.length; i < ii; i += stride) { + const rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle; + const rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle; + minRotX = Math.min(minRotX, rotX); + minRotY = Math.min(minRotY, rotY); + maxRotX = Math.max(maxRotX, rotX); + maxRotY = Math.max(maxRotY, rotY); + } + return [minRotX, minRotY, maxRotX, maxRotY]; + } + /** + * @param {import("./geom/SimpleGeometry.js").default} geometry The geometry. + * @param {FitOptions} [options] Options. + */ + fitInternal(geometry, options) { + options = options || {}; + let size = options.size; + if (!size) { + size = this.getViewportSizeMinusPadding_(); + } + const padding = options.padding !== void 0 ? options.padding : [0, 0, 0, 0]; + const nearest = options.nearest !== void 0 ? options.nearest : false; + let minResolution; + if (options.minResolution !== void 0) { + minResolution = options.minResolution; + } else if (options.maxZoom !== void 0) { + minResolution = this.getResolutionForZoom(options.maxZoom); + } else { + minResolution = 0; + } + const rotatedExtent = this.rotatedExtentForGeometry(geometry); + let resolution = this.getResolutionForExtentInternal(rotatedExtent, [ + size[0] - padding[1] - padding[3], + size[1] - padding[0] - padding[2] + ]); + resolution = isNaN(resolution) ? minResolution : Math.max(resolution, minResolution); + resolution = this.getConstrainedResolution(resolution, nearest ? 0 : 1); + const rotation = this.getRotation(); + const sinAngle = Math.sin(rotation); + const cosAngle = Math.cos(rotation); + const centerRot = getCenter(rotatedExtent); + centerRot[0] += (padding[1] - padding[3]) / 2 * resolution; + centerRot[1] += (padding[0] - padding[2]) / 2 * resolution; + const centerX = centerRot[0] * cosAngle - centerRot[1] * sinAngle; + const centerY = centerRot[1] * cosAngle + centerRot[0] * sinAngle; + const center = this.getConstrainedCenter([centerX, centerY], resolution); + const callback = options.callback ? options.callback : VOID; + if (options.duration !== void 0) { + this.animateInternal( + { + resolution, + center, + duration: options.duration, + easing: options.easing + }, + callback + ); + } else { + this.targetResolution_ = resolution; + this.targetCenter_ = center; + this.applyTargetState_(false, true); + animationCallback(callback, true); + } + } + /** + * Center on coordinate and view position. + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("./size.js").Size} size Box pixel size. + * @param {import("./pixel.js").Pixel} position Position on the view to center on. + * @api + */ + centerOn(coordinate, size, position) { + this.centerOnInternal( + fromUserCoordinate(coordinate, this.getProjection()), + size, + position + ); + } + /** + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("./size.js").Size} size Box pixel size. + * @param {import("./pixel.js").Pixel} position Position on the view to center on. + */ + centerOnInternal(coordinate, size, position) { + this.setCenterInternal( + calculateCenterOn( + coordinate, + size, + position, + this.getResolution(), + this.getRotation() + ) + ); + } + /** + * Calculates the shift between map and viewport center. + * @param {import("./coordinate.js").Coordinate} center Center. + * @param {number} resolution Resolution. + * @param {number} rotation Rotation. + * @param {import("./size.js").Size} size Size. + * @return {Array|undefined} Center shift. + */ + calculateCenterShift(center, resolution, rotation, size) { + let centerShift; + const padding = this.padding_; + if (padding && center) { + const reducedSize = this.getViewportSizeMinusPadding_(-rotation); + const shiftedCenter = calculateCenterOn( + center, + size, + [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]], + resolution, + rotation + ); + centerShift = [ + center[0] - shiftedCenter[0], + center[1] - shiftedCenter[1] + ]; + } + return centerShift; + } + /** + * @return {boolean} Is defined. + */ + isDef() { + return !!this.getCenterInternal() && this.getResolution() !== void 0; + } + /** + * Adds relative coordinates to the center of the view. Any extent constraint will apply. + * @param {import("./coordinate.js").Coordinate} deltaCoordinates Relative value to add. + * @api + */ + adjustCenter(deltaCoordinates) { + const center = toUserCoordinate(this.targetCenter_, this.getProjection()); + this.setCenter([ + center[0] + deltaCoordinates[0], + center[1] + deltaCoordinates[1] + ]); + } + /** + * Adds relative coordinates to the center of the view. Any extent constraint will apply. + * @param {import("./coordinate.js").Coordinate} deltaCoordinates Relative value to add. + */ + adjustCenterInternal(deltaCoordinates) { + const center = this.targetCenter_; + this.setCenterInternal([ + center[0] + deltaCoordinates[0], + center[1] + deltaCoordinates[1] + ]); + } + /** + * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution + * constraint will apply. + * @param {number} ratio The ratio to apply on the view resolution. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + * @api + */ + adjustResolution(ratio, anchor) { + anchor = anchor && fromUserCoordinate(anchor, this.getProjection()); + this.adjustResolutionInternal(ratio, anchor); + } + /** + * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution + * constraint will apply. + * @param {number} ratio The ratio to apply on the view resolution. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + */ + adjustResolutionInternal(ratio, anchor) { + const isMoving = this.getAnimating() || this.getInteracting(); + const size = this.getViewportSize_(this.getRotation()); + const newResolution = this.constraints_.resolution( + this.targetResolution_ * ratio, + 0, + size, + isMoving + ); + if (anchor) { + this.targetCenter_ = this.calculateCenterZoom(newResolution, anchor); + } + this.targetResolution_ *= ratio; + this.applyTargetState_(); + } + /** + * Adds a value to the view zoom level, optionally using an anchor. Any resolution + * constraint will apply. + * @param {number} delta Relative value to add to the zoom level. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + * @api + */ + adjustZoom(delta, anchor) { + this.adjustResolution(Math.pow(this.zoomFactor_, -delta), anchor); + } + /** + * Adds a value to the view rotation, optionally using an anchor. Any rotation + * constraint will apply. + * @param {number} delta Relative value to add to the zoom rotation, in radians. + * @param {import("./coordinate.js").Coordinate} [anchor] The rotation center. + * @api + */ + adjustRotation(delta, anchor) { + if (anchor) { + anchor = fromUserCoordinate(anchor, this.getProjection()); + } + this.adjustRotationInternal(delta, anchor); + } + /** + * @param {number} delta Relative value to add to the zoom rotation, in radians. + * @param {import("./coordinate.js").Coordinate} [anchor] The rotation center. + */ + adjustRotationInternal(delta, anchor) { + const isMoving = this.getAnimating() || this.getInteracting(); + const newRotation = this.constraints_.rotation( + this.targetRotation_ + delta, + isMoving + ); + if (anchor) { + this.targetCenter_ = this.calculateCenterRotate(newRotation, anchor); + } + this.targetRotation_ += delta; + this.applyTargetState_(); + } + /** + * Set the center of the current view. Any extent constraint will apply. + * @param {import("./coordinate.js").Coordinate|undefined} center The center of the view. + * @observable + * @api + */ + setCenter(center) { + this.setCenterInternal( + center ? fromUserCoordinate(center, this.getProjection()) : center + ); + } + /** + * Set the center using the view projection (not the user projection). + * @param {import("./coordinate.js").Coordinate|undefined} center The center of the view. + */ + setCenterInternal(center) { + this.targetCenter_ = center; + this.applyTargetState_(); + } + /** + * @param {import("./ViewHint.js").default} hint Hint. + * @param {number} delta Delta. + * @return {number} New value. + */ + setHint(hint, delta) { + this.hints_[hint] += delta; + this.changed(); + return this.hints_[hint]; + } + /** + * Set the resolution for this view. Any resolution constraint will apply. + * @param {number|undefined} resolution The resolution of the view. + * @observable + * @api + */ + setResolution(resolution) { + this.targetResolution_ = resolution; + this.applyTargetState_(); + } + /** + * Set the rotation for this view. Any rotation constraint will apply. + * @param {number} rotation The rotation of the view in radians. + * @observable + * @api + */ + setRotation(rotation) { + this.targetRotation_ = rotation; + this.applyTargetState_(); + } + /** + * Zoom to a specific zoom level. Any resolution constrain will apply. + * @param {number} zoom Zoom level. + * @api + */ + setZoom(zoom) { + this.setResolution(this.getResolutionForZoom(zoom)); + } + /** + * Recompute rotation/resolution/center based on target values. + * Note: we have to compute rotation first, then resolution and center considering that + * parameters can influence one another in case a view extent constraint is present. + * @param {boolean} [doNotCancelAnims] Do not cancel animations. + * @param {boolean} [forceMoving] Apply constraints as if the view is moving. + * @private + */ + applyTargetState_(doNotCancelAnims, forceMoving) { + const isMoving = this.getAnimating() || this.getInteracting() || forceMoving; + const newRotation = this.constraints_.rotation( + this.targetRotation_, + isMoving + ); + const size = this.getViewportSize_(newRotation); + const newResolution = this.constraints_.resolution( + this.targetResolution_, + 0, + size, + isMoving + ); + const newCenter = this.constraints_.center( + this.targetCenter_, + newResolution, + size, + isMoving, + this.calculateCenterShift( + this.targetCenter_, + newResolution, + newRotation, + size + ) + ); + if (this.get(ViewProperty.ROTATION) !== newRotation) { + this.set(ViewProperty.ROTATION, newRotation); + } + if (this.get(ViewProperty.RESOLUTION) !== newResolution) { + this.set(ViewProperty.RESOLUTION, newResolution); + this.set("zoom", this.getZoom(), true); + } + if (!newCenter || !this.get(ViewProperty.CENTER) || !equals(this.get(ViewProperty.CENTER), newCenter)) { + this.set(ViewProperty.CENTER, newCenter); + } + if (this.getAnimating() && !doNotCancelAnims) { + this.cancelAnimations(); + } + this.cancelAnchor_ = void 0; + } + /** + * If any constraints need to be applied, an animation will be triggered. + * This is typically done on interaction end. + * Note: calling this with a duration of 0 will apply the constrained values straight away, + * without animation. + * @param {number} [duration] The animation duration in ms. + * @param {number} [resolutionDirection] Which direction to zoom. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + */ + resolveConstraints(duration, resolutionDirection, anchor) { + duration = duration !== void 0 ? duration : 200; + const direction = resolutionDirection || 0; + const newRotation = this.constraints_.rotation(this.targetRotation_); + const size = this.getViewportSize_(newRotation); + const newResolution = this.constraints_.resolution( + this.targetResolution_, + direction, + size + ); + const newCenter = this.constraints_.center( + this.targetCenter_, + newResolution, + size, + false, + this.calculateCenterShift( + this.targetCenter_, + newResolution, + newRotation, + size + ) + ); + if (duration === 0 && !this.cancelAnchor_) { + this.targetResolution_ = newResolution; + this.targetRotation_ = newRotation; + this.targetCenter_ = newCenter; + this.applyTargetState_(); + return; + } + anchor = anchor || (duration === 0 ? this.cancelAnchor_ : void 0); + this.cancelAnchor_ = void 0; + if (this.getResolution() !== newResolution || this.getRotation() !== newRotation || !this.getCenterInternal() || !equals(this.getCenterInternal(), newCenter)) { + if (this.getAnimating()) { + this.cancelAnimations(); + } + this.animateInternal({ + rotation: newRotation, + center: newCenter, + resolution: newResolution, + duration, + easing: easeOut, + anchor + }); + } + } + /** + * Notify the View that an interaction has started. + * The view state will be resolved to a stable one if needed + * (depending on its constraints). + * @api + */ + beginInteraction() { + this.resolveConstraints(0); + this.setHint(ViewHint.INTERACTING, 1); + } + /** + * Notify the View that an interaction has ended. The view state will be resolved + * to a stable one if needed (depending on its constraints). + * @param {number} [duration] Animation duration in ms. + * @param {number} [resolutionDirection] Which direction to zoom. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + * @api + */ + endInteraction(duration, resolutionDirection, anchor) { + anchor = anchor && fromUserCoordinate(anchor, this.getProjection()); + this.endInteractionInternal(duration, resolutionDirection, anchor); + } + /** + * Notify the View that an interaction has ended. The view state will be resolved + * to a stable one if needed (depending on its constraints). + * @param {number} [duration] Animation duration in ms. + * @param {number} [resolutionDirection] Which direction to zoom. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + */ + endInteractionInternal(duration, resolutionDirection, anchor) { + if (!this.getInteracting()) { + return; + } + this.setHint(ViewHint.INTERACTING, -1); + this.resolveConstraints(duration, resolutionDirection, anchor); + } + /** + * Get a valid position for the view center according to the current constraints. + * @param {import("./coordinate.js").Coordinate|undefined} targetCenter Target center position. + * @param {number} [targetResolution] Target resolution. If not supplied, the current one will be used. + * This is useful to guess a valid center position at a different zoom level. + * @return {import("./coordinate.js").Coordinate|undefined} Valid center position. + */ + getConstrainedCenter(targetCenter, targetResolution) { + const size = this.getViewportSize_(this.getRotation()); + return this.constraints_.center( + targetCenter, + targetResolution || this.getResolution(), + size + ); + } + /** + * Get a valid zoom level according to the current view constraints. + * @param {number|undefined} targetZoom Target zoom. + * @param {number} [direction=0] Indicate which resolution should be used + * by a renderer if the view resolution does not match any resolution of the tile source. + * If 0, the nearest resolution will be used. If 1, the nearest lower resolution + * will be used. If -1, the nearest higher resolution will be used. + * @return {number|undefined} Valid zoom level. + */ + getConstrainedZoom(targetZoom, direction) { + const targetRes = this.getResolutionForZoom(targetZoom); + return this.getZoomForResolution( + this.getConstrainedResolution(targetRes, direction) + ); + } + /** + * Get a valid resolution according to the current view constraints. + * @param {number|undefined} targetResolution Target resolution. + * @param {number} [direction=0] Indicate which resolution should be used + * by a renderer if the view resolution does not match any resolution of the tile source. + * If 0, the nearest resolution will be used. If 1, the nearest lower resolution + * will be used. If -1, the nearest higher resolution will be used. + * @return {number|undefined} Valid resolution. + */ + getConstrainedResolution(targetResolution, direction) { + direction = direction || 0; + const size = this.getViewportSize_(this.getRotation()); + return this.constraints_.resolution(targetResolution, direction, size); + } +} +function animationCallback(callback, returnValue) { + setTimeout(function() { + callback(returnValue); + }, 0); +} +function createCenterConstraint(options) { + if (options.extent !== void 0) { + const smooth = options.smoothExtentConstraint !== void 0 ? options.smoothExtentConstraint : true; + return createExtent(options.extent, options.constrainOnlyCenter, smooth); + } + const projection = createProjection(options.projection, "EPSG:3857"); + if (options.multiWorld !== true && projection.isGlobal()) { + const extent = projection.getExtent().slice(); + extent[0] = -Infinity; + extent[2] = Infinity; + return createExtent(extent, false, false); + } + return none$1; +} +function createResolutionConstraint(options) { + let resolutionConstraint; + let maxResolution; + let minResolution; + const defaultMaxZoom = 28; + const defaultZoomFactor = 2; + let minZoom = options.minZoom !== void 0 ? options.minZoom : DEFAULT_MIN_ZOOM; + let maxZoom = options.maxZoom !== void 0 ? options.maxZoom : defaultMaxZoom; + const zoomFactor = options.zoomFactor !== void 0 ? options.zoomFactor : defaultZoomFactor; + const multiWorld = options.multiWorld !== void 0 ? options.multiWorld : false; + const smooth = options.smoothResolutionConstraint !== void 0 ? options.smoothResolutionConstraint : true; + const showFullExtent = options.showFullExtent !== void 0 ? options.showFullExtent : false; + const projection = createProjection(options.projection, "EPSG:3857"); + const projExtent = projection.getExtent(); + let constrainOnlyCenter = options.constrainOnlyCenter; + let extent = options.extent; + if (!multiWorld && !extent && projection.isGlobal()) { + constrainOnlyCenter = false; + extent = projExtent; + } + if (options.resolutions !== void 0) { + const resolutions = options.resolutions; + maxResolution = resolutions[minZoom]; + minResolution = resolutions[maxZoom] !== void 0 ? resolutions[maxZoom] : resolutions[resolutions.length - 1]; + if (options.constrainResolution) { + resolutionConstraint = createSnapToResolutions( + resolutions, + smooth, + !constrainOnlyCenter && extent, + showFullExtent + ); + } else { + resolutionConstraint = createMinMaxResolution( + maxResolution, + minResolution, + smooth, + !constrainOnlyCenter && extent, + showFullExtent + ); + } + } else { + const size = !projExtent ? ( + // use an extent that can fit the whole world if need be + 360 * METERS_PER_UNIT$1.degrees / projection.getMetersPerUnit() + ) : Math.max(getWidth(projExtent), getHeight(projExtent)); + const defaultMaxResolution = size / DEFAULT_TILE_SIZE / Math.pow(defaultZoomFactor, DEFAULT_MIN_ZOOM); + const defaultMinResolution = defaultMaxResolution / Math.pow(defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM); + maxResolution = options.maxResolution; + if (maxResolution !== void 0) { + minZoom = 0; + } else { + maxResolution = defaultMaxResolution / Math.pow(zoomFactor, minZoom); + } + minResolution = options.minResolution; + if (minResolution === void 0) { + if (options.maxZoom !== void 0) { + if (options.maxResolution !== void 0) { + minResolution = maxResolution / Math.pow(zoomFactor, maxZoom); + } else { + minResolution = defaultMaxResolution / Math.pow(zoomFactor, maxZoom); + } + } else { + minResolution = defaultMinResolution; + } + } + maxZoom = minZoom + Math.floor( + Math.log(maxResolution / minResolution) / Math.log(zoomFactor) + ); + minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom); + if (options.constrainResolution) { + resolutionConstraint = createSnapToPower( + zoomFactor, + maxResolution, + minResolution, + smooth, + !constrainOnlyCenter && extent, + showFullExtent + ); + } else { + resolutionConstraint = createMinMaxResolution( + maxResolution, + minResolution, + smooth, + !constrainOnlyCenter && extent, + showFullExtent + ); + } + } + return { + constraint: resolutionConstraint, + maxResolution, + minResolution, + minZoom, + zoomFactor + }; +} +function createRotationConstraint(options) { + const enableRotation = options.enableRotation !== void 0 ? options.enableRotation : true; + if (enableRotation) { + const constrainRotation = options.constrainRotation; + if (constrainRotation === void 0 || constrainRotation === true) { + return createSnapToZero(); + } + if (constrainRotation === false) { + return none; + } + if (typeof constrainRotation === "number") { + return createSnapToN(constrainRotation); + } + return none; + } + return disable; +} +function isNoopAnimation(animation) { + if (animation.sourceCenter && animation.targetCenter) { + if (!equals(animation.sourceCenter, animation.targetCenter)) { + return false; + } + } + if (animation.sourceResolution !== animation.targetResolution) { + return false; + } + if (animation.sourceRotation !== animation.targetRotation) { + return false; + } + return true; +} +function calculateCenterOn(coordinate, size, position, resolution, rotation) { + const cosAngle = Math.cos(-rotation); + let sinAngle = Math.sin(-rotation); + let rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle; + let rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle; + rotX += (size[0] / 2 - position[0]) * resolution; + rotY += (position[1] - size[1] / 2) * resolution; + sinAngle = -sinAngle; + const centerX = rotX * cosAngle - rotY * sinAngle; + const centerY = rotY * cosAngle + rotX * sinAngle; + return [centerX, centerY]; +} +const OlView = View; +class Layer extends BaseLayer$1 { + /** + * @param {Options} options Layer options. + */ + constructor(options) { + const baseOptions = Object.assign({}, options); + delete baseOptions.source; + super(baseOptions); + this.on; + this.once; + this.un; + this.mapPrecomposeKey_ = null; + this.mapRenderKey_ = null; + this.sourceChangeKey_ = null; + this.renderer_ = null; + this.sourceReady_ = false; + this.rendered = false; + if (options.render) { + this.render = options.render; + } + if (options.map) { + this.setMap(options.map); + } + this.addChangeListener( + LayerProperty.SOURCE, + this.handleSourcePropertyChange_ + ); + const source = options.source ? ( + /** @type {SourceType} */ + options.source + ) : null; + this.setSource(source); + } + /** + * @param {Array} [array] Array of layers (to be modified in place). + * @return {Array} Array of layers. + */ + getLayersArray(array) { + array = array ? array : []; + array.push(this); + return array; + } + /** + * @param {Array} [states] Optional list of layer states (to be modified in place). + * @return {Array} List of layer states. + */ + getLayerStatesArray(states) { + states = states ? states : []; + states.push(this.getLayerState()); + return states; + } + /** + * Get the layer source. + * @return {SourceType|null} The layer source (or `null` if not yet set). + * @observable + * @api + */ + getSource() { + return ( + /** @type {SourceType} */ + this.get(LayerProperty.SOURCE) || null + ); + } + /** + * @return {SourceType|null} The source being rendered. + */ + getRenderSource() { + return this.getSource(); + } + /** + * @return {import("../source/Source.js").State} Source state. + */ + getSourceState() { + const source = this.getSource(); + return !source ? "undefined" : source.getState(); + } + /** + * @private + */ + handleSourceChange_() { + this.changed(); + if (this.sourceReady_ || this.getSource().getState() !== "ready") { + return; + } + this.sourceReady_ = true; + this.dispatchEvent("sourceready"); + } + /** + * @private + */ + handleSourcePropertyChange_() { + if (this.sourceChangeKey_) { + unlistenByKey(this.sourceChangeKey_); + this.sourceChangeKey_ = null; + } + this.sourceReady_ = false; + const source = this.getSource(); + if (source) { + this.sourceChangeKey_ = listen( + source, + EventType.CHANGE, + this.handleSourceChange_, + this + ); + if (source.getState() === "ready") { + this.sourceReady_ = true; + setTimeout(() => { + this.dispatchEvent("sourceready"); + }, 0); + } + } + this.changed(); + } + /** + * @param {import("../pixel").Pixel} pixel Pixel. + * @return {Promise>} Promise that resolves with + * an array of features. + */ + getFeatures(pixel) { + if (!this.renderer_) { + return Promise.resolve([]); + } + return this.renderer_.getFeatures(pixel); + } + /** + * @param {import("../pixel").Pixel} pixel Pixel. + * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data. + */ + getData(pixel) { + if (!this.renderer_ || !this.rendered) { + return null; + } + return this.renderer_.getData(pixel); + } + /** + * The layer is visible on the map view, i.e. within its min/max resolution or zoom and + * extent, not set to `visible: false`, and not inside a layer group that is set + * to `visible: false`. + * @param {View|import("../View.js").ViewStateLayerStateExtent} [view] View or {@link import("../Map.js").FrameState}. + * Only required when the layer is not added to a map. + * @return {boolean} The layer is visible in the map view. + * @api + */ + isVisible(view) { + let frameState; + const map = this.getMapInternal(); + if (!view && map) { + view = map.getView(); + } + if (view instanceof OlView) { + frameState = { + viewState: view.getState(), + extent: view.calculateExtent() + }; + } else { + frameState = view; + } + if (!frameState.layerStatesArray && map) { + frameState.layerStatesArray = map.getLayerGroup().getLayerStatesArray(); + } + let layerState; + if (frameState.layerStatesArray) { + layerState = frameState.layerStatesArray.find( + (layerState2) => layerState2.layer === this + ); + } else { + layerState = this.getLayerState(); + } + const layerExtent = this.getExtent(); + return inView(layerState, frameState.viewState) && (!layerExtent || intersects$1(layerExtent, frameState.extent)); + } + /** + * Get the attributions of the source of this layer for the given view. + * @param {View|import("../View.js").ViewStateLayerStateExtent} [view] View or {@link import("../Map.js").FrameState}. + * Only required when the layer is not added to a map. + * @return {Array} Attributions for this layer at the given view. + * @api + */ + getAttributions(view) { + if (!this.isVisible(view)) { + return []; + } + let getAttributions; + const source = this.getSource(); + if (source) { + getAttributions = source.getAttributions(); + } + if (!getAttributions) { + return []; + } + const frameState = view instanceof OlView ? view.getViewStateAndExtent() : view; + let attributions = getAttributions(frameState); + if (!Array.isArray(attributions)) { + attributions = [attributions]; + } + return attributions; + } + /** + * In charge to manage the rendering of the layer. One layer type is + * bounded with one layer renderer. + * @param {?import("../Map.js").FrameState} frameState Frame state. + * @param {HTMLElement} target Target which the renderer may (but need not) use + * for rendering its content. + * @return {HTMLElement|null} The rendered element. + */ + render(frameState, target) { + const layerRenderer = this.getRenderer(); + if (layerRenderer.prepareFrame(frameState)) { + this.rendered = true; + return layerRenderer.renderFrame(frameState, target); + } + return null; + } + /** + * Called when a layer is not visible during a map render. + */ + unrender() { + this.rendered = false; + } + /** + * For use inside the library only. + * @param {import("../Map.js").default|null} map Map. + */ + setMapInternal(map) { + if (!map) { + this.unrender(); + } + this.set(LayerProperty.MAP, map); + } + /** + * For use inside the library only. + * @return {import("../Map.js").default|null} Map. + */ + getMapInternal() { + return this.get(LayerProperty.MAP); + } + /** + * Sets the layer to be rendered on top of other layers on a map. The map will + * not manage this layer in its layers collection. This + * is useful for temporary layers. To remove an unmanaged layer from the map, + * use `#setMap(null)`. + * + * To add the layer to a map and have it managed by the map, use + * {@link module:ol/Map~Map#addLayer} instead. + * @param {import("../Map.js").default|null} map Map. + * @api + */ + setMap(map) { + if (this.mapPrecomposeKey_) { + unlistenByKey(this.mapPrecomposeKey_); + this.mapPrecomposeKey_ = null; + } + if (!map) { + this.changed(); + } + if (this.mapRenderKey_) { + unlistenByKey(this.mapRenderKey_); + this.mapRenderKey_ = null; + } + if (map) { + this.mapPrecomposeKey_ = listen( + map, + RenderEventType.PRECOMPOSE, + function(evt) { + const renderEvent = ( + /** @type {import("../render/Event.js").default} */ + evt + ); + const layerStatesArray = renderEvent.frameState.layerStatesArray; + const layerState = this.getLayerState(false); + assert( + !layerStatesArray.some(function(arrayLayerState) { + return arrayLayerState.layer === layerState.layer; + }), + "A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both." + ); + layerStatesArray.push(layerState); + }, + this + ); + this.mapRenderKey_ = listen(this, EventType.CHANGE, map.render, map); + this.changed(); + } + } + /** + * Set the layer source. + * @param {SourceType|null} source The layer source. + * @observable + * @api + */ + setSource(source) { + this.set(LayerProperty.SOURCE, source); + } + /** + * Get the renderer for this layer. + * @return {RendererType|null} The layer renderer. + */ + getRenderer() { + if (!this.renderer_) { + this.renderer_ = this.createRenderer(); + } + return this.renderer_; + } + /** + * @return {boolean} The layer has a renderer. + */ + hasRenderer() { + return !!this.renderer_; + } + /** + * Create a renderer for this layer. + * @return {RendererType} A layer renderer. + * @protected + */ + createRenderer() { + return null; + } + /** + * Clean up. + */ + disposeInternal() { + if (this.renderer_) { + this.renderer_.dispose(); + delete this.renderer_; + } + this.setSource(null); + super.disposeInternal(); + } +} +function inView(layerState, viewState) { + if (!layerState.visible) { + return false; + } + const resolution = viewState.resolution; + if (resolution < layerState.minResolution || resolution >= layerState.maxResolution) { + return false; + } + const zoom = viewState.zoom; + return zoom > layerState.minZoom && zoom <= layerState.maxZoom; +} +const Layer$1 = Layer; +class MapRenderer extends Disposable$1 { + /** + * @param {import("../Map.js").default} map Map. + */ + constructor(map) { + super(); + this.map_ = map; + } + /** + * @abstract + * @param {import("../render/EventType.js").default} type Event type. + * @param {import("../Map.js").FrameState} frameState Frame state. + */ + dispatchRenderEvent(type, frameState) { + abstract(); + } + /** + * @param {import("../Map.js").FrameState} frameState FrameState. + * @protected + */ + calculateMatrices2D(frameState) { + const viewState = frameState.viewState; + const coordinateToPixelTransform = frameState.coordinateToPixelTransform; + const pixelToCoordinateTransform = frameState.pixelToCoordinateTransform; + compose( + coordinateToPixelTransform, + frameState.size[0] / 2, + frameState.size[1] / 2, + 1 / viewState.resolution, + -1 / viewState.resolution, + -viewState.rotation, + -viewState.center[0], + -viewState.center[1] + ); + makeInverse(pixelToCoordinateTransform, coordinateToPixelTransform); + } + /** + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("../Map.js").FrameState} frameState FrameState. + * @param {number} hitTolerance Hit tolerance in pixels. + * @param {boolean} checkWrapped Check for wrapped geometries. + * @param {import("./vector.js").FeatureCallback} callback Feature callback. + * @param {S} thisArg Value to use as `this` when executing `callback`. + * @param {function(this: U, import("../layer/Layer.js").default): boolean} layerFilter Layer filter + * function, only layers which are visible and for which this function + * returns `true` will be tested for features. By default, all visible + * layers will be tested. + * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`. + * @return {T|undefined} Callback result. + * @template S,T,U + */ + forEachFeatureAtCoordinate(coordinate, frameState, hitTolerance, checkWrapped, callback, thisArg, layerFilter, thisArg2) { + let result; + const viewState = frameState.viewState; + function forEachFeatureAtCoordinate(managed, feature, layer, geometry) { + return callback.call(thisArg, feature, managed ? layer : null, geometry); + } + const projection = viewState.projection; + const translatedCoordinate = wrapX$1(coordinate.slice(), projection); + const offsets = [[0, 0]]; + if (projection.canWrapX() && checkWrapped) { + const projectionExtent = projection.getExtent(); + const worldWidth = getWidth(projectionExtent); + offsets.push([-worldWidth, 0], [worldWidth, 0]); + } + const layerStates = frameState.layerStatesArray; + const numLayers = layerStates.length; + const matches = ( + /** @type {Array>} */ + [] + ); + const tmpCoord = []; + for (let i = 0; i < offsets.length; i++) { + for (let j = numLayers - 1; j >= 0; --j) { + const layerState = layerStates[j]; + const layer = layerState.layer; + if (layer.hasRenderer() && inView(layerState, viewState) && layerFilter.call(thisArg2, layer)) { + const layerRenderer = layer.getRenderer(); + const source = layer.getSource(); + if (layerRenderer && source) { + const coordinates2 = source.getWrapX() ? translatedCoordinate : coordinate; + const callback2 = forEachFeatureAtCoordinate.bind( + null, + layerState.managed + ); + tmpCoord[0] = coordinates2[0] + offsets[i][0]; + tmpCoord[1] = coordinates2[1] + offsets[i][1]; + result = layerRenderer.forEachFeatureAtCoordinate( + tmpCoord, + frameState, + hitTolerance, + callback2, + matches + ); + } + if (result) { + return result; + } + } + } + } + if (matches.length === 0) { + return void 0; + } + const order = 1 / matches.length; + matches.forEach((m, i) => m.distanceSq += i * order); + matches.sort((a, b) => a.distanceSq - b.distanceSq); + matches.some((m) => { + return result = m.callback(m.feature, m.layer, m.geometry); + }); + return result; + } + /** + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("../Map.js").FrameState} frameState FrameState. + * @param {number} hitTolerance Hit tolerance in pixels. + * @param {boolean} checkWrapped Check for wrapped geometries. + * @param {function(this: U, import("../layer/Layer.js").default): boolean} layerFilter Layer filter + * function, only layers which are visible and for which this function + * returns `true` will be tested for features. By default, all visible + * layers will be tested. + * @param {U} thisArg Value to use as `this` when executing `layerFilter`. + * @return {boolean} Is there a feature at the given coordinate? + * @template U + */ + hasFeatureAtCoordinate(coordinate, frameState, hitTolerance, checkWrapped, layerFilter, thisArg) { + const hasFeature = this.forEachFeatureAtCoordinate( + coordinate, + frameState, + hitTolerance, + checkWrapped, + TRUE, + this, + layerFilter, + thisArg + ); + return hasFeature !== void 0; + } + /** + * @return {import("../Map.js").default} Map. + */ + getMap() { + return this.map_; + } + /** + * Render. + * @abstract + * @param {?import("../Map.js").FrameState} frameState Frame state. + */ + renderFrame(frameState) { + abstract(); + } + /** + * @param {import("../Map.js").FrameState} frameState Frame state. + */ + flushDeclutterItems(frameState) { + } + /** + * @param {import("../Map.js").FrameState} frameState Frame state. + * @protected + */ + scheduleExpireIconCache(frameState) { + if (shared.canExpireCache()) { + frameState.postRenderFunctions.push(expireIconCache); + } + } +} +function expireIconCache(map, frameState) { + shared.expire(); +} +const MapRenderer$1 = MapRenderer; +class RenderEvent extends Event { + /** + * @param {import("./EventType.js").default} type Type. + * @param {import("../transform.js").Transform} [inversePixelTransform] Transform for + * CSS pixels to rendered pixels. + * @param {import("../Map.js").FrameState} [frameState] Frame state. + * @param {?(CanvasRenderingContext2D|WebGLRenderingContext)} [context] Context. + */ + constructor(type, inversePixelTransform, frameState, context) { + super(type); + this.inversePixelTransform = inversePixelTransform; + this.frameState = frameState; + this.context = context; + } +} +const RenderEvent$1 = RenderEvent; +const CLASS_HIDDEN = "ol-hidden"; +const CLASS_SELECTABLE = "ol-selectable"; +const CLASS_UNSELECTABLE = "ol-unselectable"; +const CLASS_CONTROL = "ol-control"; +const CLASS_COLLAPSED = "ol-collapsed"; +const fontRegEx = new RegExp( + [ + "^\\s*(?=(?:(?:[-a-z]+\\s*){0,2}(italic|oblique))?)", + "(?=(?:(?:[-a-z]+\\s*){0,2}(small-caps))?)", + "(?=(?:(?:[-a-z]+\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)", + "(?:(?:normal|\\1|\\2|\\3)\\s*){0,3}((?:xx?-)?", + "(?:small|large)|medium|smaller|larger|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx]))", + "(?:\\s*\\/\\s*(normal|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx])?))", + `?\\s*([-,\\"\\'\\sa-z]+?)\\s*$` + ].join(""), + "i" +); +const fontRegExMatchIndex = [ + "style", + "variant", + "weight", + "size", + "lineHeight", + "family" +]; +const getFontParameters = function(fontSpec) { + const match = fontSpec.match(fontRegEx); + if (!match) { + return null; + } + const style = ( + /** @type {FontParameters} */ + { + lineHeight: "normal", + size: "1.2em", + style: "normal", + weight: "normal", + variant: "normal" + } + ); + for (let i = 0, ii = fontRegExMatchIndex.length; i < ii; ++i) { + const value = match[i + 1]; + if (value !== void 0) { + style[fontRegExMatchIndex[i]] = value; + } + } + style.families = style.family.split(/,\s?/); + return style; +}; +function createCanvasContext2D(width, height, canvasPool2, settings) { + let canvas; + if (canvasPool2 && canvasPool2.length) { + canvas = canvasPool2.shift(); + } else if (WORKER_OFFSCREEN_CANVAS) { + canvas = new OffscreenCanvas(width || 300, height || 300); + } else { + canvas = document.createElement("canvas"); + } + if (width) { + canvas.width = width; + } + if (height) { + canvas.height = height; + } + return ( + /** @type {CanvasRenderingContext2D} */ + canvas.getContext("2d", settings) + ); +} +function releaseCanvas(context) { + const canvas = context.canvas; + canvas.width = 1; + canvas.height = 1; + context.clearRect(0, 0, 1, 1); +} +function outerWidth(element) { + let width = element.offsetWidth; + const style = getComputedStyle(element); + width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10); + return width; +} +function outerHeight(element) { + let height = element.offsetHeight; + const style = getComputedStyle(element); + height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10); + return height; +} +function replaceNode(newNode, oldNode) { + const parent = oldNode.parentNode; + if (parent) { + parent.replaceChild(newNode, oldNode); + } +} +function removeNode(node) { + return node && node.parentNode ? node.parentNode.removeChild(node) : null; +} +function removeChildren(node) { + while (node.lastChild) { + node.removeChild(node.lastChild); + } +} +function replaceChildren(node, children) { + const oldChildren = node.childNodes; + for (let i = 0; true; ++i) { + const oldChild = oldChildren[i]; + const newChild = children[i]; + if (!oldChild && !newChild) { + break; + } + if (oldChild === newChild) { + continue; + } + if (!oldChild) { + node.appendChild(newChild); + continue; + } + if (!newChild) { + node.removeChild(oldChild); + --i; + continue; + } + node.insertBefore(newChild, oldChild); + } +} +const defaultFont = "10px sans-serif"; +const defaultFillStyle = "#000"; +const defaultLineCap = "round"; +const defaultLineDash = []; +const defaultLineDashOffset = 0; +const defaultLineJoin = "round"; +const defaultMiterLimit = 10; +const defaultStrokeStyle = "#000"; +const defaultTextAlign = "center"; +const defaultTextBaseline = "middle"; +const defaultPadding = [0, 0, 0, 0]; +const defaultLineWidth = 1; +const checkedFonts = new BaseObject$1(); +let measureContext = null; +let measureFont; +const textHeights = {}; +const registerFont = function() { + const retries = 100; + const size = "32px "; + const referenceFonts = ["monospace", "serif"]; + const len = referenceFonts.length; + const text = "wmytzilWMYTZIL@#/&?$%10"; + let interval, referenceWidth; + function isAvailable(fontStyle, fontWeight, fontFamily) { + let available = true; + for (let i = 0; i < len; ++i) { + const referenceFont = referenceFonts[i]; + referenceWidth = measureTextWidth( + fontStyle + " " + fontWeight + " " + size + referenceFont, + text + ); + if (fontFamily != referenceFont) { + const width = measureTextWidth( + fontStyle + " " + fontWeight + " " + size + fontFamily + "," + referenceFont, + text + ); + available = available && width != referenceWidth; + } + } + if (available) { + return true; + } + return false; + } + function check() { + let done = true; + const fonts = checkedFonts.getKeys(); + for (let i = 0, ii = fonts.length; i < ii; ++i) { + const font = fonts[i]; + if (checkedFonts.get(font) < retries) { + if (isAvailable.apply(this, font.split("\n"))) { + clear(textHeights); + measureContext = null; + measureFont = void 0; + checkedFonts.set(font, retries); + } else { + checkedFonts.set(font, checkedFonts.get(font) + 1, true); + done = false; + } + } + } + if (done) { + clearInterval(interval); + interval = void 0; + } + } + return function(fontSpec) { + const font = getFontParameters(fontSpec); + if (!font) { + return; + } + const families = font.families; + for (let i = 0, ii = families.length; i < ii; ++i) { + const family = families[i]; + const key = font.style + "\n" + font.weight + "\n" + family; + if (checkedFonts.get(key) === void 0) { + checkedFonts.set(key, retries, true); + if (!isAvailable(font.style, font.weight, family)) { + checkedFonts.set(key, 0, true); + if (interval === void 0) { + interval = setInterval(check, 32); + } + } + } + } + }; +}(); +const measureTextHeight = function() { + let measureElement; + return function(fontSpec) { + let height = textHeights[fontSpec]; + if (height == void 0) { + if (WORKER_OFFSCREEN_CANVAS) { + const font = getFontParameters(fontSpec); + const metrics = measureText(fontSpec, "Žg"); + const lineHeight = isNaN(Number(font.lineHeight)) ? 1.2 : Number(font.lineHeight); + height = lineHeight * (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent); + } else { + if (!measureElement) { + measureElement = document.createElement("div"); + measureElement.innerHTML = "M"; + measureElement.style.minHeight = "0"; + measureElement.style.maxHeight = "none"; + measureElement.style.height = "auto"; + measureElement.style.padding = "0"; + measureElement.style.border = "none"; + measureElement.style.position = "absolute"; + measureElement.style.display = "block"; + measureElement.style.left = "-99999px"; + } + measureElement.style.font = fontSpec; + document.body.appendChild(measureElement); + height = measureElement.offsetHeight; + document.body.removeChild(measureElement); + } + textHeights[fontSpec] = height; + } + return height; + }; +}(); +function measureText(font, text) { + if (!measureContext) { + measureContext = createCanvasContext2D(1, 1); + } + if (font != measureFont) { + measureContext.font = font; + measureFont = measureContext.font; + } + return measureContext.measureText(text); +} +function measureTextWidth(font, text) { + return measureText(font, text).width; +} +function measureAndCacheTextWidth(font, text, cache2) { + if (text in cache2) { + return cache2[text]; + } + const width = text.split("\n").reduce((prev, curr) => Math.max(prev, measureTextWidth(font, curr)), 0); + cache2[text] = width; + return width; +} +function getTextDimensions(baseStyle, chunks) { + const widths = []; + const heights = []; + const lineWidths = []; + let width = 0; + let lineWidth = 0; + let height = 0; + let lineHeight = 0; + for (let i = 0, ii = chunks.length; i <= ii; i += 2) { + const text = chunks[i]; + if (text === "\n" || i === ii) { + width = Math.max(width, lineWidth); + lineWidths.push(lineWidth); + lineWidth = 0; + height += lineHeight; + continue; + } + const font = chunks[i + 1] || baseStyle.font; + const currentWidth = measureTextWidth(font, text); + widths.push(currentWidth); + lineWidth += currentWidth; + const currentHeight = measureTextHeight(font); + heights.push(currentHeight); + lineHeight = Math.max(lineHeight, currentHeight); + } + return { width, height, widths, heights, lineWidths }; +} +function drawImageOrLabel(context, transform2, opacity, labelOrImage, originX, originY, w, h, x, y, scale2) { + context.save(); + if (opacity !== 1) { + context.globalAlpha *= opacity; + } + if (transform2) { + context.transform.apply(context, transform2); + } + if ( + /** @type {*} */ + labelOrImage.contextInstructions + ) { + context.translate(x, y); + context.scale(scale2[0], scale2[1]); + executeLabelInstructions( + /** @type {Label} */ + labelOrImage, + context + ); + } else if (scale2[0] < 0 || scale2[1] < 0) { + context.translate(x, y); + context.scale(scale2[0], scale2[1]); + context.drawImage( + /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ + labelOrImage, + originX, + originY, + w, + h, + 0, + 0, + w, + h + ); + } else { + context.drawImage( + /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ + labelOrImage, + originX, + originY, + w, + h, + x, + y, + w * scale2[0], + h * scale2[1] + ); + } + context.restore(); +} +function executeLabelInstructions(label, context) { + const contextInstructions = label.contextInstructions; + for (let i = 0, ii = contextInstructions.length; i < ii; i += 2) { + if (Array.isArray(contextInstructions[i + 1])) { + context[contextInstructions[i]].apply( + context, + contextInstructions[i + 1] + ); + } else { + context[contextInstructions[i]] = contextInstructions[i + 1]; + } + } +} +class CompositeMapRenderer extends MapRenderer$1 { + /** + * @param {import("../Map.js").default} map Map. + */ + constructor(map) { + super(map); + this.fontChangeListenerKey_ = listen( + checkedFonts, + ObjectEventType.PROPERTYCHANGE, + map.redrawText.bind(map) + ); + this.element_ = document.createElement("div"); + const style = this.element_.style; + style.position = "absolute"; + style.width = "100%"; + style.height = "100%"; + style.zIndex = "0"; + this.element_.className = CLASS_UNSELECTABLE + " ol-layers"; + const container = map.getViewport(); + container.insertBefore(this.element_, container.firstChild || null); + this.children_ = []; + this.renderedVisible_ = true; + this.declutterLayers_ = []; + } + /** + * @param {import("../render/EventType.js").default} type Event type. + * @param {import("../Map.js").FrameState} frameState Frame state. + */ + dispatchRenderEvent(type, frameState) { + const map = this.getMap(); + if (map.hasListener(type)) { + const event = new RenderEvent$1(type, void 0, frameState); + map.dispatchEvent(event); + } + } + disposeInternal() { + unlistenByKey(this.fontChangeListenerKey_); + this.element_.parentNode.removeChild(this.element_); + super.disposeInternal(); + } + /** + * Render. + * @param {?import("../Map.js").FrameState} frameState Frame state. + */ + renderFrame(frameState) { + if (!frameState) { + if (this.renderedVisible_) { + this.element_.style.display = "none"; + this.renderedVisible_ = false; + } + return; + } + this.calculateMatrices2D(frameState); + this.dispatchRenderEvent(RenderEventType.PRECOMPOSE, frameState); + const layerStatesArray = frameState.layerStatesArray.sort(function(a, b) { + return a.zIndex - b.zIndex; + }); + const viewState = frameState.viewState; + this.children_.length = 0; + const declutterLayers = this.declutterLayers_; + declutterLayers.length = 0; + let previousElement = null; + for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) { + const layerState = layerStatesArray[i]; + frameState.layerIndex = i; + const layer = layerState.layer; + const sourceState = layer.getSourceState(); + if (!inView(layerState, viewState) || sourceState != "ready" && sourceState != "undefined") { + layer.unrender(); + continue; + } + const element = layer.render(frameState, previousElement); + if (!element) { + continue; + } + if (element !== previousElement) { + this.children_.push(element); + previousElement = element; + } + if ("getDeclutter" in layer) { + declutterLayers.push( + /** @type {import("../layer/BaseVector.js").default} */ + layer + ); + } + } + this.flushDeclutterItems(frameState); + replaceChildren(this.element_, this.children_); + this.dispatchRenderEvent(RenderEventType.POSTCOMPOSE, frameState); + if (!this.renderedVisible_) { + this.element_.style.display = ""; + this.renderedVisible_ = true; + } + this.scheduleExpireIconCache(frameState); + } + /** + * @param {import("../Map.js").FrameState} frameState Frame state. + */ + flushDeclutterItems(frameState) { + const layers = this.declutterLayers_; + for (let i = layers.length - 1; i >= 0; --i) { + layers[i].renderDeclutter(frameState); + } + layers.length = 0; + } +} +const CompositeMapRenderer$1 = CompositeMapRenderer; +class GroupEvent extends Event { + /** + * @param {EventType} type The event type. + * @param {BaseLayer} layer The layer. + */ + constructor(type, layer) { + super(type); + this.layer = layer; + } +} +const Property$2 = { + LAYERS: "layers" +}; +class LayerGroup extends BaseLayer$1 { + /** + * @param {Options} [options] Layer options. + */ + constructor(options) { + options = options || {}; + const baseOptions = ( + /** @type {Options} */ + Object.assign({}, options) + ); + delete baseOptions.layers; + let layers = options.layers; + super(baseOptions); + this.on; + this.once; + this.un; + this.layersListenerKeys_ = []; + this.listenerKeys_ = {}; + this.addChangeListener(Property$2.LAYERS, this.handleLayersChanged_); + if (layers) { + if (Array.isArray(layers)) { + layers = new Collection$1(layers.slice(), { unique: true }); + } else { + assert( + typeof /** @type {?} */ + layers.getArray === "function", + "Expected `layers` to be an array or a `Collection`" + ); + } + } else { + layers = new Collection$1(void 0, { unique: true }); + } + this.setLayers(layers); + } + /** + * @private + */ + handleLayerChange_() { + this.changed(); + } + /** + * @private + */ + handleLayersChanged_() { + this.layersListenerKeys_.forEach(unlistenByKey); + this.layersListenerKeys_.length = 0; + const layers = this.getLayers(); + this.layersListenerKeys_.push( + listen(layers, CollectionEventType.ADD, this.handleLayersAdd_, this), + listen(layers, CollectionEventType.REMOVE, this.handleLayersRemove_, this) + ); + for (const id in this.listenerKeys_) { + this.listenerKeys_[id].forEach(unlistenByKey); + } + clear(this.listenerKeys_); + const layersArray = layers.getArray(); + for (let i = 0, ii = layersArray.length; i < ii; i++) { + const layer = layersArray[i]; + this.registerLayerListeners_(layer); + this.dispatchEvent(new GroupEvent("addlayer", layer)); + } + this.changed(); + } + /** + * @param {BaseLayer} layer The layer. + */ + registerLayerListeners_(layer) { + const listenerKeys = [ + listen( + layer, + ObjectEventType.PROPERTYCHANGE, + this.handleLayerChange_, + this + ), + listen(layer, EventType.CHANGE, this.handleLayerChange_, this) + ]; + if (layer instanceof LayerGroup) { + listenerKeys.push( + listen(layer, "addlayer", this.handleLayerGroupAdd_, this), + listen(layer, "removelayer", this.handleLayerGroupRemove_, this) + ); + } + this.listenerKeys_[getUid(layer)] = listenerKeys; + } + /** + * @param {GroupEvent} event The layer group event. + */ + handleLayerGroupAdd_(event) { + this.dispatchEvent(new GroupEvent("addlayer", event.layer)); + } + /** + * @param {GroupEvent} event The layer group event. + */ + handleLayerGroupRemove_(event) { + this.dispatchEvent(new GroupEvent("removelayer", event.layer)); + } + /** + * @param {import("../Collection.js").CollectionEvent} collectionEvent CollectionEvent. + * @private + */ + handleLayersAdd_(collectionEvent) { + const layer = collectionEvent.element; + this.registerLayerListeners_(layer); + this.dispatchEvent(new GroupEvent("addlayer", layer)); + this.changed(); + } + /** + * @param {import("../Collection.js").CollectionEvent} collectionEvent CollectionEvent. + * @private + */ + handleLayersRemove_(collectionEvent) { + const layer = collectionEvent.element; + const key = getUid(layer); + this.listenerKeys_[key].forEach(unlistenByKey); + delete this.listenerKeys_[key]; + this.dispatchEvent(new GroupEvent("removelayer", layer)); + this.changed(); + } + /** + * Returns the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers} + * in this group. + * @return {!Collection} Collection of + * {@link module:ol/layer/Base~BaseLayer layers} that are part of this group. + * @observable + * @api + */ + getLayers() { + return ( + /** @type {!Collection} */ + this.get(Property$2.LAYERS) + ); + } + /** + * Set the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers} + * in this group. + * @param {!Collection} layers Collection of + * {@link module:ol/layer/Base~BaseLayer layers} that are part of this group. + * @observable + * @api + */ + setLayers(layers) { + const collection = this.getLayers(); + if (collection) { + const currentLayers = collection.getArray(); + for (let i = 0, ii = currentLayers.length; i < ii; ++i) { + this.dispatchEvent(new GroupEvent("removelayer", currentLayers[i])); + } + } + this.set(Property$2.LAYERS, layers); + } + /** + * @param {Array} [array] Array of layers (to be modified in place). + * @return {Array} Array of layers. + */ + getLayersArray(array) { + array = array !== void 0 ? array : []; + this.getLayers().forEach(function(layer) { + layer.getLayersArray(array); + }); + return array; + } + /** + * Get the layer states list and use this groups z-index as the default + * for all layers in this and nested groups, if it is unset at this point. + * If dest is not provided and this group's z-index is undefined + * 0 is used a the default z-index. + * @param {Array} [dest] Optional list + * of layer states (to be modified in place). + * @return {Array} List of layer states. + */ + getLayerStatesArray(dest) { + const states = dest !== void 0 ? dest : []; + const pos = states.length; + this.getLayers().forEach(function(layer) { + layer.getLayerStatesArray(states); + }); + const ownLayerState = this.getLayerState(); + let defaultZIndex = ownLayerState.zIndex; + if (!dest && ownLayerState.zIndex === void 0) { + defaultZIndex = 0; + } + for (let i = pos, ii = states.length; i < ii; i++) { + const layerState = states[i]; + layerState.opacity *= ownLayerState.opacity; + layerState.visible = layerState.visible && ownLayerState.visible; + layerState.maxResolution = Math.min( + layerState.maxResolution, + ownLayerState.maxResolution + ); + layerState.minResolution = Math.max( + layerState.minResolution, + ownLayerState.minResolution + ); + layerState.minZoom = Math.max(layerState.minZoom, ownLayerState.minZoom); + layerState.maxZoom = Math.min(layerState.maxZoom, ownLayerState.maxZoom); + if (ownLayerState.extent !== void 0) { + if (layerState.extent !== void 0) { + layerState.extent = getIntersection( + layerState.extent, + ownLayerState.extent + ); + } else { + layerState.extent = ownLayerState.extent; + } + } + if (layerState.zIndex === void 0) { + layerState.zIndex = defaultZIndex; + } + } + return states; + } + /** + * @return {import("../source/Source.js").State} Source state. + */ + getSourceState() { + return "ready"; + } +} +const LayerGroup$1 = LayerGroup; +class MapEvent extends Event { + /** + * @param {string} type Event type. + * @param {import("./Map.js").default} map Map. + * @param {?import("./Map.js").FrameState} [frameState] Frame state. + */ + constructor(type, map, frameState) { + super(type); + this.map = map; + this.frameState = frameState !== void 0 ? frameState : null; + } +} +const MapEvent$1 = MapEvent; +class MapBrowserEvent extends MapEvent$1 { + /** + * @param {string} type Event type. + * @param {import("./Map.js").default} map Map. + * @param {EVENT} originalEvent Original event. + * @param {boolean} [dragging] Is the map currently being dragged? + * @param {import("./Map.js").FrameState} [frameState] Frame state. + * @param {Array} [activePointers] Active pointers. + */ + constructor(type, map, originalEvent, dragging, frameState, activePointers) { + super(type, map, frameState); + this.originalEvent = originalEvent; + this.pixel_ = null; + this.coordinate_ = null; + this.dragging = dragging !== void 0 ? dragging : false; + this.activePointers = activePointers; + } + /** + * The map pixel relative to the viewport corresponding to the original event. + * @type {import("./pixel.js").Pixel} + * @api + */ + get pixel() { + if (!this.pixel_) { + this.pixel_ = this.map.getEventPixel(this.originalEvent); + } + return this.pixel_; + } + set pixel(pixel) { + this.pixel_ = pixel; + } + /** + * The coordinate corresponding to the original browser event. This will be in the user + * projection if one is set. Otherwise it will be in the view projection. + * @type {import("./coordinate.js").Coordinate} + * @api + */ + get coordinate() { + if (!this.coordinate_) { + this.coordinate_ = this.map.getCoordinateFromPixel(this.pixel); + } + return this.coordinate_; + } + set coordinate(coordinate) { + this.coordinate_ = coordinate; + } + /** + * Prevents the default browser action. + * See https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault. + * @api + */ + preventDefault() { + super.preventDefault(); + if ("preventDefault" in this.originalEvent) { + this.originalEvent.preventDefault(); + } + } + /** + * Prevents further propagation of the current event. + * See https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation. + * @api + */ + stopPropagation() { + super.stopPropagation(); + if ("stopPropagation" in this.originalEvent) { + this.originalEvent.stopPropagation(); + } + } +} +const MapBrowserEvent$1 = MapBrowserEvent; +const MapBrowserEventType = { + /** + * A true single click with no dragging and no double click. Note that this + * event is delayed by 250 ms to ensure that it is not a double click. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#singleclick + * @api + */ + SINGLECLICK: "singleclick", + /** + * A click with no dragging. A double click will fire two of this. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#click + * @api + */ + CLICK: EventType.CLICK, + /** + * A true double click, with no dragging. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#dblclick + * @api + */ + DBLCLICK: EventType.DBLCLICK, + /** + * Triggered when a pointer is dragged. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointerdrag + * @api + */ + POINTERDRAG: "pointerdrag", + /** + * Triggered when a pointer is moved. Note that on touch devices this is + * triggered when the map is panned, so is not the same as mousemove. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointermove + * @api + */ + POINTERMOVE: "pointermove", + POINTERDOWN: "pointerdown", + POINTERUP: "pointerup", + POINTEROVER: "pointerover", + POINTEROUT: "pointerout", + POINTERENTER: "pointerenter", + POINTERLEAVE: "pointerleave", + POINTERCANCEL: "pointercancel" +}; +const PointerEventType = { + POINTERMOVE: "pointermove", + POINTERDOWN: "pointerdown", + POINTERUP: "pointerup", + POINTEROVER: "pointerover", + POINTEROUT: "pointerout", + POINTERENTER: "pointerenter", + POINTERLEAVE: "pointerleave", + POINTERCANCEL: "pointercancel" +}; +class MapBrowserEventHandler extends EventTarget { + /** + * @param {import("./Map.js").default} map The map with the viewport to listen to events on. + * @param {number} [moveTolerance] The minimal distance the pointer must travel to trigger a move. + */ + constructor(map, moveTolerance) { + super(map); + this.map_ = map; + this.clickTimeoutId_; + this.emulateClicks_ = false; + this.dragging_ = false; + this.dragListenerKeys_ = []; + this.moveTolerance_ = moveTolerance === void 0 ? 1 : moveTolerance; + this.down_ = null; + const element = this.map_.getViewport(); + this.activePointers_ = []; + this.trackedTouches_ = {}; + this.element_ = element; + this.pointerdownListenerKey_ = listen( + element, + PointerEventType.POINTERDOWN, + this.handlePointerDown_, + this + ); + this.originalPointerMoveEvent_; + this.relayedListenerKey_ = listen( + element, + PointerEventType.POINTERMOVE, + this.relayMoveEvent_, + this + ); + this.boundHandleTouchMove_ = this.handleTouchMove_.bind(this); + this.element_.addEventListener( + EventType.TOUCHMOVE, + this.boundHandleTouchMove_, + PASSIVE_EVENT_LISTENERS ? { passive: false } : false + ); + } + /** + * @param {PointerEvent} pointerEvent Pointer + * event. + * @private + */ + emulateClick_(pointerEvent) { + let newEvent = new MapBrowserEvent$1( + MapBrowserEventType.CLICK, + this.map_, + pointerEvent + ); + this.dispatchEvent(newEvent); + if (this.clickTimeoutId_ !== void 0) { + clearTimeout(this.clickTimeoutId_); + this.clickTimeoutId_ = void 0; + newEvent = new MapBrowserEvent$1( + MapBrowserEventType.DBLCLICK, + this.map_, + pointerEvent + ); + this.dispatchEvent(newEvent); + } else { + this.clickTimeoutId_ = setTimeout(() => { + this.clickTimeoutId_ = void 0; + const newEvent2 = new MapBrowserEvent$1( + MapBrowserEventType.SINGLECLICK, + this.map_, + pointerEvent + ); + this.dispatchEvent(newEvent2); + }, 250); + } + } + /** + * Keeps track on how many pointers are currently active. + * + * @param {PointerEvent} pointerEvent Pointer + * event. + * @private + */ + updateActivePointers_(pointerEvent) { + const event = pointerEvent; + const id = event.pointerId; + if (event.type == MapBrowserEventType.POINTERUP || event.type == MapBrowserEventType.POINTERCANCEL) { + delete this.trackedTouches_[id]; + for (const pointerId in this.trackedTouches_) { + if (this.trackedTouches_[pointerId].target !== event.target) { + delete this.trackedTouches_[pointerId]; + break; + } + } + } else if (event.type == MapBrowserEventType.POINTERDOWN || event.type == MapBrowserEventType.POINTERMOVE) { + this.trackedTouches_[id] = event; + } + this.activePointers_ = Object.values(this.trackedTouches_); + } + /** + * @param {PointerEvent} pointerEvent Pointer + * event. + * @private + */ + handlePointerUp_(pointerEvent) { + this.updateActivePointers_(pointerEvent); + const newEvent = new MapBrowserEvent$1( + MapBrowserEventType.POINTERUP, + this.map_, + pointerEvent, + void 0, + void 0, + this.activePointers_ + ); + this.dispatchEvent(newEvent); + if (this.emulateClicks_ && !newEvent.defaultPrevented && !this.dragging_ && this.isMouseActionButton_(pointerEvent)) { + this.emulateClick_(this.down_); + } + if (this.activePointers_.length === 0) { + this.dragListenerKeys_.forEach(unlistenByKey); + this.dragListenerKeys_.length = 0; + this.dragging_ = false; + this.down_ = null; + } + } + /** + * @param {PointerEvent} pointerEvent Pointer + * event. + * @return {boolean} If the left mouse button was pressed. + * @private + */ + isMouseActionButton_(pointerEvent) { + return pointerEvent.button === 0; + } + /** + * @param {PointerEvent} pointerEvent Pointer + * event. + * @private + */ + handlePointerDown_(pointerEvent) { + this.emulateClicks_ = this.activePointers_.length === 0; + this.updateActivePointers_(pointerEvent); + const newEvent = new MapBrowserEvent$1( + MapBrowserEventType.POINTERDOWN, + this.map_, + pointerEvent, + void 0, + void 0, + this.activePointers_ + ); + this.dispatchEvent(newEvent); + this.down_ = new PointerEvent(pointerEvent.type, pointerEvent); + Object.defineProperty(this.down_, "target", { + writable: false, + value: pointerEvent.target + }); + if (this.dragListenerKeys_.length === 0) { + const doc = this.map_.getOwnerDocument(); + this.dragListenerKeys_.push( + listen( + doc, + MapBrowserEventType.POINTERMOVE, + this.handlePointerMove_, + this + ), + listen(doc, MapBrowserEventType.POINTERUP, this.handlePointerUp_, this), + /* Note that the listener for `pointercancel is set up on + * `pointerEventHandler_` and not `documentPointerEventHandler_` like + * the `pointerup` and `pointermove` listeners. + * + * The reason for this is the following: `TouchSource.vacuumTouches_()` + * issues `pointercancel` events, when there was no `touchend` for a + * `touchstart`. Now, let's say a first `touchstart` is registered on + * `pointerEventHandler_`. The `documentPointerEventHandler_` is set up. + * But `documentPointerEventHandler_` doesn't know about the first + * `touchstart`. If there is no `touchend` for the `touchstart`, we can + * only receive a `touchcancel` from `pointerEventHandler_`, because it is + * only registered there. + */ + listen( + this.element_, + MapBrowserEventType.POINTERCANCEL, + this.handlePointerUp_, + this + ) + ); + if (this.element_.getRootNode && this.element_.getRootNode() !== doc) { + this.dragListenerKeys_.push( + listen( + this.element_.getRootNode(), + MapBrowserEventType.POINTERUP, + this.handlePointerUp_, + this + ) + ); + } + } + } + /** + * @param {PointerEvent} pointerEvent Pointer + * event. + * @private + */ + handlePointerMove_(pointerEvent) { + if (this.isMoving_(pointerEvent)) { + this.updateActivePointers_(pointerEvent); + this.dragging_ = true; + const newEvent = new MapBrowserEvent$1( + MapBrowserEventType.POINTERDRAG, + this.map_, + pointerEvent, + this.dragging_, + void 0, + this.activePointers_ + ); + this.dispatchEvent(newEvent); + } + } + /** + * Wrap and relay a pointermove event. + * @param {PointerEvent} pointerEvent Pointer + * event. + * @private + */ + relayMoveEvent_(pointerEvent) { + this.originalPointerMoveEvent_ = pointerEvent; + const dragging = !!(this.down_ && this.isMoving_(pointerEvent)); + this.dispatchEvent( + new MapBrowserEvent$1( + MapBrowserEventType.POINTERMOVE, + this.map_, + pointerEvent, + dragging + ) + ); + } + /** + * Flexible handling of a `touch-action: none` css equivalent: because calling + * `preventDefault()` on a `pointermove` event does not stop native page scrolling + * and zooming, we also listen for `touchmove` and call `preventDefault()` on it + * when an interaction (currently `DragPan` handles the event. + * @param {TouchEvent} event Event. + * @private + */ + handleTouchMove_(event) { + const originalEvent = this.originalPointerMoveEvent_; + if ((!originalEvent || originalEvent.defaultPrevented) && (typeof event.cancelable !== "boolean" || event.cancelable === true)) { + event.preventDefault(); + } + } + /** + * @param {PointerEvent} pointerEvent Pointer + * event. + * @return {boolean} Is moving. + * @private + */ + isMoving_(pointerEvent) { + return this.dragging_ || Math.abs(pointerEvent.clientX - this.down_.clientX) > this.moveTolerance_ || Math.abs(pointerEvent.clientY - this.down_.clientY) > this.moveTolerance_; + } + /** + * Clean up. + */ + disposeInternal() { + if (this.relayedListenerKey_) { + unlistenByKey(this.relayedListenerKey_); + this.relayedListenerKey_ = null; + } + this.element_.removeEventListener( + EventType.TOUCHMOVE, + this.boundHandleTouchMove_ + ); + if (this.pointerdownListenerKey_) { + unlistenByKey(this.pointerdownListenerKey_); + this.pointerdownListenerKey_ = null; + } + this.dragListenerKeys_.forEach(unlistenByKey); + this.dragListenerKeys_.length = 0; + this.element_ = null; + super.disposeInternal(); + } +} +const MapBrowserEventHandler$1 = MapBrowserEventHandler; +const MapEventType = { + /** + * Triggered after a map frame is rendered. + * @event module:ol/MapEvent~MapEvent#postrender + * @api + */ + POSTRENDER: "postrender", + /** + * Triggered when the map starts moving. + * @event module:ol/MapEvent~MapEvent#movestart + * @api + */ + MOVESTART: "movestart", + /** + * Triggered after the map is moved. + * @event module:ol/MapEvent~MapEvent#moveend + * @api + */ + MOVEEND: "moveend", + /** + * Triggered when loading of additional map data (tiles, images, features) starts. + * @event module:ol/MapEvent~MapEvent#loadstart + * @api + */ + LOADSTART: "loadstart", + /** + * Triggered when loading of additional map data has completed. + * @event module:ol/MapEvent~MapEvent#loadend + * @api + */ + LOADEND: "loadend" +}; +const MapProperty = { + LAYERGROUP: "layergroup", + SIZE: "size", + TARGET: "target", + VIEW: "view" +}; +const DROP = Infinity; +class PriorityQueue { + /** + * @param {function(T): number} priorityFunction Priority function. + * @param {function(T): string} keyFunction Key function. + */ + constructor(priorityFunction, keyFunction) { + this.priorityFunction_ = priorityFunction; + this.keyFunction_ = keyFunction; + this.elements_ = []; + this.priorities_ = []; + this.queuedElements_ = {}; + } + /** + * FIXME empty description for jsdoc + */ + clear() { + this.elements_.length = 0; + this.priorities_.length = 0; + clear(this.queuedElements_); + } + /** + * Remove and return the highest-priority element. O(log N). + * @return {T} Element. + */ + dequeue() { + const elements = this.elements_; + const priorities = this.priorities_; + const element = elements[0]; + if (elements.length == 1) { + elements.length = 0; + priorities.length = 0; + } else { + elements[0] = elements.pop(); + priorities[0] = priorities.pop(); + this.siftUp_(0); + } + const elementKey = this.keyFunction_(element); + delete this.queuedElements_[elementKey]; + return element; + } + /** + * Enqueue an element. O(log N). + * @param {T} element Element. + * @return {boolean} The element was added to the queue. + */ + enqueue(element) { + assert( + !(this.keyFunction_(element) in this.queuedElements_), + "Tried to enqueue an `element` that was already added to the queue" + ); + const priority = this.priorityFunction_(element); + if (priority != DROP) { + this.elements_.push(element); + this.priorities_.push(priority); + this.queuedElements_[this.keyFunction_(element)] = true; + this.siftDown_(0, this.elements_.length - 1); + return true; + } + return false; + } + /** + * @return {number} Count. + */ + getCount() { + return this.elements_.length; + } + /** + * Gets the index of the left child of the node at the given index. + * @param {number} index The index of the node to get the left child for. + * @return {number} The index of the left child. + * @private + */ + getLeftChildIndex_(index) { + return index * 2 + 1; + } + /** + * Gets the index of the right child of the node at the given index. + * @param {number} index The index of the node to get the right child for. + * @return {number} The index of the right child. + * @private + */ + getRightChildIndex_(index) { + return index * 2 + 2; + } + /** + * Gets the index of the parent of the node at the given index. + * @param {number} index The index of the node to get the parent for. + * @return {number} The index of the parent. + * @private + */ + getParentIndex_(index) { + return index - 1 >> 1; + } + /** + * Make this a heap. O(N). + * @private + */ + heapify_() { + let i; + for (i = (this.elements_.length >> 1) - 1; i >= 0; i--) { + this.siftUp_(i); + } + } + /** + * @return {boolean} Is empty. + */ + isEmpty() { + return this.elements_.length === 0; + } + /** + * @param {string} key Key. + * @return {boolean} Is key queued. + */ + isKeyQueued(key) { + return key in this.queuedElements_; + } + /** + * @param {T} element Element. + * @return {boolean} Is queued. + */ + isQueued(element) { + return this.isKeyQueued(this.keyFunction_(element)); + } + /** + * @param {number} index The index of the node to move down. + * @private + */ + siftUp_(index) { + const elements = this.elements_; + const priorities = this.priorities_; + const count = elements.length; + const element = elements[index]; + const priority = priorities[index]; + const startIndex = index; + while (index < count >> 1) { + const lIndex = this.getLeftChildIndex_(index); + const rIndex = this.getRightChildIndex_(index); + const smallerChildIndex = rIndex < count && priorities[rIndex] < priorities[lIndex] ? rIndex : lIndex; + elements[index] = elements[smallerChildIndex]; + priorities[index] = priorities[smallerChildIndex]; + index = smallerChildIndex; + } + elements[index] = element; + priorities[index] = priority; + this.siftDown_(startIndex, index); + } + /** + * @param {number} startIndex The index of the root. + * @param {number} index The index of the node to move up. + * @private + */ + siftDown_(startIndex, index) { + const elements = this.elements_; + const priorities = this.priorities_; + const element = elements[index]; + const priority = priorities[index]; + while (index > startIndex) { + const parentIndex = this.getParentIndex_(index); + if (priorities[parentIndex] > priority) { + elements[index] = elements[parentIndex]; + priorities[index] = priorities[parentIndex]; + index = parentIndex; + } else { + break; + } + } + elements[index] = element; + priorities[index] = priority; + } + /** + * FIXME empty description for jsdoc + */ + reprioritize() { + const priorityFunction = this.priorityFunction_; + const elements = this.elements_; + const priorities = this.priorities_; + let index = 0; + const n = elements.length; + let element, i, priority; + for (i = 0; i < n; ++i) { + element = elements[i]; + priority = priorityFunction(element); + if (priority == DROP) { + delete this.queuedElements_[this.keyFunction_(element)]; + } else { + priorities[index] = priority; + elements[index++] = element; + } + } + elements.length = index; + priorities.length = index; + this.heapify_(); + } +} +const PriorityQueue$1 = PriorityQueue; +const TileState = { + IDLE: 0, + LOADING: 1, + LOADED: 2, + /** + * Indicates that tile loading failed + * @type {number} + */ + ERROR: 3, + EMPTY: 4 +}; +class TileQueue extends PriorityQueue$1 { + /** + * @param {PriorityFunction} tilePriorityFunction Tile priority function. + * @param {function(): ?} tileChangeCallback Function called on each tile change event. + */ + constructor(tilePriorityFunction, tileChangeCallback) { + super( + /** + * @param {Array} element Element. + * @return {number} Priority. + */ + function(element) { + return tilePriorityFunction.apply(null, element); + }, + /** + * @param {Array} element Element. + * @return {string} Key. + */ + function(element) { + return ( + /** @type {import("./Tile.js").default} */ + element[0].getKey() + ); + } + ); + this.boundHandleTileChange_ = this.handleTileChange.bind(this); + this.tileChangeCallback_ = tileChangeCallback; + this.tilesLoading_ = 0; + this.tilesLoadingKeys_ = {}; + } + /** + * @param {Array} element Element. + * @return {boolean} The element was added to the queue. + */ + enqueue(element) { + const added = super.enqueue(element); + if (added) { + const tile = element[0]; + tile.addEventListener(EventType.CHANGE, this.boundHandleTileChange_); + } + return added; + } + /** + * @return {number} Number of tiles loading. + */ + getTilesLoading() { + return this.tilesLoading_; + } + /** + * @param {import("./events/Event.js").default} event Event. + * @protected + */ + handleTileChange(event) { + const tile = ( + /** @type {import("./Tile.js").default} */ + event.target + ); + const state = tile.getState(); + if (state === TileState.LOADED || state === TileState.ERROR || state === TileState.EMPTY) { + if (state !== TileState.ERROR) { + tile.removeEventListener(EventType.CHANGE, this.boundHandleTileChange_); + } + const tileKey = tile.getKey(); + if (tileKey in this.tilesLoadingKeys_) { + delete this.tilesLoadingKeys_[tileKey]; + --this.tilesLoading_; + } + this.tileChangeCallback_(); + } + } + /** + * @param {number} maxTotalLoading Maximum number tiles to load simultaneously. + * @param {number} maxNewLoads Maximum number of new tiles to load. + */ + loadMoreTiles(maxTotalLoading, maxNewLoads) { + let newLoads = 0; + let state, tile, tileKey; + while (this.tilesLoading_ < maxTotalLoading && newLoads < maxNewLoads && this.getCount() > 0) { + tile = /** @type {import("./Tile.js").default} */ + this.dequeue()[0]; + tileKey = tile.getKey(); + state = tile.getState(); + if (state === TileState.IDLE && !(tileKey in this.tilesLoadingKeys_)) { + this.tilesLoadingKeys_[tileKey] = true; + ++this.tilesLoading_; + ++newLoads; + tile.load(); + } + } + } +} +const TileQueue$1 = TileQueue; +function getTilePriority(frameState, tile, tileSourceKey, tileCenter, tileResolution) { + if (!frameState || !(tileSourceKey in frameState.wantedTiles)) { + return DROP; + } + if (!frameState.wantedTiles[tileSourceKey][tile.getKey()]) { + return DROP; + } + const center = frameState.viewState.center; + const deltaX = tileCenter[0] - center[0]; + const deltaY = tileCenter[1] - center[1]; + return 65536 * Math.log(tileResolution) + Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution; +} +class Control extends BaseObject$1 { + /** + * @param {Options} options Control options. + */ + constructor(options) { + super(); + const element = options.element; + if (element && !options.target && !element.style.pointerEvents) { + element.style.pointerEvents = "auto"; + } + this.element = element ? element : null; + this.target_ = null; + this.map_ = null; + this.listenerKeys = []; + if (options.render) { + this.render = options.render; + } + if (options.target) { + this.setTarget(options.target); + } + } + /** + * Clean up. + */ + disposeInternal() { + removeNode(this.element); + super.disposeInternal(); + } + /** + * Get the map associated with this control. + * @return {import("../Map.js").default|null} Map. + * @api + */ + getMap() { + return this.map_; + } + /** + * Remove the control from its current map and attach it to the new map. + * Pass `null` to just remove the control from the current map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {import("../Map.js").default|null} map Map. + * @api + */ + setMap(map) { + if (this.map_) { + removeNode(this.element); + } + for (let i = 0, ii = this.listenerKeys.length; i < ii; ++i) { + unlistenByKey(this.listenerKeys[i]); + } + this.listenerKeys.length = 0; + this.map_ = map; + if (map) { + const target = this.target_ ? this.target_ : map.getOverlayContainerStopEvent(); + target.appendChild(this.element); + if (this.render !== VOID) { + this.listenerKeys.push( + listen(map, MapEventType.POSTRENDER, this.render, this) + ); + } + map.render(); + } + } + /** + * Renders the control. + * @param {import("../MapEvent.js").default} mapEvent Map event. + * @api + */ + render(mapEvent) { + } + /** + * This function is used to set a target element for the control. It has no + * effect if it is called after the control has been added to the map (i.e. + * after `setMap` is called on the control). If no `target` is set in the + * options passed to the control constructor and if `setTarget` is not called + * then the control is added to the map's overlay container. + * @param {HTMLElement|string} target Target. + * @api + */ + setTarget(target) { + this.target_ = typeof target === "string" ? document.getElementById(target) : target; + } +} +const Control$1 = Control; +class Attribution extends Control$1 { + /** + * @param {Options} [options] Attribution options. + */ + constructor(options) { + options = options ? options : {}; + super({ + element: document.createElement("div"), + render: options.render, + target: options.target + }); + this.ulElement_ = document.createElement("ul"); + this.collapsed_ = options.collapsed !== void 0 ? options.collapsed : true; + this.userCollapsed_ = this.collapsed_; + this.overrideCollapsible_ = options.collapsible !== void 0; + this.collapsible_ = options.collapsible !== void 0 ? options.collapsible : true; + if (!this.collapsible_) { + this.collapsed_ = false; + } + const className = options.className !== void 0 ? options.className : "ol-attribution"; + const tipLabel = options.tipLabel !== void 0 ? options.tipLabel : "Attributions"; + const expandClassName = options.expandClassName !== void 0 ? options.expandClassName : className + "-expand"; + const collapseLabel = options.collapseLabel !== void 0 ? options.collapseLabel : "›"; + const collapseClassName = options.collapseClassName !== void 0 ? options.collapseClassName : className + "-collapse"; + if (typeof collapseLabel === "string") { + this.collapseLabel_ = document.createElement("span"); + this.collapseLabel_.textContent = collapseLabel; + this.collapseLabel_.className = collapseClassName; + } else { + this.collapseLabel_ = collapseLabel; + } + const label = options.label !== void 0 ? options.label : "i"; + if (typeof label === "string") { + this.label_ = document.createElement("span"); + this.label_.textContent = label; + this.label_.className = expandClassName; + } else { + this.label_ = label; + } + const activeLabel = this.collapsible_ && !this.collapsed_ ? this.collapseLabel_ : this.label_; + this.toggleButton_ = document.createElement("button"); + this.toggleButton_.setAttribute("type", "button"); + this.toggleButton_.setAttribute("aria-expanded", String(!this.collapsed_)); + this.toggleButton_.title = tipLabel; + this.toggleButton_.appendChild(activeLabel); + this.toggleButton_.addEventListener( + EventType.CLICK, + this.handleClick_.bind(this), + false + ); + const cssClasses = className + " " + CLASS_UNSELECTABLE + " " + CLASS_CONTROL + (this.collapsed_ && this.collapsible_ ? " " + CLASS_COLLAPSED : "") + (this.collapsible_ ? "" : " ol-uncollapsible"); + const element = this.element; + element.className = cssClasses; + element.appendChild(this.toggleButton_); + element.appendChild(this.ulElement_); + this.renderedAttributions_ = []; + this.renderedVisible_ = true; + } + /** + * Collect a list of visible attributions and set the collapsible state. + * @param {import("../Map.js").FrameState} frameState Frame state. + * @return {Array} Attributions. + * @private + */ + collectSourceAttributions_(frameState) { + const visibleAttributions = Array.from( + new Set( + this.getMap().getAllLayers().flatMap((layer) => layer.getAttributions(frameState)) + ) + ); + const collapsible = !this.getMap().getAllLayers().some( + (layer) => layer.getSource() && layer.getSource().getAttributionsCollapsible() === false + ); + if (!this.overrideCollapsible_) { + this.setCollapsible(collapsible); + } + return visibleAttributions; + } + /** + * @private + * @param {?import("../Map.js").FrameState} frameState Frame state. + */ + updateElement_(frameState) { + if (!frameState) { + if (this.renderedVisible_) { + this.element.style.display = "none"; + this.renderedVisible_ = false; + } + return; + } + const attributions = this.collectSourceAttributions_(frameState); + const visible = attributions.length > 0; + if (this.renderedVisible_ != visible) { + this.element.style.display = visible ? "" : "none"; + this.renderedVisible_ = visible; + } + if (equals$2(attributions, this.renderedAttributions_)) { + return; + } + removeChildren(this.ulElement_); + for (let i = 0, ii = attributions.length; i < ii; ++i) { + const element = document.createElement("li"); + element.innerHTML = attributions[i]; + this.ulElement_.appendChild(element); + } + this.renderedAttributions_ = attributions; + } + /** + * @param {MouseEvent} event The event to handle + * @private + */ + handleClick_(event) { + event.preventDefault(); + this.handleToggle_(); + this.userCollapsed_ = this.collapsed_; + } + /** + * @private + */ + handleToggle_() { + this.element.classList.toggle(CLASS_COLLAPSED); + if (this.collapsed_) { + replaceNode(this.collapseLabel_, this.label_); + } else { + replaceNode(this.label_, this.collapseLabel_); + } + this.collapsed_ = !this.collapsed_; + this.toggleButton_.setAttribute("aria-expanded", String(!this.collapsed_)); + } + /** + * Return `true` if the attribution is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api + */ + getCollapsible() { + return this.collapsible_; + } + /** + * Set whether the attribution should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api + */ + setCollapsible(collapsible) { + if (this.collapsible_ === collapsible) { + return; + } + this.collapsible_ = collapsible; + this.element.classList.toggle("ol-uncollapsible"); + if (this.userCollapsed_) { + this.handleToggle_(); + } + } + /** + * Collapse or expand the attribution according to the passed parameter. Will + * not do anything if the attribution isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api + */ + setCollapsed(collapsed) { + this.userCollapsed_ = collapsed; + if (!this.collapsible_ || this.collapsed_ === collapsed) { + return; + } + this.handleToggle_(); + } + /** + * Return `true` when the attribution is currently collapsed or `false` + * otherwise. + * @return {boolean} True if the widget is collapsed. + * @api + */ + getCollapsed() { + return this.collapsed_; + } + /** + * Update the attribution element. + * @param {import("../MapEvent.js").default} mapEvent Map event. + * @override + */ + render(mapEvent) { + this.updateElement_(mapEvent.frameState); + } +} +const Attribution$1 = Attribution; +class Rotate extends Control$1 { + /** + * @param {Options} [options] Rotate options. + */ + constructor(options) { + options = options ? options : {}; + super({ + element: document.createElement("div"), + render: options.render, + target: options.target + }); + const className = options.className !== void 0 ? options.className : "ol-rotate"; + const label = options.label !== void 0 ? options.label : "⇧"; + const compassClassName = options.compassClassName !== void 0 ? options.compassClassName : "ol-compass"; + this.label_ = null; + if (typeof label === "string") { + this.label_ = document.createElement("span"); + this.label_.className = compassClassName; + this.label_.textContent = label; + } else { + this.label_ = label; + this.label_.classList.add(compassClassName); + } + const tipLabel = options.tipLabel ? options.tipLabel : "Reset rotation"; + const button = document.createElement("button"); + button.className = className + "-reset"; + button.setAttribute("type", "button"); + button.title = tipLabel; + button.appendChild(this.label_); + button.addEventListener( + EventType.CLICK, + this.handleClick_.bind(this), + false + ); + const cssClasses = className + " " + CLASS_UNSELECTABLE + " " + CLASS_CONTROL; + const element = this.element; + element.className = cssClasses; + element.appendChild(button); + this.callResetNorth_ = options.resetNorth ? options.resetNorth : void 0; + this.duration_ = options.duration !== void 0 ? options.duration : 250; + this.autoHide_ = options.autoHide !== void 0 ? options.autoHide : true; + this.rotation_ = void 0; + if (this.autoHide_) { + this.element.classList.add(CLASS_HIDDEN); + } + } + /** + * @param {MouseEvent} event The event to handle + * @private + */ + handleClick_(event) { + event.preventDefault(); + if (this.callResetNorth_ !== void 0) { + this.callResetNorth_(); + } else { + this.resetNorth_(); + } + } + /** + * @private + */ + resetNorth_() { + const map = this.getMap(); + const view = map.getView(); + if (!view) { + return; + } + const rotation = view.getRotation(); + if (rotation !== void 0) { + if (this.duration_ > 0 && rotation % (2 * Math.PI) !== 0) { + view.animate({ + rotation: 0, + duration: this.duration_, + easing: easeOut + }); + } else { + view.setRotation(0); + } + } + } + /** + * Update the rotate control element. + * @param {import("../MapEvent.js").default} mapEvent Map event. + * @override + */ + render(mapEvent) { + const frameState = mapEvent.frameState; + if (!frameState) { + return; + } + const rotation = frameState.viewState.rotation; + if (rotation != this.rotation_) { + const transform2 = "rotate(" + rotation + "rad)"; + if (this.autoHide_) { + const contains2 = this.element.classList.contains(CLASS_HIDDEN); + if (!contains2 && rotation === 0) { + this.element.classList.add(CLASS_HIDDEN); + } else if (contains2 && rotation !== 0) { + this.element.classList.remove(CLASS_HIDDEN); + } + } + this.label_.style.transform = transform2; + } + this.rotation_ = rotation; + } +} +const Rotate$1 = Rotate; +class Zoom extends Control$1 { + /** + * @param {Options} [options] Zoom options. + */ + constructor(options) { + options = options ? options : {}; + super({ + element: document.createElement("div"), + target: options.target + }); + const className = options.className !== void 0 ? options.className : "ol-zoom"; + const delta = options.delta !== void 0 ? options.delta : 1; + const zoomInClassName = options.zoomInClassName !== void 0 ? options.zoomInClassName : className + "-in"; + const zoomOutClassName = options.zoomOutClassName !== void 0 ? options.zoomOutClassName : className + "-out"; + const zoomInLabel = options.zoomInLabel !== void 0 ? options.zoomInLabel : "+"; + const zoomOutLabel = options.zoomOutLabel !== void 0 ? options.zoomOutLabel : "–"; + const zoomInTipLabel = options.zoomInTipLabel !== void 0 ? options.zoomInTipLabel : "Zoom in"; + const zoomOutTipLabel = options.zoomOutTipLabel !== void 0 ? options.zoomOutTipLabel : "Zoom out"; + const inElement = document.createElement("button"); + inElement.className = zoomInClassName; + inElement.setAttribute("type", "button"); + inElement.title = zoomInTipLabel; + inElement.appendChild( + typeof zoomInLabel === "string" ? document.createTextNode(zoomInLabel) : zoomInLabel + ); + inElement.addEventListener( + EventType.CLICK, + this.handleClick_.bind(this, delta), + false + ); + const outElement = document.createElement("button"); + outElement.className = zoomOutClassName; + outElement.setAttribute("type", "button"); + outElement.title = zoomOutTipLabel; + outElement.appendChild( + typeof zoomOutLabel === "string" ? document.createTextNode(zoomOutLabel) : zoomOutLabel + ); + outElement.addEventListener( + EventType.CLICK, + this.handleClick_.bind(this, -delta), + false + ); + const cssClasses = className + " " + CLASS_UNSELECTABLE + " " + CLASS_CONTROL; + const element = this.element; + element.className = cssClasses; + element.appendChild(inElement); + element.appendChild(outElement); + this.duration_ = options.duration !== void 0 ? options.duration : 250; + } + /** + * @param {number} delta Zoom delta. + * @param {MouseEvent} event The event to handle + * @private + */ + handleClick_(delta, event) { + event.preventDefault(); + this.zoomByDelta_(delta); + } + /** + * @param {number} delta Zoom delta. + * @private + */ + zoomByDelta_(delta) { + const map = this.getMap(); + const view = map.getView(); + if (!view) { + return; + } + const currentZoom = view.getZoom(); + if (currentZoom !== void 0) { + const newZoom = view.getConstrainedZoom(currentZoom + delta); + if (this.duration_ > 0) { + if (view.getAnimating()) { + view.cancelAnimations(); + } + view.animate({ + zoom: newZoom, + duration: this.duration_, + easing: easeOut + }); + } else { + view.setZoom(newZoom); + } + } + } +} +const Zoom$1 = Zoom; +function defaults$1(options) { + options = options ? options : {}; + const controls = new Collection$1(); + const zoomControl = options.zoom !== void 0 ? options.zoom : true; + if (zoomControl) { + controls.push(new Zoom$1(options.zoomOptions)); + } + const rotateControl = options.rotate !== void 0 ? options.rotate : true; + if (rotateControl) { + controls.push(new Rotate$1(options.rotateOptions)); + } + const attributionControl = options.attribution !== void 0 ? options.attribution : true; + if (attributionControl) { + controls.push(new Attribution$1(options.attributionOptions)); + } + return controls; +} +const InteractionProperty = { + ACTIVE: "active" +}; +class Interaction extends BaseObject$1 { + /** + * @param {InteractionOptions} [options] Options. + */ + constructor(options) { + super(); + this.on; + this.once; + this.un; + if (options && options.handleEvent) { + this.handleEvent = options.handleEvent; + } + this.map_ = null; + this.setActive(true); + } + /** + * Return whether the interaction is currently active. + * @return {boolean} `true` if the interaction is active, `false` otherwise. + * @observable + * @api + */ + getActive() { + return ( + /** @type {boolean} */ + this.get(InteractionProperty.ACTIVE) + ); + } + /** + * Get the map associated with this interaction. + * @return {import("../Map.js").default|null} Map. + * @api + */ + getMap() { + return this.map_; + } + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event}. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + * @api + */ + handleEvent(mapBrowserEvent) { + return true; + } + /** + * Activate or deactivate the interaction. + * @param {boolean} active Active. + * @observable + * @api + */ + setActive(active) { + this.set(InteractionProperty.ACTIVE, active); + } + /** + * Remove the interaction from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {import("../Map.js").default|null} map Map. + */ + setMap(map) { + this.map_ = map; + } +} +function pan(view, delta, duration) { + const currentCenter = view.getCenterInternal(); + if (currentCenter) { + const center = [currentCenter[0] + delta[0], currentCenter[1] + delta[1]]; + view.animateInternal({ + duration: duration !== void 0 ? duration : 250, + easing: linear, + center: view.getConstrainedCenter(center) + }); + } +} +function zoomByDelta(view, delta, anchor, duration) { + const currentZoom = view.getZoom(); + if (currentZoom === void 0) { + return; + } + const newZoom = view.getConstrainedZoom(currentZoom + delta); + const newResolution = view.getResolutionForZoom(newZoom); + if (view.getAnimating()) { + view.cancelAnimations(); + } + view.animate({ + resolution: newResolution, + anchor, + duration: duration !== void 0 ? duration : 250, + easing: easeOut + }); +} +const Interaction$1 = Interaction; +class DoubleClickZoom extends Interaction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + super(); + options = options ? options : {}; + this.delta_ = options.delta ? options.delta : 1; + this.duration_ = options.duration !== void 0 ? options.duration : 250; + } + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a + * doubleclick) and eventually zooms the map. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + */ + handleEvent(mapBrowserEvent) { + let stopEvent = false; + if (mapBrowserEvent.type == MapBrowserEventType.DBLCLICK) { + const browserEvent = ( + /** @type {MouseEvent} */ + mapBrowserEvent.originalEvent + ); + const map = mapBrowserEvent.map; + const anchor = mapBrowserEvent.coordinate; + const delta = browserEvent.shiftKey ? -this.delta_ : this.delta_; + const view = map.getView(); + zoomByDelta(view, delta, anchor, this.duration_); + browserEvent.preventDefault(); + stopEvent = true; + } + return !stopEvent; + } +} +const DoubleClickZoom$1 = DoubleClickZoom; +class PointerInteraction extends Interaction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + super( + /** @type {import("./Interaction.js").InteractionOptions} */ + options + ); + if (options.handleDownEvent) { + this.handleDownEvent = options.handleDownEvent; + } + if (options.handleDragEvent) { + this.handleDragEvent = options.handleDragEvent; + } + if (options.handleMoveEvent) { + this.handleMoveEvent = options.handleMoveEvent; + } + if (options.handleUpEvent) { + this.handleUpEvent = options.handleUpEvent; + } + if (options.stopDown) { + this.stopDown = options.stopDown; + } + this.handlingDownUpSequence = false; + this.targetPointers = []; + } + /** + * Returns the current number of pointers involved in the interaction, + * e.g. `2` when two fingers are used. + * @return {number} The number of pointers. + * @api + */ + getPointerCount() { + return this.targetPointers.length; + } + /** + * Handle pointer down events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + * @protected + */ + handleDownEvent(mapBrowserEvent) { + return false; + } + /** + * Handle pointer drag events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @protected + */ + handleDragEvent(mapBrowserEvent) { + } + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may call into + * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are + * detected. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + * @api + */ + handleEvent(mapBrowserEvent) { + if (!mapBrowserEvent.originalEvent) { + return true; + } + let stopEvent = false; + this.updateTrackedPointers_(mapBrowserEvent); + if (this.handlingDownUpSequence) { + if (mapBrowserEvent.type == MapBrowserEventType.POINTERDRAG) { + this.handleDragEvent(mapBrowserEvent); + mapBrowserEvent.originalEvent.preventDefault(); + } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) { + const handledUp = this.handleUpEvent(mapBrowserEvent); + this.handlingDownUpSequence = handledUp && this.targetPointers.length > 0; + } + } else { + if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) { + const handled = this.handleDownEvent(mapBrowserEvent); + this.handlingDownUpSequence = handled; + stopEvent = this.stopDown(handled); + } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE) { + this.handleMoveEvent(mapBrowserEvent); + } + } + return !stopEvent; + } + /** + * Handle pointer move events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @protected + */ + handleMoveEvent(mapBrowserEvent) { + } + /** + * Handle pointer up events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + * @protected + */ + handleUpEvent(mapBrowserEvent) { + return false; + } + /** + * This function is used to determine if "down" events should be propagated + * to other interactions or should be stopped. + * @param {boolean} handled Was the event handled by the interaction? + * @return {boolean} Should the `down` event be stopped? + */ + stopDown(handled) { + return handled; + } + /** + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @private + */ + updateTrackedPointers_(mapBrowserEvent) { + if (mapBrowserEvent.activePointers) { + this.targetPointers = mapBrowserEvent.activePointers; + } + } +} +function centroid(pointerEvents) { + const length = pointerEvents.length; + let clientX = 0; + let clientY = 0; + for (let i = 0; i < length; i++) { + clientX += pointerEvents[i].clientX; + clientY += pointerEvents[i].clientY; + } + return { clientX: clientX / length, clientY: clientY / length }; +} +const PointerInteraction$1 = PointerInteraction; +function all$1(var_args) { + const conditions = arguments; + return function(event) { + let pass = true; + for (let i = 0, ii = conditions.length; i < ii; ++i) { + pass = pass && conditions[i](event); + if (!pass) { + break; + } + } + return pass; + }; +} +const altShiftKeysOnly = function(mapBrowserEvent) { + const originalEvent = ( + /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ + mapBrowserEvent.originalEvent + ); + return originalEvent.altKey && !(originalEvent.metaKey || originalEvent.ctrlKey) && originalEvent.shiftKey; +}; +const focus = function(event) { + const targetElement = event.map.getTargetElement(); + const activeElement = event.map.getOwnerDocument().activeElement; + return targetElement.contains(activeElement); +}; +const focusWithTabindex = function(event) { + return event.map.getTargetElement().hasAttribute("tabindex") ? focus(event) : true; +}; +const always$1 = TRUE; +const click = function(mapBrowserEvent) { + return mapBrowserEvent.type == MapBrowserEventType.CLICK; +}; +const mouseActionButton = function(mapBrowserEvent) { + const originalEvent = ( + /** @type {MouseEvent} */ + mapBrowserEvent.originalEvent + ); + return originalEvent.button == 0 && !(WEBKIT && MAC && originalEvent.ctrlKey); +}; +const never = FALSE; +const pointerMove = function(mapBrowserEvent) { + return mapBrowserEvent.type == "pointermove"; +}; +const singleClick = function(mapBrowserEvent) { + return mapBrowserEvent.type == MapBrowserEventType.SINGLECLICK; +}; +const noModifierKeys = function(mapBrowserEvent) { + const originalEvent = ( + /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ + mapBrowserEvent.originalEvent + ); + return !originalEvent.altKey && !(originalEvent.metaKey || originalEvent.ctrlKey) && !originalEvent.shiftKey; +}; +const platformModifierKeyOnly = function(mapBrowserEvent) { + const originalEvent = ( + /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ + mapBrowserEvent.originalEvent + ); + return !originalEvent.altKey && (MAC ? originalEvent.metaKey : originalEvent.ctrlKey) && !originalEvent.shiftKey; +}; +const platformModifierKey = function(mapBrowserEvent) { + const originalEvent = ( + /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ + mapBrowserEvent.originalEvent + ); + return MAC ? originalEvent.metaKey : originalEvent.ctrlKey; +}; +const shiftKeyOnly = function(mapBrowserEvent) { + const originalEvent = ( + /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ + mapBrowserEvent.originalEvent + ); + return !originalEvent.altKey && !(originalEvent.metaKey || originalEvent.ctrlKey) && originalEvent.shiftKey; +}; +const targetNotEditable = function(mapBrowserEvent) { + const originalEvent = ( + /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ + mapBrowserEvent.originalEvent + ); + const tagName = ( + /** @type {Element} */ + originalEvent.target.tagName + ); + return tagName !== "INPUT" && tagName !== "SELECT" && tagName !== "TEXTAREA" && // `isContentEditable` is only available on `HTMLElement`, but it may also be a + // different type like `SVGElement`. + // @ts-ignore + !originalEvent.target.isContentEditable; +}; +const mouseOnly = function(mapBrowserEvent) { + const pointerEvent = ( + /** @type {import("../MapBrowserEvent").default} */ + mapBrowserEvent.originalEvent + ); + assert( + pointerEvent !== void 0, + "mapBrowserEvent must originate from a pointer event" + ); + return pointerEvent.pointerType == "mouse"; +}; +const primaryAction = function(mapBrowserEvent) { + const pointerEvent = ( + /** @type {import("../MapBrowserEvent").default} */ + mapBrowserEvent.originalEvent + ); + assert( + pointerEvent !== void 0, + "mapBrowserEvent must originate from a pointer event" + ); + return pointerEvent.isPrimary && pointerEvent.button === 0; +}; +class DragPan extends PointerInteraction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + super({ + stopDown: FALSE + }); + options = options ? options : {}; + this.kinetic_ = options.kinetic; + this.lastCentroid = null; + this.lastPointersCount_; + this.panning_ = false; + const condition = options.condition ? options.condition : all$1(noModifierKeys, primaryAction); + this.condition_ = options.onFocusOnly ? all$1(focusWithTabindex, condition) : condition; + this.noKinetic_ = false; + } + /** + * Handle pointer drag events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + */ + handleDragEvent(mapBrowserEvent) { + const map = mapBrowserEvent.map; + if (!this.panning_) { + this.panning_ = true; + map.getView().beginInteraction(); + } + const targetPointers = this.targetPointers; + const centroid$1 = map.getEventPixel(centroid(targetPointers)); + if (targetPointers.length == this.lastPointersCount_) { + if (this.kinetic_) { + this.kinetic_.update(centroid$1[0], centroid$1[1]); + } + if (this.lastCentroid) { + const delta = [ + this.lastCentroid[0] - centroid$1[0], + centroid$1[1] - this.lastCentroid[1] + ]; + const map2 = mapBrowserEvent.map; + const view = map2.getView(); + scale$2(delta, view.getResolution()); + rotate$1(delta, view.getRotation()); + view.adjustCenterInternal(delta); + } + } else if (this.kinetic_) { + this.kinetic_.begin(); + } + this.lastCentroid = centroid$1; + this.lastPointersCount_ = targetPointers.length; + mapBrowserEvent.originalEvent.preventDefault(); + } + /** + * Handle pointer up events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleUpEvent(mapBrowserEvent) { + const map = mapBrowserEvent.map; + const view = map.getView(); + if (this.targetPointers.length === 0) { + if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) { + const distance = this.kinetic_.getDistance(); + const angle = this.kinetic_.getAngle(); + const center = view.getCenterInternal(); + const centerpx = map.getPixelFromCoordinateInternal(center); + const dest = map.getCoordinateFromPixelInternal([ + centerpx[0] - distance * Math.cos(angle), + centerpx[1] - distance * Math.sin(angle) + ]); + view.animateInternal({ + center: view.getConstrainedCenter(dest), + duration: 500, + easing: easeOut + }); + } + if (this.panning_) { + this.panning_ = false; + view.endInteraction(); + } + return false; + } + if (this.kinetic_) { + this.kinetic_.begin(); + } + this.lastCentroid = null; + return true; + } + /** + * Handle pointer down events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleDownEvent(mapBrowserEvent) { + if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) { + const map = mapBrowserEvent.map; + const view = map.getView(); + this.lastCentroid = null; + if (view.getAnimating()) { + view.cancelAnimations(); + } + if (this.kinetic_) { + this.kinetic_.begin(); + } + this.noKinetic_ = this.targetPointers.length > 1; + return true; + } + return false; + } +} +const OlInteractionDragPan = DragPan; +class DragRotate extends PointerInteraction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + super({ + stopDown: FALSE + }); + this.condition_ = options.condition ? options.condition : altShiftKeysOnly; + this.lastAngle_ = void 0; + this.duration_ = options.duration !== void 0 ? options.duration : 250; + } + /** + * Handle pointer drag events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + */ + handleDragEvent(mapBrowserEvent) { + if (!mouseOnly(mapBrowserEvent)) { + return; + } + const map = mapBrowserEvent.map; + const view = map.getView(); + if (view.getConstraints().rotation === disable) { + return; + } + const size = map.getSize(); + const offset = mapBrowserEvent.pixel; + const theta = Math.atan2(size[1] / 2 - offset[1], offset[0] - size[0] / 2); + if (this.lastAngle_ !== void 0) { + const delta = theta - this.lastAngle_; + view.adjustRotationInternal(-delta); + } + this.lastAngle_ = theta; + } + /** + * Handle pointer up events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleUpEvent(mapBrowserEvent) { + if (!mouseOnly(mapBrowserEvent)) { + return true; + } + const map = mapBrowserEvent.map; + const view = map.getView(); + view.endInteraction(this.duration_); + return false; + } + /** + * Handle pointer down events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleDownEvent(mapBrowserEvent) { + if (!mouseOnly(mapBrowserEvent)) { + return false; + } + if (mouseActionButton(mapBrowserEvent) && this.condition_(mapBrowserEvent)) { + const map = mapBrowserEvent.map; + map.getView().beginInteraction(); + this.lastAngle_ = void 0; + return true; + } + return false; + } +} +const DragRotate$1 = DragRotate; +class RenderBox extends Disposable$1 { + /** + * @param {string} className CSS class name. + */ + constructor(className) { + super(); + this.geometry_ = null; + this.element_ = document.createElement("div"); + this.element_.style.position = "absolute"; + this.element_.style.pointerEvents = "auto"; + this.element_.className = "ol-box " + className; + this.map_ = null; + this.startPixel_ = null; + this.endPixel_ = null; + } + /** + * Clean up. + */ + disposeInternal() { + this.setMap(null); + } + /** + * @private + */ + render_() { + const startPixel = this.startPixel_; + const endPixel = this.endPixel_; + const px = "px"; + const style = this.element_.style; + style.left = Math.min(startPixel[0], endPixel[0]) + px; + style.top = Math.min(startPixel[1], endPixel[1]) + px; + style.width = Math.abs(endPixel[0] - startPixel[0]) + px; + style.height = Math.abs(endPixel[1] - startPixel[1]) + px; + } + /** + * @param {import("../Map.js").default|null} map Map. + */ + setMap(map) { + if (this.map_) { + this.map_.getOverlayContainer().removeChild(this.element_); + const style = this.element_.style; + style.left = "inherit"; + style.top = "inherit"; + style.width = "inherit"; + style.height = "inherit"; + } + this.map_ = map; + if (this.map_) { + this.map_.getOverlayContainer().appendChild(this.element_); + } + } + /** + * @param {import("../pixel.js").Pixel} startPixel Start pixel. + * @param {import("../pixel.js").Pixel} endPixel End pixel. + */ + setPixels(startPixel, endPixel) { + this.startPixel_ = startPixel; + this.endPixel_ = endPixel; + this.createOrUpdateGeometry(); + this.render_(); + } + /** + * Creates or updates the cached geometry. + */ + createOrUpdateGeometry() { + const startPixel = this.startPixel_; + const endPixel = this.endPixel_; + const pixels = [ + startPixel, + [startPixel[0], endPixel[1]], + endPixel, + [endPixel[0], startPixel[1]] + ]; + const coordinates2 = pixels.map( + this.map_.getCoordinateFromPixelInternal, + this.map_ + ); + coordinates2[4] = coordinates2[0].slice(); + if (!this.geometry_) { + this.geometry_ = new Polygon$1([coordinates2]); + } else { + this.geometry_.setCoordinates([coordinates2]); + } + } + /** + * @return {import("../geom/Polygon.js").default} Geometry. + */ + getGeometry() { + return this.geometry_; + } +} +const RenderBox$1 = RenderBox; +const DragBoxEventType = { + /** + * Triggered upon drag box start. + * @event DragBoxEvent#boxstart + * @api + */ + BOXSTART: "boxstart", + /** + * Triggered on drag when box is active. + * @event DragBoxEvent#boxdrag + * @api + */ + BOXDRAG: "boxdrag", + /** + * Triggered upon drag box end. + * @event DragBoxEvent#boxend + * @api + */ + BOXEND: "boxend", + /** + * Triggered upon drag box canceled. + * @event DragBoxEvent#boxcancel + * @api + */ + BOXCANCEL: "boxcancel" +}; +class DragBoxEvent extends Event { + /** + * @param {string} type The event type. + * @param {import("../coordinate.js").Coordinate} coordinate The event coordinate. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Originating event. + */ + constructor(type, coordinate, mapBrowserEvent) { + super(type); + this.coordinate = coordinate; + this.mapBrowserEvent = mapBrowserEvent; + } +} +class DragBox extends PointerInteraction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + super(); + this.on; + this.once; + this.un; + options = options ? options : {}; + this.box_ = new RenderBox$1(options.className || "ol-dragbox"); + this.minArea_ = options.minArea !== void 0 ? options.minArea : 64; + if (options.onBoxEnd) { + this.onBoxEnd = options.onBoxEnd; + } + this.startPixel_ = null; + this.condition_ = options.condition ? options.condition : mouseActionButton; + this.boxEndCondition_ = options.boxEndCondition ? options.boxEndCondition : this.defaultBoxEndCondition; + } + /** + * The default condition for determining whether the boxend event + * should fire. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent The originating MapBrowserEvent + * leading to the box end. + * @param {import("../pixel.js").Pixel} startPixel The starting pixel of the box. + * @param {import("../pixel.js").Pixel} endPixel The end pixel of the box. + * @return {boolean} Whether or not the boxend condition should be fired. + */ + defaultBoxEndCondition(mapBrowserEvent, startPixel, endPixel) { + const width = endPixel[0] - startPixel[0]; + const height = endPixel[1] - startPixel[1]; + return width * width + height * height >= this.minArea_; + } + /** + * Returns geometry of last drawn box. + * @return {import("../geom/Polygon.js").default} Geometry. + * @api + */ + getGeometry() { + return this.box_.getGeometry(); + } + /** + * Handle pointer drag events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + */ + handleDragEvent(mapBrowserEvent) { + this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel); + this.dispatchEvent( + new DragBoxEvent( + DragBoxEventType.BOXDRAG, + mapBrowserEvent.coordinate, + mapBrowserEvent + ) + ); + } + /** + * Handle pointer up events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleUpEvent(mapBrowserEvent) { + this.box_.setMap(null); + const completeBox = this.boxEndCondition_( + mapBrowserEvent, + this.startPixel_, + mapBrowserEvent.pixel + ); + if (completeBox) { + this.onBoxEnd(mapBrowserEvent); + } + this.dispatchEvent( + new DragBoxEvent( + completeBox ? DragBoxEventType.BOXEND : DragBoxEventType.BOXCANCEL, + mapBrowserEvent.coordinate, + mapBrowserEvent + ) + ); + return false; + } + /** + * Handle pointer down events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleDownEvent(mapBrowserEvent) { + if (this.condition_(mapBrowserEvent)) { + this.startPixel_ = mapBrowserEvent.pixel; + this.box_.setMap(mapBrowserEvent.map); + this.box_.setPixels(this.startPixel_, this.startPixel_); + this.dispatchEvent( + new DragBoxEvent( + DragBoxEventType.BOXSTART, + mapBrowserEvent.coordinate, + mapBrowserEvent + ) + ); + return true; + } + return false; + } + /** + * Function to execute just before `onboxend` is fired + * @param {import("../MapBrowserEvent.js").default} event Event. + */ + onBoxEnd(event) { + } +} +const DragBox$1 = DragBox; +class DragZoom extends DragBox$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + const condition = options.condition ? options.condition : shiftKeyOnly; + super({ + condition, + className: options.className || "ol-dragzoom", + minArea: options.minArea + }); + this.duration_ = options.duration !== void 0 ? options.duration : 200; + this.out_ = options.out !== void 0 ? options.out : false; + } + /** + * Function to execute just before `onboxend` is fired + * @param {import("../MapBrowserEvent.js").default} event Event. + */ + onBoxEnd(event) { + const map = this.getMap(); + const view = ( + /** @type {!import("../View.js").default} */ + map.getView() + ); + let geometry = this.getGeometry(); + if (this.out_) { + const rotatedExtent = view.rotatedExtentForGeometry(geometry); + const resolution = view.getResolutionForExtentInternal(rotatedExtent); + const factor = view.getResolution() / resolution; + geometry = geometry.clone(); + geometry.scale(factor * factor); + } + view.fitInternal(geometry, { + duration: this.duration_, + easing: easeOut + }); + } +} +const DragZoom$1 = DragZoom; +const Key = { + LEFT: "ArrowLeft", + UP: "ArrowUp", + RIGHT: "ArrowRight", + DOWN: "ArrowDown" +}; +class KeyboardPan extends Interaction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + super(); + options = options || {}; + this.defaultCondition_ = function(mapBrowserEvent) { + return noModifierKeys(mapBrowserEvent) && targetNotEditable(mapBrowserEvent); + }; + this.condition_ = options.condition !== void 0 ? options.condition : this.defaultCondition_; + this.duration_ = options.duration !== void 0 ? options.duration : 100; + this.pixelDelta_ = options.pixelDelta !== void 0 ? options.pixelDelta : 128; + } + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a + * `KeyEvent`, and decides the direction to pan to (if an arrow key was + * pressed). + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + */ + handleEvent(mapBrowserEvent) { + let stopEvent = false; + if (mapBrowserEvent.type == EventType.KEYDOWN) { + const keyEvent = ( + /** @type {KeyboardEvent} */ + mapBrowserEvent.originalEvent + ); + const key = keyEvent.key; + if (this.condition_(mapBrowserEvent) && (key == Key.DOWN || key == Key.LEFT || key == Key.RIGHT || key == Key.UP)) { + const map = mapBrowserEvent.map; + const view = map.getView(); + const mapUnitsDelta = view.getResolution() * this.pixelDelta_; + let deltaX = 0, deltaY = 0; + if (key == Key.DOWN) { + deltaY = -mapUnitsDelta; + } else if (key == Key.LEFT) { + deltaX = -mapUnitsDelta; + } else if (key == Key.RIGHT) { + deltaX = mapUnitsDelta; + } else { + deltaY = mapUnitsDelta; + } + const delta = [deltaX, deltaY]; + rotate$1(delta, view.getRotation()); + pan(view, delta, this.duration_); + keyEvent.preventDefault(); + stopEvent = true; + } + } + return !stopEvent; + } +} +const KeyboardPan$1 = KeyboardPan; +class KeyboardZoom extends Interaction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + super(); + options = options ? options : {}; + this.condition_ = options.condition ? options.condition : function(mapBrowserEvent) { + return !platformModifierKey(mapBrowserEvent) && targetNotEditable(mapBrowserEvent); + }; + this.delta_ = options.delta ? options.delta : 1; + this.duration_ = options.duration !== void 0 ? options.duration : 100; + } + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a + * `KeyEvent`, and decides whether to zoom in or out (depending on whether the + * key pressed was '+' or '-'). + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + */ + handleEvent(mapBrowserEvent) { + let stopEvent = false; + if (mapBrowserEvent.type == EventType.KEYDOWN || mapBrowserEvent.type == EventType.KEYPRESS) { + const keyEvent = ( + /** @type {KeyboardEvent} */ + mapBrowserEvent.originalEvent + ); + const key = keyEvent.key; + if (this.condition_(mapBrowserEvent) && (key === "+" || key === "-")) { + const map = mapBrowserEvent.map; + const delta = key === "+" ? this.delta_ : -this.delta_; + const view = map.getView(); + zoomByDelta(view, delta, void 0, this.duration_); + keyEvent.preventDefault(); + stopEvent = true; + } + } + return !stopEvent; + } +} +const KeyboardZoom$1 = KeyboardZoom; +class Kinetic { + /** + * @param {number} decay Rate of decay (must be negative). + * @param {number} minVelocity Minimum velocity (pixels/millisecond). + * @param {number} delay Delay to consider to calculate the kinetic + * initial values (milliseconds). + */ + constructor(decay, minVelocity, delay) { + this.decay_ = decay; + this.minVelocity_ = minVelocity; + this.delay_ = delay; + this.points_ = []; + this.angle_ = 0; + this.initialVelocity_ = 0; + } + /** + * FIXME empty description for jsdoc + */ + begin() { + this.points_.length = 0; + this.angle_ = 0; + this.initialVelocity_ = 0; + } + /** + * @param {number} x X. + * @param {number} y Y. + */ + update(x, y) { + this.points_.push(x, y, Date.now()); + } + /** + * @return {boolean} Whether we should do kinetic animation. + */ + end() { + if (this.points_.length < 6) { + return false; + } + const delay = Date.now() - this.delay_; + const lastIndex = this.points_.length - 3; + if (this.points_[lastIndex + 2] < delay) { + return false; + } + let firstIndex = lastIndex - 3; + while (firstIndex > 0 && this.points_[firstIndex + 2] > delay) { + firstIndex -= 3; + } + const duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2]; + if (duration < 1e3 / 60) { + return false; + } + const dx = this.points_[lastIndex] - this.points_[firstIndex]; + const dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1]; + this.angle_ = Math.atan2(dy, dx); + this.initialVelocity_ = Math.sqrt(dx * dx + dy * dy) / duration; + return this.initialVelocity_ > this.minVelocity_; + } + /** + * @return {number} Total distance travelled (pixels). + */ + getDistance() { + return (this.minVelocity_ - this.initialVelocity_) / this.decay_; + } + /** + * @return {number} Angle of the kinetic panning animation (radians). + */ + getAngle() { + return this.angle_; + } +} +const Kinetic$1 = Kinetic; +class MouseWheelZoom extends Interaction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + super( + /** @type {import("./Interaction.js").InteractionOptions} */ + options + ); + this.totalDelta_ = 0; + this.lastDelta_ = 0; + this.maxDelta_ = options.maxDelta !== void 0 ? options.maxDelta : 1; + this.duration_ = options.duration !== void 0 ? options.duration : 250; + this.timeout_ = options.timeout !== void 0 ? options.timeout : 80; + this.useAnchor_ = options.useAnchor !== void 0 ? options.useAnchor : true; + this.constrainResolution_ = options.constrainResolution !== void 0 ? options.constrainResolution : false; + const condition = options.condition ? options.condition : always$1; + this.condition_ = options.onFocusOnly ? all$1(focusWithTabindex, condition) : condition; + this.lastAnchor_ = null; + this.startTime_ = void 0; + this.timeoutId_; + this.mode_ = void 0; + this.trackpadEventGap_ = 400; + this.trackpadTimeoutId_; + this.deltaPerZoom_ = 300; + } + /** + * @private + */ + endInteraction_() { + this.trackpadTimeoutId_ = void 0; + const map = this.getMap(); + if (!map) { + return; + } + const view = map.getView(); + view.endInteraction( + void 0, + this.lastDelta_ ? this.lastDelta_ > 0 ? 1 : -1 : 0, + this.lastAnchor_ + ); + } + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a mousewheel-event) and eventually + * zooms the map. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + */ + handleEvent(mapBrowserEvent) { + if (!this.condition_(mapBrowserEvent)) { + return true; + } + const type = mapBrowserEvent.type; + if (type !== EventType.WHEEL) { + return true; + } + const map = mapBrowserEvent.map; + const wheelEvent = ( + /** @type {WheelEvent} */ + mapBrowserEvent.originalEvent + ); + wheelEvent.preventDefault(); + if (this.useAnchor_) { + this.lastAnchor_ = mapBrowserEvent.coordinate; + } + let delta; + if (mapBrowserEvent.type == EventType.WHEEL) { + delta = wheelEvent.deltaY; + if (FIREFOX && wheelEvent.deltaMode === WheelEvent.DOM_DELTA_PIXEL) { + delta /= DEVICE_PIXEL_RATIO; + } + if (wheelEvent.deltaMode === WheelEvent.DOM_DELTA_LINE) { + delta *= 40; + } + } + if (delta === 0) { + return false; + } + this.lastDelta_ = delta; + const now = Date.now(); + if (this.startTime_ === void 0) { + this.startTime_ = now; + } + if (!this.mode_ || now - this.startTime_ > this.trackpadEventGap_) { + this.mode_ = Math.abs(delta) < 4 ? "trackpad" : "wheel"; + } + const view = map.getView(); + if (this.mode_ === "trackpad" && !(view.getConstrainResolution() || this.constrainResolution_)) { + if (this.trackpadTimeoutId_) { + clearTimeout(this.trackpadTimeoutId_); + } else { + if (view.getAnimating()) { + view.cancelAnimations(); + } + view.beginInteraction(); + } + this.trackpadTimeoutId_ = setTimeout( + this.endInteraction_.bind(this), + this.timeout_ + ); + view.adjustZoom(-delta / this.deltaPerZoom_, this.lastAnchor_); + this.startTime_ = now; + return false; + } + this.totalDelta_ += delta; + const timeLeft = Math.max(this.timeout_ - (now - this.startTime_), 0); + clearTimeout(this.timeoutId_); + this.timeoutId_ = setTimeout( + this.handleWheelZoom_.bind(this, map), + timeLeft + ); + return false; + } + /** + * @private + * @param {import("../Map.js").default} map Map. + */ + handleWheelZoom_(map) { + const view = map.getView(); + if (view.getAnimating()) { + view.cancelAnimations(); + } + let delta = -clamp( + this.totalDelta_, + -this.maxDelta_ * this.deltaPerZoom_, + this.maxDelta_ * this.deltaPerZoom_ + ) / this.deltaPerZoom_; + if (view.getConstrainResolution() || this.constrainResolution_) { + delta = delta ? delta > 0 ? 1 : -1 : 0; + } + zoomByDelta(view, delta, this.lastAnchor_, this.duration_); + this.mode_ = void 0; + this.totalDelta_ = 0; + this.lastAnchor_ = null; + this.startTime_ = void 0; + this.timeoutId_ = void 0; + } + /** + * Enable or disable using the mouse's location as an anchor when zooming + * @param {boolean} useAnchor true to zoom to the mouse's location, false + * to zoom to the center of the map + * @api + */ + setMouseAnchor(useAnchor) { + this.useAnchor_ = useAnchor; + if (!useAnchor) { + this.lastAnchor_ = null; + } + } +} +const OlInteractionMouseWheelZoom = MouseWheelZoom; +class PinchRotate extends PointerInteraction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + const pointerOptions = ( + /** @type {import("./Pointer.js").Options} */ + options + ); + if (!pointerOptions.stopDown) { + pointerOptions.stopDown = FALSE; + } + super(pointerOptions); + this.anchor_ = null; + this.lastAngle_ = void 0; + this.rotating_ = false; + this.rotationDelta_ = 0; + this.threshold_ = options.threshold !== void 0 ? options.threshold : 0.3; + this.duration_ = options.duration !== void 0 ? options.duration : 250; + } + /** + * Handle pointer drag events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + */ + handleDragEvent(mapBrowserEvent) { + let rotationDelta = 0; + const touch0 = this.targetPointers[0]; + const touch1 = this.targetPointers[1]; + const angle = Math.atan2( + touch1.clientY - touch0.clientY, + touch1.clientX - touch0.clientX + ); + if (this.lastAngle_ !== void 0) { + const delta = angle - this.lastAngle_; + this.rotationDelta_ += delta; + if (!this.rotating_ && Math.abs(this.rotationDelta_) > this.threshold_) { + this.rotating_ = true; + } + rotationDelta = delta; + } + this.lastAngle_ = angle; + const map = mapBrowserEvent.map; + const view = map.getView(); + if (view.getConstraints().rotation === disable) { + return; + } + this.anchor_ = map.getCoordinateFromPixelInternal( + map.getEventPixel(centroid(this.targetPointers)) + ); + if (this.rotating_) { + map.render(); + view.adjustRotationInternal(rotationDelta, this.anchor_); + } + } + /** + * Handle pointer up events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleUpEvent(mapBrowserEvent) { + if (this.targetPointers.length < 2) { + const map = mapBrowserEvent.map; + const view = map.getView(); + view.endInteraction(this.duration_); + return false; + } + return true; + } + /** + * Handle pointer down events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleDownEvent(mapBrowserEvent) { + if (this.targetPointers.length >= 2) { + const map = mapBrowserEvent.map; + this.anchor_ = null; + this.lastAngle_ = void 0; + this.rotating_ = false; + this.rotationDelta_ = 0; + if (!this.handlingDownUpSequence) { + map.getView().beginInteraction(); + } + return true; + } + return false; + } +} +const PinchRotate$1 = PinchRotate; +class PinchZoom extends PointerInteraction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + const pointerOptions = ( + /** @type {import("./Pointer.js").Options} */ + options + ); + if (!pointerOptions.stopDown) { + pointerOptions.stopDown = FALSE; + } + super(pointerOptions); + this.anchor_ = null; + this.duration_ = options.duration !== void 0 ? options.duration : 400; + this.lastDistance_ = void 0; + this.lastScaleDelta_ = 1; + } + /** + * Handle pointer drag events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + */ + handleDragEvent(mapBrowserEvent) { + let scaleDelta = 1; + const touch0 = this.targetPointers[0]; + const touch1 = this.targetPointers[1]; + const dx = touch0.clientX - touch1.clientX; + const dy = touch0.clientY - touch1.clientY; + const distance = Math.sqrt(dx * dx + dy * dy); + if (this.lastDistance_ !== void 0) { + scaleDelta = this.lastDistance_ / distance; + } + this.lastDistance_ = distance; + const map = mapBrowserEvent.map; + const view = map.getView(); + if (scaleDelta != 1) { + this.lastScaleDelta_ = scaleDelta; + } + this.anchor_ = map.getCoordinateFromPixelInternal( + map.getEventPixel(centroid(this.targetPointers)) + ); + map.render(); + view.adjustResolutionInternal(scaleDelta, this.anchor_); + } + /** + * Handle pointer up events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleUpEvent(mapBrowserEvent) { + if (this.targetPointers.length < 2) { + const map = mapBrowserEvent.map; + const view = map.getView(); + const direction = this.lastScaleDelta_ > 1 ? 1 : -1; + view.endInteraction(this.duration_, direction); + return false; + } + return true; + } + /** + * Handle pointer down events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + */ + handleDownEvent(mapBrowserEvent) { + if (this.targetPointers.length >= 2) { + const map = mapBrowserEvent.map; + this.anchor_ = null; + this.lastDistance_ = void 0; + this.lastScaleDelta_ = 1; + if (!this.handlingDownUpSequence) { + map.getView().beginInteraction(); + } + return true; + } + return false; + } +} +const PinchZoom$1 = PinchZoom; +function defaults(options) { + options = options ? options : {}; + const interactions = new Collection$1(); + const kinetic = new Kinetic$1(-5e-3, 0.05, 100); + const altShiftDragRotate = options.altShiftDragRotate !== void 0 ? options.altShiftDragRotate : true; + if (altShiftDragRotate) { + interactions.push(new DragRotate$1()); + } + const doubleClickZoom = options.doubleClickZoom !== void 0 ? options.doubleClickZoom : true; + if (doubleClickZoom) { + interactions.push( + new DoubleClickZoom$1({ + delta: options.zoomDelta, + duration: options.zoomDuration + }) + ); + } + const dragPan = options.dragPan !== void 0 ? options.dragPan : true; + if (dragPan) { + interactions.push( + new OlInteractionDragPan({ + onFocusOnly: options.onFocusOnly, + kinetic + }) + ); + } + const pinchRotate = options.pinchRotate !== void 0 ? options.pinchRotate : true; + if (pinchRotate) { + interactions.push(new PinchRotate$1()); + } + const pinchZoom = options.pinchZoom !== void 0 ? options.pinchZoom : true; + if (pinchZoom) { + interactions.push( + new PinchZoom$1({ + duration: options.zoomDuration + }) + ); + } + const keyboard = options.keyboard !== void 0 ? options.keyboard : true; + if (keyboard) { + interactions.push(new KeyboardPan$1()); + interactions.push( + new KeyboardZoom$1({ + delta: options.zoomDelta, + duration: options.zoomDuration + }) + ); + } + const mouseWheelZoom = options.mouseWheelZoom !== void 0 ? options.mouseWheelZoom : true; + if (mouseWheelZoom) { + interactions.push( + new OlInteractionMouseWheelZoom({ + onFocusOnly: options.onFocusOnly, + duration: options.zoomDuration + }) + ); + } + const shiftDragZoom = options.shiftDragZoom !== void 0 ? options.shiftDragZoom : true; + if (shiftDragZoom) { + interactions.push( + new DragZoom$1({ + duration: options.zoomDuration + }) + ); + } + return interactions; +} +function hasArea(size) { + return size[0] > 0 && size[1] > 0; +} +function scale(size, ratio, dest) { + if (dest === void 0) { + dest = [0, 0]; + } + dest[0] = size[0] * ratio + 0.5 | 0; + dest[1] = size[1] * ratio + 0.5 | 0; + return dest; +} +function toSize(size, dest) { + if (Array.isArray(size)) { + return size; + } + if (dest === void 0) { + dest = [size, size]; + } else { + dest[0] = size; + dest[1] = size; + } + return dest; +} +function removeLayerMapProperty(layer) { + if (layer instanceof Layer$1) { + layer.setMapInternal(null); + return; + } + if (layer instanceof LayerGroup$1) { + layer.getLayers().forEach(removeLayerMapProperty); + } +} +function setLayerMapProperty(layer, map) { + if (layer instanceof Layer$1) { + layer.setMapInternal(map); + return; + } + if (layer instanceof LayerGroup$1) { + const layers = layer.getLayers().getArray(); + for (let i = 0, ii = layers.length; i < ii; ++i) { + setLayerMapProperty(layers[i], map); + } + } +} +class Map extends BaseObject$1 { + /** + * @param {MapOptions} [options] Map options. + */ + constructor(options) { + super(); + options = options || {}; + this.on; + this.once; + this.un; + const optionsInternal = createOptionsInternal(options); + this.renderComplete_; + this.loaded_ = true; + this.boundHandleBrowserEvent_ = this.handleBrowserEvent.bind(this); + this.maxTilesLoading_ = options.maxTilesLoading !== void 0 ? options.maxTilesLoading : 16; + this.pixelRatio_ = options.pixelRatio !== void 0 ? options.pixelRatio : DEVICE_PIXEL_RATIO; + this.postRenderTimeoutHandle_; + this.animationDelayKey_; + this.animationDelay_ = this.animationDelay_.bind(this); + this.coordinateToPixelTransform_ = create(); + this.pixelToCoordinateTransform_ = create(); + this.frameIndex_ = 0; + this.frameState_ = null; + this.previousExtent_ = null; + this.viewPropertyListenerKey_ = null; + this.viewChangeListenerKey_ = null; + this.layerGroupPropertyListenerKeys_ = null; + this.viewport_ = document.createElement("div"); + this.viewport_.className = "ol-viewport" + ("ontouchstart" in window ? " ol-touch" : ""); + this.viewport_.style.position = "relative"; + this.viewport_.style.overflow = "hidden"; + this.viewport_.style.width = "100%"; + this.viewport_.style.height = "100%"; + this.overlayContainer_ = document.createElement("div"); + this.overlayContainer_.style.position = "absolute"; + this.overlayContainer_.style.zIndex = "0"; + this.overlayContainer_.style.width = "100%"; + this.overlayContainer_.style.height = "100%"; + this.overlayContainer_.style.pointerEvents = "none"; + this.overlayContainer_.className = "ol-overlaycontainer"; + this.viewport_.appendChild(this.overlayContainer_); + this.overlayContainerStopEvent_ = document.createElement("div"); + this.overlayContainerStopEvent_.style.position = "absolute"; + this.overlayContainerStopEvent_.style.zIndex = "0"; + this.overlayContainerStopEvent_.style.width = "100%"; + this.overlayContainerStopEvent_.style.height = "100%"; + this.overlayContainerStopEvent_.style.pointerEvents = "none"; + this.overlayContainerStopEvent_.className = "ol-overlaycontainer-stopevent"; + this.viewport_.appendChild(this.overlayContainerStopEvent_); + this.mapBrowserEventHandler_ = null; + this.moveTolerance_ = options.moveTolerance; + this.keyboardEventTarget_ = optionsInternal.keyboardEventTarget; + this.targetChangeHandlerKeys_ = null; + this.targetElement_ = null; + this.resizeObserver_ = new ResizeObserver(() => this.updateSize()); + this.controls = optionsInternal.controls || defaults$1(); + this.interactions = optionsInternal.interactions || defaults({ + onFocusOnly: true + }); + this.overlays_ = optionsInternal.overlays; + this.overlayIdIndex_ = {}; + this.renderer_ = null; + this.postRenderFunctions_ = []; + this.tileQueue_ = new TileQueue$1( + this.getTilePriority.bind(this), + this.handleTileChange_.bind(this) + ); + this.addChangeListener( + MapProperty.LAYERGROUP, + this.handleLayerGroupChanged_ + ); + this.addChangeListener(MapProperty.VIEW, this.handleViewChanged_); + this.addChangeListener(MapProperty.SIZE, this.handleSizeChanged_); + this.addChangeListener(MapProperty.TARGET, this.handleTargetChanged_); + this.setProperties(optionsInternal.values); + const map = this; + if (options.view && !(options.view instanceof OlView)) { + options.view.then(function(viewOptions) { + map.setView(new OlView(viewOptions)); + }); + } + this.controls.addEventListener( + CollectionEventType.ADD, + /** + * @param {import("./Collection.js").CollectionEvent} event CollectionEvent + */ + (event) => { + event.element.setMap(this); + } + ); + this.controls.addEventListener( + CollectionEventType.REMOVE, + /** + * @param {import("./Collection.js").CollectionEvent} event CollectionEvent. + */ + (event) => { + event.element.setMap(null); + } + ); + this.interactions.addEventListener( + CollectionEventType.ADD, + /** + * @param {import("./Collection.js").CollectionEvent} event CollectionEvent. + */ + (event) => { + event.element.setMap(this); + } + ); + this.interactions.addEventListener( + CollectionEventType.REMOVE, + /** + * @param {import("./Collection.js").CollectionEvent} event CollectionEvent. + */ + (event) => { + event.element.setMap(null); + } + ); + this.overlays_.addEventListener( + CollectionEventType.ADD, + /** + * @param {import("./Collection.js").CollectionEvent} event CollectionEvent. + */ + (event) => { + this.addOverlayInternal_(event.element); + } + ); + this.overlays_.addEventListener( + CollectionEventType.REMOVE, + /** + * @param {import("./Collection.js").CollectionEvent} event CollectionEvent. + */ + (event) => { + const id = event.element.getId(); + if (id !== void 0) { + delete this.overlayIdIndex_[id.toString()]; + } + event.element.setMap(null); + } + ); + this.controls.forEach( + /** + * @param {import("./control/Control.js").default} control Control. + */ + (control) => { + control.setMap(this); + } + ); + this.interactions.forEach( + /** + * @param {import("./interaction/Interaction.js").default} interaction Interaction. + */ + (interaction) => { + interaction.setMap(this); + } + ); + this.overlays_.forEach(this.addOverlayInternal_.bind(this)); + } + /** + * Add the given control to the map. + * @param {import("./control/Control.js").default} control Control. + * @api + */ + addControl(control) { + this.getControls().push(control); + } + /** + * Add the given interaction to the map. If you want to add an interaction + * at another point of the collection use `getInteractions()` and the methods + * available on {@link module:ol/Collection~Collection}. This can be used to + * stop the event propagation from the handleEvent function. The interactions + * get to handle the events in the reverse order of this collection. + * @param {import("./interaction/Interaction.js").default} interaction Interaction to add. + * @api + */ + addInteraction(interaction) { + this.getInteractions().push(interaction); + } + /** + * Adds the given layer to the top of this map. If you want to add a layer + * elsewhere in the stack, use `getLayers()` and the methods available on + * {@link module:ol/Collection~Collection}. + * @param {import("./layer/Base.js").default} layer Layer. + * @api + */ + addLayer(layer) { + const layers = this.getLayerGroup().getLayers(); + layers.push(layer); + } + /** + * @param {import("./layer/Group.js").GroupEvent} event The layer add event. + * @private + */ + handleLayerAdd_(event) { + setLayerMapProperty(event.layer, this); + } + /** + * Add the given overlay to the map. + * @param {import("./Overlay.js").default} overlay Overlay. + * @api + */ + addOverlay(overlay) { + this.getOverlays().push(overlay); + } + /** + * This deals with map's overlay collection changes. + * @param {import("./Overlay.js").default} overlay Overlay. + * @private + */ + addOverlayInternal_(overlay) { + const id = overlay.getId(); + if (id !== void 0) { + this.overlayIdIndex_[id.toString()] = overlay; + } + overlay.setMap(this); + } + /** + * + * Clean up. + */ + disposeInternal() { + this.controls.clear(); + this.interactions.clear(); + this.overlays_.clear(); + this.resizeObserver_.disconnect(); + this.setTarget(null); + super.disposeInternal(); + } + /** + * Detect features that intersect a pixel on the viewport, and execute a + * callback with each intersecting feature. Layers included in the detection can + * be configured through the `layerFilter` option in `options`. + * @param {import("./pixel.js").Pixel} pixel Pixel. + * @param {function(import("./Feature.js").FeatureLike, import("./layer/Layer.js").default, import("./geom/SimpleGeometry.js").default): T} callback Feature callback. The callback will be + * called with two arguments. The first argument is one + * {@link module:ol/Feature~Feature feature} or + * {@link module:ol/render/Feature~RenderFeature render feature} at the pixel, the second is + * the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for + * unmanaged layers. To stop detection, callback functions can return a + * truthy value. + * @param {AtPixelOptions} [options] Optional options. + * @return {T|undefined} Callback result, i.e. the return value of last + * callback execution, or the first truthy callback return value. + * @template T + * @api + */ + forEachFeatureAtPixel(pixel, callback, options) { + if (!this.frameState_ || !this.renderer_) { + return; + } + const coordinate = this.getCoordinateFromPixelInternal(pixel); + options = options !== void 0 ? options : {}; + const hitTolerance = options.hitTolerance !== void 0 ? options.hitTolerance : 0; + const layerFilter = options.layerFilter !== void 0 ? options.layerFilter : TRUE; + const checkWrapped = options.checkWrapped !== false; + return this.renderer_.forEachFeatureAtCoordinate( + coordinate, + this.frameState_, + hitTolerance, + checkWrapped, + callback, + null, + layerFilter, + null + ); + } + /** + * Get all features that intersect a pixel on the viewport. + * @param {import("./pixel.js").Pixel} pixel Pixel. + * @param {AtPixelOptions} [options] Optional options. + * @return {Array} The detected features or + * an empty array if none were found. + * @api + */ + getFeaturesAtPixel(pixel, options) { + const features = []; + this.forEachFeatureAtPixel( + pixel, + function(feature) { + features.push(feature); + }, + options + ); + return features; + } + /** + * Get all layers from all layer groups. + * @return {Array} Layers. + * @api + */ + getAllLayers() { + const layers = []; + function addLayersFrom(layerGroup) { + layerGroup.forEach(function(layer) { + if (layer instanceof LayerGroup$1) { + addLayersFrom(layer.getLayers()); + } else { + layers.push(layer); + } + }); + } + addLayersFrom(this.getLayers()); + return layers; + } + /** + * Detect if features intersect a pixel on the viewport. Layers included in the + * detection can be configured through the `layerFilter` option. + * @param {import("./pixel.js").Pixel} pixel Pixel. + * @param {AtPixelOptions} [options] Optional options. + * @return {boolean} Is there a feature at the given pixel? + * @api + */ + hasFeatureAtPixel(pixel, options) { + if (!this.frameState_ || !this.renderer_) { + return false; + } + const coordinate = this.getCoordinateFromPixelInternal(pixel); + options = options !== void 0 ? options : {}; + const layerFilter = options.layerFilter !== void 0 ? options.layerFilter : TRUE; + const hitTolerance = options.hitTolerance !== void 0 ? options.hitTolerance : 0; + const checkWrapped = options.checkWrapped !== false; + return this.renderer_.hasFeatureAtCoordinate( + coordinate, + this.frameState_, + hitTolerance, + checkWrapped, + layerFilter, + null + ); + } + /** + * Returns the coordinate in user projection for a browser event. + * @param {MouseEvent} event Event. + * @return {import("./coordinate.js").Coordinate} Coordinate. + * @api + */ + getEventCoordinate(event) { + return this.getCoordinateFromPixel(this.getEventPixel(event)); + } + /** + * Returns the coordinate in view projection for a browser event. + * @param {MouseEvent} event Event. + * @return {import("./coordinate.js").Coordinate} Coordinate. + */ + getEventCoordinateInternal(event) { + return this.getCoordinateFromPixelInternal(this.getEventPixel(event)); + } + /** + * Returns the map pixel position for a browser event relative to the viewport. + * @param {UIEvent|{clientX: number, clientY: number}} event Event. + * @return {import("./pixel.js").Pixel} Pixel. + * @api + */ + getEventPixel(event) { + const viewport = this.viewport_; + const viewportPosition = viewport.getBoundingClientRect(); + const viewportSize = this.getSize(); + const scaleX = viewportPosition.width / viewportSize[0]; + const scaleY = viewportPosition.height / viewportSize[1]; + const eventPosition = ( + //FIXME Are we really calling this with a TouchEvent anywhere? + "changedTouches" in event ? ( + /** @type {TouchEvent} */ + event.changedTouches[0] + ) : ( + /** @type {MouseEvent} */ + event + ) + ); + return [ + (eventPosition.clientX - viewportPosition.left) / scaleX, + (eventPosition.clientY - viewportPosition.top) / scaleY + ]; + } + /** + * Get the target in which this map is rendered. + * Note that this returns what is entered as an option or in setTarget: + * if that was an element, it returns an element; if a string, it returns that. + * @return {HTMLElement|string|undefined} The Element or id of the Element that the + * map is rendered in. + * @observable + * @api + */ + getTarget() { + return ( + /** @type {HTMLElement|string|undefined} */ + this.get(MapProperty.TARGET) + ); + } + /** + * Get the DOM element into which this map is rendered. In contrast to + * `getTarget` this method always return an `Element`, or `null` if the + * map has no target. + * @return {HTMLElement} The element that the map is rendered in. + * @api + */ + getTargetElement() { + return this.targetElement_; + } + /** + * Get the coordinate for a given pixel. This returns a coordinate in the + * user projection. + * @param {import("./pixel.js").Pixel} pixel Pixel position in the map viewport. + * @return {import("./coordinate.js").Coordinate} The coordinate for the pixel position. + * @api + */ + getCoordinateFromPixel(pixel) { + return toUserCoordinate( + this.getCoordinateFromPixelInternal(pixel), + this.getView().getProjection() + ); + } + /** + * Get the coordinate for a given pixel. This returns a coordinate in the + * map view projection. + * @param {import("./pixel.js").Pixel} pixel Pixel position in the map viewport. + * @return {import("./coordinate.js").Coordinate} The coordinate for the pixel position. + */ + getCoordinateFromPixelInternal(pixel) { + const frameState = this.frameState_; + if (!frameState) { + return null; + } + return apply(frameState.pixelToCoordinateTransform, pixel.slice()); + } + /** + * Get the map controls. Modifying this collection changes the controls + * associated with the map. + * @return {Collection} Controls. + * @api + */ + getControls() { + return this.controls; + } + /** + * Get the map overlays. Modifying this collection changes the overlays + * associated with the map. + * @return {Collection} Overlays. + * @api + */ + getOverlays() { + return this.overlays_; + } + /** + * Get an overlay by its identifier (the value returned by overlay.getId()). + * Note that the index treats string and numeric identifiers as the same. So + * `map.getOverlayById(2)` will return an overlay with id `'2'` or `2`. + * @param {string|number} id Overlay identifier. + * @return {import("./Overlay.js").default} Overlay. + * @api + */ + getOverlayById(id) { + const overlay = this.overlayIdIndex_[id.toString()]; + return overlay !== void 0 ? overlay : null; + } + /** + * Get the map interactions. Modifying this collection changes the interactions + * associated with the map. + * + * Interactions are used for e.g. pan, zoom and rotate. + * @return {Collection} Interactions. + * @api + */ + getInteractions() { + return this.interactions; + } + /** + * Get the layergroup associated with this map. + * @return {LayerGroup} A layer group containing the layers in this map. + * @observable + * @api + */ + getLayerGroup() { + return ( + /** @type {LayerGroup} */ + this.get(MapProperty.LAYERGROUP) + ); + } + /** + * Clear any existing layers and add layers to the map. + * @param {Array|Collection} layers The layers to be added to the map. + * @api + */ + setLayers(layers) { + const group = this.getLayerGroup(); + if (layers instanceof Collection$1) { + group.setLayers(layers); + return; + } + const collection = group.getLayers(); + collection.clear(); + collection.extend(layers); + } + /** + * Get the collection of layers associated with this map. + * @return {!Collection} Layers. + * @api + */ + getLayers() { + const layers = this.getLayerGroup().getLayers(); + return layers; + } + /** + * @return {boolean} Layers have sources that are still loading. + */ + getLoadingOrNotReady() { + const layerStatesArray = this.getLayerGroup().getLayerStatesArray(); + for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) { + const state = layerStatesArray[i]; + if (!state.visible) { + continue; + } + const renderer = state.layer.getRenderer(); + if (renderer && !renderer.ready) { + return true; + } + const source = state.layer.getSource(); + if (source && source.loading) { + return true; + } + } + return false; + } + /** + * Get the pixel for a coordinate. This takes a coordinate in the user + * projection and returns the corresponding pixel. + * @param {import("./coordinate.js").Coordinate} coordinate A map coordinate. + * @return {import("./pixel.js").Pixel} A pixel position in the map viewport. + * @api + */ + getPixelFromCoordinate(coordinate) { + const viewCoordinate = fromUserCoordinate( + coordinate, + this.getView().getProjection() + ); + return this.getPixelFromCoordinateInternal(viewCoordinate); + } + /** + * Get the pixel for a coordinate. This takes a coordinate in the map view + * projection and returns the corresponding pixel. + * @param {import("./coordinate.js").Coordinate} coordinate A map coordinate. + * @return {import("./pixel.js").Pixel} A pixel position in the map viewport. + */ + getPixelFromCoordinateInternal(coordinate) { + const frameState = this.frameState_; + if (!frameState) { + return null; + } + return apply( + frameState.coordinateToPixelTransform, + coordinate.slice(0, 2) + ); + } + /** + * Get the map renderer. + * @return {import("./renderer/Map.js").default|null} Renderer + */ + getRenderer() { + return this.renderer_; + } + /** + * Get the size of this map. + * @return {import("./size.js").Size|undefined} The size in pixels of the map in the DOM. + * @observable + * @api + */ + getSize() { + return ( + /** @type {import("./size.js").Size|undefined} */ + this.get(MapProperty.SIZE) + ); + } + /** + * Get the view associated with this map. A view manages properties such as + * center and resolution. + * @return {View} The view that controls this map. + * @observable + * @api + */ + getView() { + return ( + /** @type {View} */ + this.get(MapProperty.VIEW) + ); + } + /** + * Get the element that serves as the map viewport. + * @return {HTMLElement} Viewport. + * @api + */ + getViewport() { + return this.viewport_; + } + /** + * Get the element that serves as the container for overlays. Elements added to + * this container will let mousedown and touchstart events through to the map, + * so clicks and gestures on an overlay will trigger {@link module:ol/MapBrowserEvent~MapBrowserEvent} + * events. + * @return {!HTMLElement} The map's overlay container. + */ + getOverlayContainer() { + return this.overlayContainer_; + } + /** + * Get the element that serves as a container for overlays that don't allow + * event propagation. Elements added to this container won't let mousedown and + * touchstart events through to the map, so clicks and gestures on an overlay + * don't trigger any {@link module:ol/MapBrowserEvent~MapBrowserEvent}. + * @return {!HTMLElement} The map's overlay container that stops events. + */ + getOverlayContainerStopEvent() { + return this.overlayContainerStopEvent_; + } + /** + * @return {!Document} The document where the map is displayed. + */ + getOwnerDocument() { + const targetElement = this.getTargetElement(); + return targetElement ? targetElement.ownerDocument : document; + } + /** + * @param {import("./Tile.js").default} tile Tile. + * @param {string} tileSourceKey Tile source key. + * @param {import("./coordinate.js").Coordinate} tileCenter Tile center. + * @param {number} tileResolution Tile resolution. + * @return {number} Tile priority. + */ + getTilePriority(tile, tileSourceKey, tileCenter, tileResolution) { + return getTilePriority( + this.frameState_, + tile, + tileSourceKey, + tileCenter, + tileResolution + ); + } + /** + * @param {UIEvent} browserEvent Browser event. + * @param {string} [type] Type. + */ + handleBrowserEvent(browserEvent, type) { + type = type || browserEvent.type; + const mapBrowserEvent = new MapBrowserEvent$1(type, this, browserEvent); + this.handleMapBrowserEvent(mapBrowserEvent); + } + /** + * @param {MapBrowserEvent} mapBrowserEvent The event to handle. + */ + handleMapBrowserEvent(mapBrowserEvent) { + if (!this.frameState_) { + return; + } + const originalEvent = ( + /** @type {PointerEvent} */ + mapBrowserEvent.originalEvent + ); + const eventType = originalEvent.type; + if (eventType === PointerEventType.POINTERDOWN || eventType === EventType.WHEEL || eventType === EventType.KEYDOWN) { + const doc = this.getOwnerDocument(); + const rootNode = this.viewport_.getRootNode ? this.viewport_.getRootNode() : doc; + const target = ( + /** @type {Node} */ + originalEvent.target + ); + if ( + // Abort if the target is a child of the container for elements whose events are not meant + // to be handled by map interactions. + this.overlayContainerStopEvent_.contains(target) || // Abort if the event target is a child of the container that is no longer in the page. + // It's possible for the target to no longer be in the page if it has been removed in an + // event listener, this might happen in a Control that recreates it's content based on + // user interaction either manually or via a render in something like https://reactjs.org/ + !(rootNode === doc ? doc.documentElement : rootNode).contains(target) + ) { + return; + } + } + mapBrowserEvent.frameState = this.frameState_; + if (this.dispatchEvent(mapBrowserEvent) !== false) { + const interactionsArray = this.getInteractions().getArray().slice(); + for (let i = interactionsArray.length - 1; i >= 0; i--) { + const interaction = interactionsArray[i]; + if (interaction.getMap() !== this || !interaction.getActive() || !this.getTargetElement()) { + continue; + } + const cont = interaction.handleEvent(mapBrowserEvent); + if (!cont || mapBrowserEvent.propagationStopped) { + break; + } + } + } + } + /** + * @protected + */ + handlePostRender() { + const frameState = this.frameState_; + const tileQueue = this.tileQueue_; + if (!tileQueue.isEmpty()) { + let maxTotalLoading = this.maxTilesLoading_; + let maxNewLoads = maxTotalLoading; + if (frameState) { + const hints = frameState.viewHints; + if (hints[ViewHint.ANIMATING] || hints[ViewHint.INTERACTING]) { + const lowOnFrameBudget = Date.now() - frameState.time > 8; + maxTotalLoading = lowOnFrameBudget ? 0 : 8; + maxNewLoads = lowOnFrameBudget ? 0 : 2; + } + } + if (tileQueue.getTilesLoading() < maxTotalLoading) { + tileQueue.reprioritize(); + tileQueue.loadMoreTiles(maxTotalLoading, maxNewLoads); + } + } + if (frameState && this.renderer_ && !frameState.animate) { + if (this.renderComplete_ === true) { + if (this.hasListener(RenderEventType.RENDERCOMPLETE)) { + this.renderer_.dispatchRenderEvent( + RenderEventType.RENDERCOMPLETE, + frameState + ); + } + if (this.loaded_ === false) { + this.loaded_ = true; + this.dispatchEvent( + new MapEvent$1(MapEventType.LOADEND, this, frameState) + ); + } + } else if (this.loaded_ === true) { + this.loaded_ = false; + this.dispatchEvent( + new MapEvent$1(MapEventType.LOADSTART, this, frameState) + ); + } + } + const postRenderFunctions = this.postRenderFunctions_; + for (let i = 0, ii = postRenderFunctions.length; i < ii; ++i) { + postRenderFunctions[i](this, frameState); + } + postRenderFunctions.length = 0; + } + /** + * @private + */ + handleSizeChanged_() { + if (this.getView() && !this.getView().getAnimating()) { + this.getView().resolveConstraints(0); + } + this.render(); + } + /** + * @private + */ + handleTargetChanged_() { + if (this.mapBrowserEventHandler_) { + for (let i = 0, ii = this.targetChangeHandlerKeys_.length; i < ii; ++i) { + unlistenByKey(this.targetChangeHandlerKeys_[i]); + } + this.targetChangeHandlerKeys_ = null; + this.viewport_.removeEventListener( + EventType.CONTEXTMENU, + this.boundHandleBrowserEvent_ + ); + this.viewport_.removeEventListener( + EventType.WHEEL, + this.boundHandleBrowserEvent_ + ); + this.mapBrowserEventHandler_.dispose(); + this.mapBrowserEventHandler_ = null; + removeNode(this.viewport_); + } + if (this.targetElement_) { + this.resizeObserver_.unobserve(this.targetElement_); + const rootNode = this.targetElement_.getRootNode(); + if (rootNode instanceof ShadowRoot) { + this.resizeObserver_.unobserve(rootNode.host); + } + this.setSize(void 0); + } + const target = this.getTarget(); + const targetElement = typeof target === "string" ? document.getElementById(target) : target; + this.targetElement_ = targetElement; + if (!targetElement) { + if (this.renderer_) { + clearTimeout(this.postRenderTimeoutHandle_); + this.postRenderTimeoutHandle_ = void 0; + this.postRenderFunctions_.length = 0; + this.renderer_.dispose(); + this.renderer_ = null; + } + if (this.animationDelayKey_) { + cancelAnimationFrame(this.animationDelayKey_); + this.animationDelayKey_ = void 0; + } + } else { + targetElement.appendChild(this.viewport_); + if (!this.renderer_) { + this.renderer_ = new CompositeMapRenderer$1(this); + } + this.mapBrowserEventHandler_ = new MapBrowserEventHandler$1( + this, + this.moveTolerance_ + ); + for (const key in MapBrowserEventType) { + this.mapBrowserEventHandler_.addEventListener( + MapBrowserEventType[key], + this.handleMapBrowserEvent.bind(this) + ); + } + this.viewport_.addEventListener( + EventType.CONTEXTMENU, + this.boundHandleBrowserEvent_, + false + ); + this.viewport_.addEventListener( + EventType.WHEEL, + this.boundHandleBrowserEvent_, + PASSIVE_EVENT_LISTENERS ? { passive: false } : false + ); + const keyboardEventTarget = !this.keyboardEventTarget_ ? targetElement : this.keyboardEventTarget_; + this.targetChangeHandlerKeys_ = [ + listen( + keyboardEventTarget, + EventType.KEYDOWN, + this.handleBrowserEvent, + this + ), + listen( + keyboardEventTarget, + EventType.KEYPRESS, + this.handleBrowserEvent, + this + ) + ]; + const rootNode = targetElement.getRootNode(); + if (rootNode instanceof ShadowRoot) { + this.resizeObserver_.observe(rootNode.host); + } + this.resizeObserver_.observe(targetElement); + } + this.updateSize(); + } + /** + * @private + */ + handleTileChange_() { + this.render(); + } + /** + * @private + */ + handleViewPropertyChanged_() { + this.render(); + } + /** + * @private + */ + handleViewChanged_() { + if (this.viewPropertyListenerKey_) { + unlistenByKey(this.viewPropertyListenerKey_); + this.viewPropertyListenerKey_ = null; + } + if (this.viewChangeListenerKey_) { + unlistenByKey(this.viewChangeListenerKey_); + this.viewChangeListenerKey_ = null; + } + const view = this.getView(); + if (view) { + this.updateViewportSize_(); + this.viewPropertyListenerKey_ = listen( + view, + ObjectEventType.PROPERTYCHANGE, + this.handleViewPropertyChanged_, + this + ); + this.viewChangeListenerKey_ = listen( + view, + EventType.CHANGE, + this.handleViewPropertyChanged_, + this + ); + view.resolveConstraints(0); + } + this.render(); + } + /** + * @private + */ + handleLayerGroupChanged_() { + if (this.layerGroupPropertyListenerKeys_) { + this.layerGroupPropertyListenerKeys_.forEach(unlistenByKey); + this.layerGroupPropertyListenerKeys_ = null; + } + const layerGroup = this.getLayerGroup(); + if (layerGroup) { + this.handleLayerAdd_(new GroupEvent("addlayer", layerGroup)); + this.layerGroupPropertyListenerKeys_ = [ + listen(layerGroup, ObjectEventType.PROPERTYCHANGE, this.render, this), + listen(layerGroup, EventType.CHANGE, this.render, this), + listen(layerGroup, "addlayer", this.handleLayerAdd_, this), + listen(layerGroup, "removelayer", this.handleLayerRemove_, this) + ]; + } + this.render(); + } + /** + * @return {boolean} Is rendered. + */ + isRendered() { + return !!this.frameState_; + } + /** + * @private + */ + animationDelay_() { + this.animationDelayKey_ = void 0; + this.renderFrame_(Date.now()); + } + /** + * Requests an immediate render in a synchronous manner. + * @api + */ + renderSync() { + if (this.animationDelayKey_) { + cancelAnimationFrame(this.animationDelayKey_); + } + this.animationDelay_(); + } + /** + * Redraws all text after new fonts have loaded + */ + redrawText() { + const layerStates = this.getLayerGroup().getLayerStatesArray(); + for (let i = 0, ii = layerStates.length; i < ii; ++i) { + const layer = layerStates[i].layer; + if (layer.hasRenderer()) { + layer.getRenderer().handleFontsChanged(); + } + } + } + /** + * Request a map rendering (at the next animation frame). + * @api + */ + render() { + if (this.renderer_ && this.animationDelayKey_ === void 0) { + this.animationDelayKey_ = requestAnimationFrame(this.animationDelay_); + } + } + /** + * This method is meant to be called in a layer's `prerender` listener. It causes all collected + * declutter items to be decluttered and rendered on the map immediately. This is useful for + * layers that need to appear entirely above the decluttered items of layers lower in the layer + * stack. + * @api + */ + flushDeclutterItems() { + const frameState = this.frameState_; + if (!frameState) { + return; + } + this.renderer_.flushDeclutterItems(frameState); + } + /** + * Remove the given control from the map. + * @param {import("./control/Control.js").default} control Control. + * @return {import("./control/Control.js").default|undefined} The removed control (or undefined + * if the control was not found). + * @api + */ + removeControl(control) { + return this.getControls().remove(control); + } + /** + * Remove the given interaction from the map. + * @param {import("./interaction/Interaction.js").default} interaction Interaction to remove. + * @return {import("./interaction/Interaction.js").default|undefined} The removed interaction (or + * undefined if the interaction was not found). + * @api + */ + removeInteraction(interaction) { + return this.getInteractions().remove(interaction); + } + /** + * Removes the given layer from the map. + * @param {import("./layer/Base.js").default} layer Layer. + * @return {import("./layer/Base.js").default|undefined} The removed layer (or undefined if the + * layer was not found). + * @api + */ + removeLayer(layer) { + const layers = this.getLayerGroup().getLayers(); + return layers.remove(layer); + } + /** + * @param {import("./layer/Group.js").GroupEvent} event The layer remove event. + * @private + */ + handleLayerRemove_(event) { + removeLayerMapProperty(event.layer); + } + /** + * Remove the given overlay from the map. + * @param {import("./Overlay.js").default} overlay Overlay. + * @return {import("./Overlay.js").default|undefined} The removed overlay (or undefined + * if the overlay was not found). + * @api + */ + removeOverlay(overlay) { + return this.getOverlays().remove(overlay); + } + /** + * @param {number} time Time. + * @private + */ + renderFrame_(time) { + const size = this.getSize(); + const view = this.getView(); + const previousFrameState = this.frameState_; + let frameState = null; + if (size !== void 0 && hasArea(size) && view && view.isDef()) { + const viewHints = view.getHints( + this.frameState_ ? this.frameState_.viewHints : void 0 + ); + const viewState = view.getState(); + frameState = { + animate: false, + coordinateToPixelTransform: this.coordinateToPixelTransform_, + declutterTree: null, + extent: getForViewAndSize( + viewState.center, + viewState.resolution, + viewState.rotation, + size + ), + index: this.frameIndex_++, + layerIndex: 0, + layerStatesArray: this.getLayerGroup().getLayerStatesArray(), + pixelRatio: this.pixelRatio_, + pixelToCoordinateTransform: this.pixelToCoordinateTransform_, + postRenderFunctions: [], + size, + tileQueue: this.tileQueue_, + time, + usedTiles: {}, + viewState, + viewHints, + wantedTiles: {}, + mapId: getUid(this), + renderTargets: {} + }; + if (viewState.nextCenter && viewState.nextResolution) { + const rotation = isNaN(viewState.nextRotation) ? viewState.rotation : viewState.nextRotation; + frameState.nextExtent = getForViewAndSize( + viewState.nextCenter, + viewState.nextResolution, + rotation, + size + ); + } + } + this.frameState_ = frameState; + this.renderer_.renderFrame(frameState); + if (frameState) { + if (frameState.animate) { + this.render(); + } + Array.prototype.push.apply( + this.postRenderFunctions_, + frameState.postRenderFunctions + ); + if (previousFrameState) { + const moveStart = !this.previousExtent_ || !isEmpty(this.previousExtent_) && !equals$1(frameState.extent, this.previousExtent_); + if (moveStart) { + this.dispatchEvent( + new MapEvent$1(MapEventType.MOVESTART, this, previousFrameState) + ); + this.previousExtent_ = createOrUpdateEmpty(this.previousExtent_); + } + } + const idle = this.previousExtent_ && !frameState.viewHints[ViewHint.ANIMATING] && !frameState.viewHints[ViewHint.INTERACTING] && !equals$1(frameState.extent, this.previousExtent_); + if (idle) { + this.dispatchEvent( + new MapEvent$1(MapEventType.MOVEEND, this, frameState) + ); + clone(frameState.extent, this.previousExtent_); + } + } + this.dispatchEvent(new MapEvent$1(MapEventType.POSTRENDER, this, frameState)); + this.renderComplete_ = this.hasListener(MapEventType.LOADSTART) || this.hasListener(MapEventType.LOADEND) || this.hasListener(RenderEventType.RENDERCOMPLETE) ? !this.tileQueue_.getTilesLoading() && !this.tileQueue_.getCount() && !this.getLoadingOrNotReady() : void 0; + if (!this.postRenderTimeoutHandle_) { + this.postRenderTimeoutHandle_ = setTimeout(() => { + this.postRenderTimeoutHandle_ = void 0; + this.handlePostRender(); + }, 0); + } + } + /** + * Sets the layergroup of this map. + * @param {LayerGroup} layerGroup A layer group containing the layers in this map. + * @observable + * @api + */ + setLayerGroup(layerGroup) { + const oldLayerGroup = this.getLayerGroup(); + if (oldLayerGroup) { + this.handleLayerRemove_(new GroupEvent("removelayer", oldLayerGroup)); + } + this.set(MapProperty.LAYERGROUP, layerGroup); + } + /** + * Set the size of this map. + * @param {import("./size.js").Size|undefined} size The size in pixels of the map in the DOM. + * @observable + * @api + */ + setSize(size) { + this.set(MapProperty.SIZE, size); + } + /** + * Set the target element to render this map into. + * @param {HTMLElement|string} [target] The Element or id of the Element + * that the map is rendered in. + * @observable + * @api + */ + setTarget(target) { + this.set(MapProperty.TARGET, target); + } + /** + * Set the view for this map. + * @param {View|Promise} view The view that controls this map. + * It is also possible to pass a promise that resolves to options for constructing a view. This + * alternative allows view properties to be resolved by sources or other components that load + * view-related metadata. + * @observable + * @api + */ + setView(view) { + if (!view || view instanceof OlView) { + this.set(MapProperty.VIEW, view); + return; + } + this.set(MapProperty.VIEW, new OlView()); + const map = this; + view.then(function(viewOptions) { + map.setView(new OlView(viewOptions)); + }); + } + /** + * Force a recalculation of the map viewport size. This should be called when + * third-party code changes the size of the map viewport. + * @api + */ + updateSize() { + const targetElement = this.getTargetElement(); + let size = void 0; + if (targetElement) { + const computedStyle = getComputedStyle(targetElement); + const width = targetElement.offsetWidth - parseFloat(computedStyle["borderLeftWidth"]) - parseFloat(computedStyle["paddingLeft"]) - parseFloat(computedStyle["paddingRight"]) - parseFloat(computedStyle["borderRightWidth"]); + const height = targetElement.offsetHeight - parseFloat(computedStyle["borderTopWidth"]) - parseFloat(computedStyle["paddingTop"]) - parseFloat(computedStyle["paddingBottom"]) - parseFloat(computedStyle["borderBottomWidth"]); + if (!isNaN(width) && !isNaN(height)) { + size = [width, height]; + if (!hasArea(size) && !!(targetElement.offsetWidth || targetElement.offsetHeight || targetElement.getClientRects().length)) { + warn( + "No map visible because the map container's width or height are 0." + ); + } + } + } + const oldSize = this.getSize(); + if (size && (!oldSize || !equals$2(size, oldSize))) { + this.setSize(size); + this.updateViewportSize_(); + } + } + /** + * Recomputes the viewport size and save it on the view object (if any) + * @private + */ + updateViewportSize_() { + const view = this.getView(); + if (view) { + let size = void 0; + const computedStyle = getComputedStyle(this.viewport_); + if (computedStyle.width && computedStyle.height) { + size = [ + parseInt(computedStyle.width, 10), + parseInt(computedStyle.height, 10) + ]; + } + view.setViewportSize(size); + } + } +} +function createOptionsInternal(options) { + let keyboardEventTarget = null; + if (options.keyboardEventTarget !== void 0) { + keyboardEventTarget = typeof options.keyboardEventTarget === "string" ? document.getElementById(options.keyboardEventTarget) : options.keyboardEventTarget; + } + const values = {}; + const layerGroup = options.layers && typeof /** @type {?} */ + options.layers.getLayers === "function" ? ( + /** @type {LayerGroup} */ + options.layers + ) : new LayerGroup$1({ + layers: ( + /** @type {Collection|Array} */ + options.layers + ) + }); + values[MapProperty.LAYERGROUP] = layerGroup; + values[MapProperty.TARGET] = options.target; + values[MapProperty.VIEW] = options.view instanceof OlView ? options.view : new OlView(); + let controls; + if (options.controls !== void 0) { + if (Array.isArray(options.controls)) { + controls = new Collection$1(options.controls.slice()); + } else { + assert( + typeof /** @type {?} */ + options.controls.getArray === "function", + "Expected `controls` to be an array or an `ol/Collection.js`" + ); + controls = options.controls; + } + } + let interactions; + if (options.interactions !== void 0) { + if (Array.isArray(options.interactions)) { + interactions = new Collection$1(options.interactions.slice()); + } else { + assert( + typeof /** @type {?} */ + options.interactions.getArray === "function", + "Expected `interactions` to be an array or an `ol/Collection.js`" + ); + interactions = options.interactions; + } + } + let overlays; + if (options.overlays !== void 0) { + if (Array.isArray(options.overlays)) { + overlays = new Collection$1(options.overlays.slice()); + } else { + assert( + typeof /** @type {?} */ + options.overlays.getArray === "function", + "Expected `overlays` to be an array or an `ol/Collection.js`" + ); + overlays = options.overlays; + } + } else { + overlays = new Collection$1(); + } + return { + controls, + interactions, + keyboardEventTarget, + overlays, + values + }; +} +const OlMap = Map; +const ImageState = { + IDLE: 0, + LOADING: 1, + LOADED: 2, + ERROR: 3, + EMPTY: 4 +}; +class ImageStyle { + /** + * @param {Options} options Options. + */ + constructor(options) { + this.opacity_ = options.opacity; + this.rotateWithView_ = options.rotateWithView; + this.rotation_ = options.rotation; + this.scale_ = options.scale; + this.scaleArray_ = toSize(options.scale); + this.displacement_ = options.displacement; + this.declutterMode_ = options.declutterMode; + } + /** + * Clones the style. + * @return {ImageStyle} The cloned style. + * @api + */ + clone() { + const scale2 = this.getScale(); + return new ImageStyle({ + opacity: this.getOpacity(), + scale: Array.isArray(scale2) ? scale2.slice() : scale2, + rotation: this.getRotation(), + rotateWithView: this.getRotateWithView(), + displacement: this.getDisplacement().slice(), + declutterMode: this.getDeclutterMode() + }); + } + /** + * Get the symbolizer opacity. + * @return {number} Opacity. + * @api + */ + getOpacity() { + return this.opacity_; + } + /** + * Determine whether the symbolizer rotates with the map. + * @return {boolean} Rotate with map. + * @api + */ + getRotateWithView() { + return this.rotateWithView_; + } + /** + * Get the symoblizer rotation. + * @return {number} Rotation. + * @api + */ + getRotation() { + return this.rotation_; + } + /** + * Get the symbolizer scale. + * @return {number|import("../size.js").Size} Scale. + * @api + */ + getScale() { + return this.scale_; + } + /** + * Get the symbolizer scale array. + * @return {import("../size.js").Size} Scale array. + */ + getScaleArray() { + return this.scaleArray_; + } + /** + * Get the displacement of the shape + * @return {Array} Shape's center displacement + * @api + */ + getDisplacement() { + return this.displacement_; + } + /** + * Get the declutter mode of the shape + * @return {"declutter"|"obstacle"|"none"|undefined} Shape's declutter mode + * @api + */ + getDeclutterMode() { + return this.declutterMode_; + } + /** + * Get the anchor point in pixels. The anchor determines the center point for the + * symbolizer. + * @abstract + * @return {Array} Anchor. + */ + getAnchor() { + return abstract(); + } + /** + * Get the image element for the symbolizer. + * @abstract + * @param {number} pixelRatio Pixel ratio. + * @return {import('../DataTile.js').ImageLike} Image element. + */ + getImage(pixelRatio) { + return abstract(); + } + /** + * @abstract + * @return {import('../DataTile.js').ImageLike} Image element. + */ + getHitDetectionImage() { + return abstract(); + } + /** + * Get the image pixel ratio. + * @param {number} pixelRatio Pixel ratio. + * @return {number} Pixel ratio. + */ + getPixelRatio(pixelRatio) { + return 1; + } + /** + * @abstract + * @return {import("../ImageState.js").default} Image state. + */ + getImageState() { + return abstract(); + } + /** + * @abstract + * @return {import("../size.js").Size} Image size. + */ + getImageSize() { + return abstract(); + } + /** + * Get the origin of the symbolizer. + * @abstract + * @return {Array} Origin. + */ + getOrigin() { + return abstract(); + } + /** + * Get the size of the symbolizer (in pixels). + * @abstract + * @return {import("../size.js").Size} Size. + */ + getSize() { + return abstract(); + } + /** + * Set the displacement. + * + * @param {Array} displacement Displacement. + * @api + */ + setDisplacement(displacement) { + this.displacement_ = displacement; + } + /** + * Set the opacity. + * + * @param {number} opacity Opacity. + * @api + */ + setOpacity(opacity) { + this.opacity_ = opacity; + } + /** + * Set whether to rotate the style with the view. + * + * @param {boolean} rotateWithView Rotate with map. + * @api + */ + setRotateWithView(rotateWithView) { + this.rotateWithView_ = rotateWithView; + } + /** + * Set the rotation. + * + * @param {number} rotation Rotation. + * @api + */ + setRotation(rotation) { + this.rotation_ = rotation; + } + /** + * Set the scale. + * + * @param {number|import("../size.js").Size} scale Scale. + * @api + */ + setScale(scale2) { + this.scale_ = scale2; + this.scaleArray_ = toSize(scale2); + } + /** + * @abstract + * @param {function(import("../events/Event.js").default): void} listener Listener function. + */ + listenImageChange(listener) { + abstract(); + } + /** + * Load not yet loaded URI. + * @abstract + */ + load() { + abstract(); + } + /** + * @abstract + * @param {function(import("../events/Event.js").default): void} listener Listener function. + */ + unlistenImageChange(listener) { + abstract(); + } +} +const ImageStyle$1 = ImageStyle; +function asColorLike(color) { + if (Array.isArray(color)) { + return toString(color); + } + return color; +} +class RegularShape extends ImageStyle$1 { + /** + * @param {Options} options Options. + */ + constructor(options) { + const rotateWithView = options.rotateWithView !== void 0 ? options.rotateWithView : false; + super({ + opacity: 1, + rotateWithView, + rotation: options.rotation !== void 0 ? options.rotation : 0, + scale: options.scale !== void 0 ? options.scale : 1, + displacement: options.displacement !== void 0 ? options.displacement : [0, 0], + declutterMode: options.declutterMode + }); + this.canvas_ = void 0; + this.hitDetectionCanvas_ = null; + this.fill_ = options.fill !== void 0 ? options.fill : null; + this.origin_ = [0, 0]; + this.points_ = options.points; + this.radius_ = options.radius !== void 0 ? options.radius : options.radius1; + this.radius2_ = options.radius2; + this.angle_ = options.angle !== void 0 ? options.angle : 0; + this.stroke_ = options.stroke !== void 0 ? options.stroke : null; + this.size_ = null; + this.renderOptions_ = null; + this.render(); + } + /** + * Clones the style. + * @return {RegularShape} The cloned style. + * @api + */ + clone() { + const scale2 = this.getScale(); + const style = new RegularShape({ + fill: this.getFill() ? this.getFill().clone() : void 0, + points: this.getPoints(), + radius: this.getRadius(), + radius2: this.getRadius2(), + angle: this.getAngle(), + stroke: this.getStroke() ? this.getStroke().clone() : void 0, + rotation: this.getRotation(), + rotateWithView: this.getRotateWithView(), + scale: Array.isArray(scale2) ? scale2.slice() : scale2, + displacement: this.getDisplacement().slice(), + declutterMode: this.getDeclutterMode() + }); + style.setOpacity(this.getOpacity()); + return style; + } + /** + * Get the anchor point in pixels. The anchor determines the center point for the + * symbolizer. + * @return {Array} Anchor. + * @api + */ + getAnchor() { + const size = this.size_; + if (!size) { + return null; + } + const displacement = this.getDisplacement(); + const scale2 = this.getScaleArray(); + return [ + size[0] / 2 - displacement[0] / scale2[0], + size[1] / 2 + displacement[1] / scale2[1] + ]; + } + /** + * Get the angle used in generating the shape. + * @return {number} Shape's rotation in radians. + * @api + */ + getAngle() { + return this.angle_; + } + /** + * Get the fill style for the shape. + * @return {import("./Fill.js").default} Fill style. + * @api + */ + getFill() { + return this.fill_; + } + /** + * Set the fill style. + * @param {import("./Fill.js").default} fill Fill style. + * @api + */ + setFill(fill) { + this.fill_ = fill; + this.render(); + } + /** + * @return {HTMLCanvasElement} Image element. + */ + getHitDetectionImage() { + if (!this.hitDetectionCanvas_) { + this.createHitDetectionCanvas_(this.renderOptions_); + } + return this.hitDetectionCanvas_; + } + /** + * Get the image icon. + * @param {number} pixelRatio Pixel ratio. + * @return {HTMLCanvasElement} Image or Canvas element. + * @api + */ + getImage(pixelRatio) { + let image = this.canvas_[pixelRatio]; + if (!image) { + const renderOptions = this.renderOptions_; + const context = createCanvasContext2D( + renderOptions.size * pixelRatio, + renderOptions.size * pixelRatio + ); + this.draw_(renderOptions, context, pixelRatio); + image = context.canvas; + this.canvas_[pixelRatio] = image; + } + return image; + } + /** + * Get the image pixel ratio. + * @param {number} pixelRatio Pixel ratio. + * @return {number} Pixel ratio. + */ + getPixelRatio(pixelRatio) { + return pixelRatio; + } + /** + * @return {import("../size.js").Size} Image size. + */ + getImageSize() { + return this.size_; + } + /** + * @return {import("../ImageState.js").default} Image state. + */ + getImageState() { + return ImageState.LOADED; + } + /** + * Get the origin of the symbolizer. + * @return {Array} Origin. + * @api + */ + getOrigin() { + return this.origin_; + } + /** + * Get the number of points for generating the shape. + * @return {number} Number of points for stars and regular polygons. + * @api + */ + getPoints() { + return this.points_; + } + /** + * Get the (primary) radius for the shape. + * @return {number} Radius. + * @api + */ + getRadius() { + return this.radius_; + } + /** + * Get the secondary radius for the shape. + * @return {number|undefined} Radius2. + * @api + */ + getRadius2() { + return this.radius2_; + } + /** + * Get the size of the symbolizer (in pixels). + * @return {import("../size.js").Size} Size. + * @api + */ + getSize() { + return this.size_; + } + /** + * Get the stroke style for the shape. + * @return {import("./Stroke.js").default} Stroke style. + * @api + */ + getStroke() { + return this.stroke_; + } + /** + * Set the stroke style. + * @param {import("./Stroke.js").default} stroke Stroke style. + * @api + */ + setStroke(stroke) { + this.stroke_ = stroke; + this.render(); + } + /** + * @param {function(import("../events/Event.js").default): void} listener Listener function. + */ + listenImageChange(listener) { + } + /** + * Load not yet loaded URI. + */ + load() { + } + /** + * @param {function(import("../events/Event.js").default): void} listener Listener function. + */ + unlistenImageChange(listener) { + } + /** + * Calculate additional canvas size needed for the miter. + * @param {string} lineJoin Line join + * @param {number} strokeWidth Stroke width + * @param {number} miterLimit Miter limit + * @return {number} Additional canvas size needed + * @private + */ + calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit) { + if (strokeWidth === 0 || this.points_ === Infinity || lineJoin !== "bevel" && lineJoin !== "miter") { + return strokeWidth; + } + let r1 = this.radius_; + let r2 = this.radius2_ === void 0 ? r1 : this.radius2_; + if (r1 < r2) { + const tmp = r1; + r1 = r2; + r2 = tmp; + } + const points = this.radius2_ === void 0 ? this.points_ : this.points_ * 2; + const alpha = 2 * Math.PI / points; + const a = r2 * Math.sin(alpha); + const b = Math.sqrt(r2 * r2 - a * a); + const d = r1 - b; + const e = Math.sqrt(a * a + d * d); + const miterRatio = e / a; + if (lineJoin === "miter" && miterRatio <= miterLimit) { + return miterRatio * strokeWidth; + } + const k = strokeWidth / 2 / miterRatio; + const l = strokeWidth / 2 * (d / e); + const maxr = Math.sqrt((r1 + k) * (r1 + k) + l * l); + const bevelAdd = maxr - r1; + if (this.radius2_ === void 0 || lineJoin === "bevel") { + return bevelAdd * 2; + } + const aa = r1 * Math.sin(alpha); + const bb = Math.sqrt(r1 * r1 - aa * aa); + const dd = r2 - bb; + const ee = Math.sqrt(aa * aa + dd * dd); + const innerMiterRatio = ee / aa; + if (innerMiterRatio <= miterLimit) { + const innerLength = innerMiterRatio * strokeWidth / 2 - r2 - r1; + return 2 * Math.max(bevelAdd, innerLength); + } + return bevelAdd * 2; + } + /** + * @return {RenderOptions} The render options + * @protected + */ + createRenderOptions() { + let lineCap = defaultLineCap; + let lineJoin = defaultLineJoin; + let miterLimit = 0; + let lineDash = null; + let lineDashOffset = 0; + let strokeStyle; + let strokeWidth = 0; + if (this.stroke_) { + strokeStyle = this.stroke_.getColor(); + if (strokeStyle === null) { + strokeStyle = defaultStrokeStyle; + } + strokeStyle = asColorLike(strokeStyle); + strokeWidth = this.stroke_.getWidth(); + if (strokeWidth === void 0) { + strokeWidth = defaultLineWidth; + } + lineDash = this.stroke_.getLineDash(); + lineDashOffset = this.stroke_.getLineDashOffset(); + lineJoin = this.stroke_.getLineJoin(); + if (lineJoin === void 0) { + lineJoin = defaultLineJoin; + } + lineCap = this.stroke_.getLineCap(); + if (lineCap === void 0) { + lineCap = defaultLineCap; + } + miterLimit = this.stroke_.getMiterLimit(); + if (miterLimit === void 0) { + miterLimit = defaultMiterLimit; + } + } + const add2 = this.calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit); + const maxRadius = Math.max(this.radius_, this.radius2_ || 0); + const size = Math.ceil(2 * maxRadius + add2); + return { + strokeStyle, + strokeWidth, + size, + lineCap, + lineDash, + lineDashOffset, + lineJoin, + miterLimit + }; + } + /** + * @protected + */ + render() { + this.renderOptions_ = this.createRenderOptions(); + const size = this.renderOptions_.size; + this.canvas_ = {}; + this.size_ = [size, size]; + } + /** + * @private + * @param {RenderOptions} renderOptions Render options. + * @param {CanvasRenderingContext2D} context The rendering context. + * @param {number} pixelRatio The pixel ratio. + */ + draw_(renderOptions, context, pixelRatio) { + context.scale(pixelRatio, pixelRatio); + context.translate(renderOptions.size / 2, renderOptions.size / 2); + this.createPath_(context); + if (this.fill_) { + let color = this.fill_.getColor(); + if (color === null) { + color = defaultFillStyle; + } + context.fillStyle = asColorLike(color); + context.fill(); + } + if (this.stroke_) { + context.strokeStyle = renderOptions.strokeStyle; + context.lineWidth = renderOptions.strokeWidth; + if (renderOptions.lineDash) { + context.setLineDash(renderOptions.lineDash); + context.lineDashOffset = renderOptions.lineDashOffset; + } + context.lineCap = renderOptions.lineCap; + context.lineJoin = renderOptions.lineJoin; + context.miterLimit = renderOptions.miterLimit; + context.stroke(); + } + } + /** + * @private + * @param {RenderOptions} renderOptions Render options. + */ + createHitDetectionCanvas_(renderOptions) { + if (this.fill_) { + let color = this.fill_.getColor(); + let opacity = 0; + if (typeof color === "string") { + color = asArray(color); + } + if (color === null) { + opacity = 1; + } else if (Array.isArray(color)) { + opacity = color.length === 4 ? color[3] : 1; + } + if (opacity === 0) { + const context = createCanvasContext2D( + renderOptions.size, + renderOptions.size + ); + this.hitDetectionCanvas_ = context.canvas; + this.drawHitDetectionCanvas_(renderOptions, context); + } + } + if (!this.hitDetectionCanvas_) { + this.hitDetectionCanvas_ = this.getImage(1); + } + } + /** + * @private + * @param {CanvasRenderingContext2D} context The context to draw in. + */ + createPath_(context) { + let points = this.points_; + const radius = this.radius_; + if (points === Infinity) { + context.arc(0, 0, radius, 0, 2 * Math.PI); + } else { + const radius2 = this.radius2_ === void 0 ? radius : this.radius2_; + if (this.radius2_ !== void 0) { + points *= 2; + } + const startAngle = this.angle_ - Math.PI / 2; + const step = 2 * Math.PI / points; + for (let i = 0; i < points; i++) { + const angle0 = startAngle + i * step; + const radiusC = i % 2 === 0 ? radius : radius2; + context.lineTo(radiusC * Math.cos(angle0), radiusC * Math.sin(angle0)); + } + context.closePath(); + } + } + /** + * @private + * @param {RenderOptions} renderOptions Render options. + * @param {CanvasRenderingContext2D} context The context. + */ + drawHitDetectionCanvas_(renderOptions, context) { + context.translate(renderOptions.size / 2, renderOptions.size / 2); + this.createPath_(context); + context.fillStyle = defaultFillStyle; + context.fill(); + if (this.stroke_) { + context.strokeStyle = renderOptions.strokeStyle; + context.lineWidth = renderOptions.strokeWidth; + if (renderOptions.lineDash) { + context.setLineDash(renderOptions.lineDash); + context.lineDashOffset = renderOptions.lineDashOffset; + } + context.lineJoin = renderOptions.lineJoin; + context.miterLimit = renderOptions.miterLimit; + context.stroke(); + } + } +} +const RegularShape$1 = RegularShape; +class CircleStyle extends RegularShape$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : { radius: 5 }; + super({ + points: Infinity, + fill: options.fill, + radius: options.radius, + stroke: options.stroke, + scale: options.scale !== void 0 ? options.scale : 1, + rotation: options.rotation !== void 0 ? options.rotation : 0, + rotateWithView: options.rotateWithView !== void 0 ? options.rotateWithView : false, + displacement: options.displacement !== void 0 ? options.displacement : [0, 0], + declutterMode: options.declutterMode + }); + } + /** + * Clones the style. + * @return {CircleStyle} The cloned style. + * @api + */ + clone() { + const scale2 = this.getScale(); + const style = new CircleStyle({ + fill: this.getFill() ? this.getFill().clone() : void 0, + stroke: this.getStroke() ? this.getStroke().clone() : void 0, + radius: this.getRadius(), + scale: Array.isArray(scale2) ? scale2.slice() : scale2, + rotation: this.getRotation(), + rotateWithView: this.getRotateWithView(), + displacement: this.getDisplacement().slice(), + declutterMode: this.getDeclutterMode() + }); + style.setOpacity(this.getOpacity()); + return style; + } + /** + * Set the circle radius. + * + * @param {number} radius Circle radius. + * @api + */ + setRadius(radius) { + this.radius_ = radius; + this.render(); + } +} +const Circle = CircleStyle; +class Fill { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options || {}; + this.color_ = options.color !== void 0 ? options.color : null; + } + /** + * Clones the style. The color is not cloned if it is an {@link module:ol/colorlike~ColorLike}. + * @return {Fill} The cloned style. + * @api + */ + clone() { + const color = this.getColor(); + return new Fill({ + color: Array.isArray(color) ? color.slice() : color || void 0 + }); + } + /** + * Get the fill color. + * @return {import("../color.js").Color|import("../colorlike.js").ColorLike|null} Color. + * @api + */ + getColor() { + return this.color_; + } + /** + * Set the color. + * + * @param {import("../color.js").Color|import("../colorlike.js").ColorLike|null} color Color. + * @api + */ + setColor(color) { + this.color_ = color; + } +} +const Fill$1 = Fill; +class Stroke { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options || {}; + this.color_ = options.color !== void 0 ? options.color : null; + this.lineCap_ = options.lineCap; + this.lineDash_ = options.lineDash !== void 0 ? options.lineDash : null; + this.lineDashOffset_ = options.lineDashOffset; + this.lineJoin_ = options.lineJoin; + this.miterLimit_ = options.miterLimit; + this.width_ = options.width; + } + /** + * Clones the style. + * @return {Stroke} The cloned style. + * @api + */ + clone() { + const color = this.getColor(); + return new Stroke({ + color: Array.isArray(color) ? color.slice() : color || void 0, + lineCap: this.getLineCap(), + lineDash: this.getLineDash() ? this.getLineDash().slice() : void 0, + lineDashOffset: this.getLineDashOffset(), + lineJoin: this.getLineJoin(), + miterLimit: this.getMiterLimit(), + width: this.getWidth() + }); + } + /** + * Get the stroke color. + * @return {import("../color.js").Color|import("../colorlike.js").ColorLike} Color. + * @api + */ + getColor() { + return this.color_; + } + /** + * Get the line cap type for the stroke. + * @return {CanvasLineCap|undefined} Line cap. + * @api + */ + getLineCap() { + return this.lineCap_; + } + /** + * Get the line dash style for the stroke. + * @return {Array|null} Line dash. + * @api + */ + getLineDash() { + return this.lineDash_; + } + /** + * Get the line dash offset for the stroke. + * @return {number|undefined} Line dash offset. + * @api + */ + getLineDashOffset() { + return this.lineDashOffset_; + } + /** + * Get the line join type for the stroke. + * @return {CanvasLineJoin|undefined} Line join. + * @api + */ + getLineJoin() { + return this.lineJoin_; + } + /** + * Get the miter limit for the stroke. + * @return {number|undefined} Miter limit. + * @api + */ + getMiterLimit() { + return this.miterLimit_; + } + /** + * Get the stroke width. + * @return {number|undefined} Width. + * @api + */ + getWidth() { + return this.width_; + } + /** + * Set the color. + * + * @param {import("../color.js").Color|import("../colorlike.js").ColorLike} color Color. + * @api + */ + setColor(color) { + this.color_ = color; + } + /** + * Set the line cap. + * + * @param {CanvasLineCap|undefined} lineCap Line cap. + * @api + */ + setLineCap(lineCap) { + this.lineCap_ = lineCap; + } + /** + * Set the line dash. + * + * @param {Array|null} lineDash Line dash. + * @api + */ + setLineDash(lineDash) { + this.lineDash_ = lineDash; + } + /** + * Set the line dash offset. + * + * @param {number|undefined} lineDashOffset Line dash offset. + * @api + */ + setLineDashOffset(lineDashOffset) { + this.lineDashOffset_ = lineDashOffset; + } + /** + * Set the line join. + * + * @param {CanvasLineJoin|undefined} lineJoin Line join. + * @api + */ + setLineJoin(lineJoin) { + this.lineJoin_ = lineJoin; + } + /** + * Set the miter limit. + * + * @param {number|undefined} miterLimit Miter limit. + * @api + */ + setMiterLimit(miterLimit) { + this.miterLimit_ = miterLimit; + } + /** + * Set the width. + * + * @param {number|undefined} width Width. + * @api + */ + setWidth(width) { + this.width_ = width; + } +} +const OlStroke = Stroke; +class Style { + /** + * @param {Options} [options] Style options. + */ + constructor(options) { + options = options || {}; + this.geometry_ = null; + this.geometryFunction_ = defaultGeometryFunction; + if (options.geometry !== void 0) { + this.setGeometry(options.geometry); + } + this.fill_ = options.fill !== void 0 ? options.fill : null; + this.image_ = options.image !== void 0 ? options.image : null; + this.renderer_ = options.renderer !== void 0 ? options.renderer : null; + this.hitDetectionRenderer_ = options.hitDetectionRenderer !== void 0 ? options.hitDetectionRenderer : null; + this.stroke_ = options.stroke !== void 0 ? options.stroke : null; + this.text_ = options.text !== void 0 ? options.text : null; + this.zIndex_ = options.zIndex; + } + /** + * Clones the style. + * @return {Style} The cloned style. + * @api + */ + clone() { + let geometry = this.getGeometry(); + if (geometry && typeof geometry === "object") { + geometry = /** @type {import("../geom/Geometry.js").default} */ + geometry.clone(); + } + return new Style({ + geometry, + fill: this.getFill() ? this.getFill().clone() : void 0, + image: this.getImage() ? this.getImage().clone() : void 0, + renderer: this.getRenderer(), + stroke: this.getStroke() ? this.getStroke().clone() : void 0, + text: this.getText() ? this.getText().clone() : void 0, + zIndex: this.getZIndex() + }); + } + /** + * Get the custom renderer function that was configured with + * {@link #setRenderer} or the `renderer` constructor option. + * @return {RenderFunction|null} Custom renderer function. + * @api + */ + getRenderer() { + return this.renderer_; + } + /** + * Sets a custom renderer function for this style. When set, `fill`, `stroke` + * and `image` options of the style will be ignored. + * @param {RenderFunction|null} renderer Custom renderer function. + * @api + */ + setRenderer(renderer) { + this.renderer_ = renderer; + } + /** + * Sets a custom renderer function for this style used + * in hit detection. + * @param {RenderFunction|null} renderer Custom renderer function. + * @api + */ + setHitDetectionRenderer(renderer) { + this.hitDetectionRenderer_ = renderer; + } + /** + * Get the custom renderer function that was configured with + * {@link #setHitDetectionRenderer} or the `hitDetectionRenderer` constructor option. + * @return {RenderFunction|null} Custom renderer function. + * @api + */ + getHitDetectionRenderer() { + return this.hitDetectionRenderer_; + } + /** + * Get the geometry to be rendered. + * @return {string|import("../geom/Geometry.js").default|GeometryFunction} + * Feature property or geometry or function that returns the geometry that will + * be rendered with this style. + * @api + */ + getGeometry() { + return this.geometry_; + } + /** + * Get the function used to generate a geometry for rendering. + * @return {!GeometryFunction} Function that is called with a feature + * and returns the geometry to render instead of the feature's geometry. + * @api + */ + getGeometryFunction() { + return this.geometryFunction_; + } + /** + * Get the fill style. + * @return {import("./Fill.js").default} Fill style. + * @api + */ + getFill() { + return this.fill_; + } + /** + * Set the fill style. + * @param {import("./Fill.js").default} fill Fill style. + * @api + */ + setFill(fill) { + this.fill_ = fill; + } + /** + * Get the image style. + * @return {import("./Image.js").default} Image style. + * @api + */ + getImage() { + return this.image_; + } + /** + * Set the image style. + * @param {import("./Image.js").default} image Image style. + * @api + */ + setImage(image) { + this.image_ = image; + } + /** + * Get the stroke style. + * @return {import("./Stroke.js").default} Stroke style. + * @api + */ + getStroke() { + return this.stroke_; + } + /** + * Set the stroke style. + * @param {import("./Stroke.js").default} stroke Stroke style. + * @api + */ + setStroke(stroke) { + this.stroke_ = stroke; + } + /** + * Get the text style. + * @return {import("./Text.js").default} Text style. + * @api + */ + getText() { + return this.text_; + } + /** + * Set the text style. + * @param {import("./Text.js").default} text Text style. + * @api + */ + setText(text) { + this.text_ = text; + } + /** + * Get the z-index for the style. + * @return {number|undefined} ZIndex. + * @api + */ + getZIndex() { + return this.zIndex_; + } + /** + * Set a geometry that is rendered instead of the feature's geometry. + * + * @param {string|import("../geom/Geometry.js").default|GeometryFunction} geometry + * Feature property or geometry or function returning a geometry to render + * for this style. + * @api + */ + setGeometry(geometry) { + if (typeof geometry === "function") { + this.geometryFunction_ = geometry; + } else if (typeof geometry === "string") { + this.geometryFunction_ = function(feature) { + return ( + /** @type {import("../geom/Geometry.js").default} */ + feature.get(geometry) + ); + }; + } else if (!geometry) { + this.geometryFunction_ = defaultGeometryFunction; + } else if (geometry !== void 0) { + this.geometryFunction_ = function() { + return ( + /** @type {import("../geom/Geometry.js").default} */ + geometry + ); + }; + } + this.geometry_ = geometry; + } + /** + * Set the z-index. + * + * @param {number|undefined} zIndex ZIndex. + * @api + */ + setZIndex(zIndex) { + this.zIndex_ = zIndex; + } +} +function toFunction(obj) { + let styleFunction; + if (typeof obj === "function") { + styleFunction = obj; + } else { + let styles; + if (Array.isArray(obj)) { + styles = obj; + } else { + assert( + typeof /** @type {?} */ + obj.getZIndex === "function", + "Expected an `Style` or an array of `Style`" + ); + const style = ( + /** @type {Style} */ + obj + ); + styles = [style]; + } + styleFunction = function() { + return styles; + }; + } + return styleFunction; +} +let defaultStyles = null; +function createDefaultStyle(feature, resolution) { + if (!defaultStyles) { + const fill = new Fill$1({ + color: "rgba(255,255,255,0.4)" + }); + const stroke = new OlStroke({ + color: "#3399CC", + width: 1.25 + }); + defaultStyles = [ + new Style({ + image: new Circle({ + fill, + stroke, + radius: 5 + }), + fill, + stroke + }) + ]; + } + return defaultStyles; +} +function createEditingStyle() { + const styles = {}; + const white = [255, 255, 255, 1]; + const blue = [0, 153, 255, 1]; + const width = 3; + styles["Polygon"] = [ + new Style({ + fill: new Fill$1({ + color: [255, 255, 255, 0.5] + }) + }) + ]; + styles["MultiPolygon"] = styles["Polygon"]; + styles["LineString"] = [ + new Style({ + stroke: new OlStroke({ + color: white, + width: width + 2 + }) + }), + new Style({ + stroke: new OlStroke({ + color: blue, + width + }) + }) + ]; + styles["MultiLineString"] = styles["LineString"]; + styles["Circle"] = styles["Polygon"].concat(styles["LineString"]); + styles["Point"] = [ + new Style({ + image: new Circle({ + radius: width * 2, + fill: new Fill$1({ + color: blue + }), + stroke: new OlStroke({ + color: white, + width: width / 2 + }) + }), + zIndex: Infinity + }) + ]; + styles["MultiPoint"] = styles["Point"]; + styles["GeometryCollection"] = styles["Polygon"].concat( + styles["LineString"], + styles["Point"] + ); + return styles; +} +function defaultGeometryFunction(feature) { + return feature.getGeometry(); +} +const DEFAULT_FILL_COLOR = "#333"; +class Text { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options || {}; + this.font_ = options.font; + this.rotation_ = options.rotation; + this.rotateWithView_ = options.rotateWithView; + this.scale_ = options.scale; + this.scaleArray_ = toSize(options.scale !== void 0 ? options.scale : 1); + this.text_ = options.text; + this.textAlign_ = options.textAlign; + this.justify_ = options.justify; + this.repeat_ = options.repeat; + this.textBaseline_ = options.textBaseline; + this.fill_ = options.fill !== void 0 ? options.fill : new Fill$1({ color: DEFAULT_FILL_COLOR }); + this.maxAngle_ = options.maxAngle !== void 0 ? options.maxAngle : Math.PI / 4; + this.placement_ = options.placement !== void 0 ? options.placement : "point"; + this.overflow_ = !!options.overflow; + this.stroke_ = options.stroke !== void 0 ? options.stroke : null; + this.offsetX_ = options.offsetX !== void 0 ? options.offsetX : 0; + this.offsetY_ = options.offsetY !== void 0 ? options.offsetY : 0; + this.backgroundFill_ = options.backgroundFill ? options.backgroundFill : null; + this.backgroundStroke_ = options.backgroundStroke ? options.backgroundStroke : null; + this.padding_ = options.padding === void 0 ? null : options.padding; + } + /** + * Clones the style. + * @return {Text} The cloned style. + * @api + */ + clone() { + const scale2 = this.getScale(); + return new Text({ + font: this.getFont(), + placement: this.getPlacement(), + repeat: this.getRepeat(), + maxAngle: this.getMaxAngle(), + overflow: this.getOverflow(), + rotation: this.getRotation(), + rotateWithView: this.getRotateWithView(), + scale: Array.isArray(scale2) ? scale2.slice() : scale2, + text: this.getText(), + textAlign: this.getTextAlign(), + justify: this.getJustify(), + textBaseline: this.getTextBaseline(), + fill: this.getFill() ? this.getFill().clone() : void 0, + stroke: this.getStroke() ? this.getStroke().clone() : void 0, + offsetX: this.getOffsetX(), + offsetY: this.getOffsetY(), + backgroundFill: this.getBackgroundFill() ? this.getBackgroundFill().clone() : void 0, + backgroundStroke: this.getBackgroundStroke() ? this.getBackgroundStroke().clone() : void 0, + padding: this.getPadding() || void 0 + }); + } + /** + * Get the `overflow` configuration. + * @return {boolean} Let text overflow the length of the path they follow. + * @api + */ + getOverflow() { + return this.overflow_; + } + /** + * Get the font name. + * @return {string|undefined} Font. + * @api + */ + getFont() { + return this.font_; + } + /** + * Get the maximum angle between adjacent characters. + * @return {number} Angle in radians. + * @api + */ + getMaxAngle() { + return this.maxAngle_; + } + /** + * Get the label placement. + * @return {TextPlacement} Text placement. + * @api + */ + getPlacement() { + return this.placement_; + } + /** + * Get the repeat interval of the text. + * @return {number|undefined} Repeat interval in pixels. + * @api + */ + getRepeat() { + return this.repeat_; + } + /** + * Get the x-offset for the text. + * @return {number} Horizontal text offset. + * @api + */ + getOffsetX() { + return this.offsetX_; + } + /** + * Get the y-offset for the text. + * @return {number} Vertical text offset. + * @api + */ + getOffsetY() { + return this.offsetY_; + } + /** + * Get the fill style for the text. + * @return {import("./Fill.js").default} Fill style. + * @api + */ + getFill() { + return this.fill_; + } + /** + * Determine whether the text rotates with the map. + * @return {boolean|undefined} Rotate with map. + * @api + */ + getRotateWithView() { + return this.rotateWithView_; + } + /** + * Get the text rotation. + * @return {number|undefined} Rotation. + * @api + */ + getRotation() { + return this.rotation_; + } + /** + * Get the text scale. + * @return {number|import("../size.js").Size|undefined} Scale. + * @api + */ + getScale() { + return this.scale_; + } + /** + * Get the symbolizer scale array. + * @return {import("../size.js").Size} Scale array. + */ + getScaleArray() { + return this.scaleArray_; + } + /** + * Get the stroke style for the text. + * @return {import("./Stroke.js").default} Stroke style. + * @api + */ + getStroke() { + return this.stroke_; + } + /** + * Get the text to be rendered. + * @return {string|Array|undefined} Text. + * @api + */ + getText() { + return this.text_; + } + /** + * Get the text alignment. + * @return {CanvasTextAlign|undefined} Text align. + * @api + */ + getTextAlign() { + return this.textAlign_; + } + /** + * Get the justification. + * @return {TextJustify|undefined} Justification. + * @api + */ + getJustify() { + return this.justify_; + } + /** + * Get the text baseline. + * @return {CanvasTextBaseline|undefined} Text baseline. + * @api + */ + getTextBaseline() { + return this.textBaseline_; + } + /** + * Get the background fill style for the text. + * @return {import("./Fill.js").default} Fill style. + * @api + */ + getBackgroundFill() { + return this.backgroundFill_; + } + /** + * Get the background stroke style for the text. + * @return {import("./Stroke.js").default} Stroke style. + * @api + */ + getBackgroundStroke() { + return this.backgroundStroke_; + } + /** + * Get the padding for the text. + * @return {Array|null} Padding. + * @api + */ + getPadding() { + return this.padding_; + } + /** + * Set the `overflow` property. + * + * @param {boolean} overflow Let text overflow the path that it follows. + * @api + */ + setOverflow(overflow) { + this.overflow_ = overflow; + } + /** + * Set the font. + * + * @param {string|undefined} font Font. + * @api + */ + setFont(font) { + this.font_ = font; + } + /** + * Set the maximum angle between adjacent characters. + * + * @param {number} maxAngle Angle in radians. + * @api + */ + setMaxAngle(maxAngle) { + this.maxAngle_ = maxAngle; + } + /** + * Set the x offset. + * + * @param {number} offsetX Horizontal text offset. + * @api + */ + setOffsetX(offsetX) { + this.offsetX_ = offsetX; + } + /** + * Set the y offset. + * + * @param {number} offsetY Vertical text offset. + * @api + */ + setOffsetY(offsetY) { + this.offsetY_ = offsetY; + } + /** + * Set the text placement. + * + * @param {TextPlacement} placement Placement. + * @api + */ + setPlacement(placement) { + this.placement_ = placement; + } + /** + * Set the repeat interval of the text. + * @param {number|undefined} [repeat] Repeat interval in pixels. + * @api + */ + setRepeat(repeat) { + this.repeat_ = repeat; + } + /** + * Set whether to rotate the text with the view. + * + * @param {boolean} rotateWithView Rotate with map. + * @api + */ + setRotateWithView(rotateWithView) { + this.rotateWithView_ = rotateWithView; + } + /** + * Set the fill. + * + * @param {import("./Fill.js").default} fill Fill style. + * @api + */ + setFill(fill) { + this.fill_ = fill; + } + /** + * Set the rotation. + * + * @param {number|undefined} rotation Rotation. + * @api + */ + setRotation(rotation) { + this.rotation_ = rotation; + } + /** + * Set the scale. + * + * @param {number|import("../size.js").Size|undefined} scale Scale. + * @api + */ + setScale(scale2) { + this.scale_ = scale2; + this.scaleArray_ = toSize(scale2 !== void 0 ? scale2 : 1); + } + /** + * Set the stroke. + * + * @param {import("./Stroke.js").default} stroke Stroke style. + * @api + */ + setStroke(stroke) { + this.stroke_ = stroke; + } + /** + * Set the text. + * + * @param {string|Array|undefined} text Text. + * @api + */ + setText(text) { + this.text_ = text; + } + /** + * Set the text alignment. + * + * @param {CanvasTextAlign|undefined} textAlign Text align. + * @api + */ + setTextAlign(textAlign) { + this.textAlign_ = textAlign; + } + /** + * Set the justification. + * + * @param {TextJustify|undefined} justify Justification. + * @api + */ + setJustify(justify) { + this.justify_ = justify; + } + /** + * Set the text baseline. + * + * @param {CanvasTextBaseline|undefined} textBaseline Text baseline. + * @api + */ + setTextBaseline(textBaseline) { + this.textBaseline_ = textBaseline; + } + /** + * Set the background fill. + * + * @param {import("./Fill.js").default} fill Fill style. + * @api + */ + setBackgroundFill(fill) { + this.backgroundFill_ = fill; + } + /** + * Set the background stroke. + * + * @param {import("./Stroke.js").default} stroke Stroke style. + * @api + */ + setBackgroundStroke(stroke) { + this.backgroundStroke_ = stroke; + } + /** + * Set the padding (`[top, right, bottom, left]`). + * + * @param {Array|null} padding Padding. + * @api + */ + setPadding(padding) { + this.padding_ = padding; + } +} +const OlText = Text; +function listenImage(image, loadHandler, errorHandler) { + const img = ( + /** @type {HTMLImageElement} */ + image + ); + let listening = true; + let decoding = false; + let loaded = false; + const listenerKeys = [ + listenOnce(img, EventType.LOAD, function() { + loaded = true; + if (!decoding) { + loadHandler(); + } + }) + ]; + if (img.src && IMAGE_DECODE) { + decoding = true; + img.decode().then(function() { + if (listening) { + loadHandler(); + } + }).catch(function(error) { + if (listening) { + if (loaded) { + loadHandler(); + } else { + errorHandler(); + } + } + }); + } else { + listenerKeys.push(listenOnce(img, EventType.ERROR, errorHandler)); + } + return function unlisten() { + listening = false; + listenerKeys.forEach(unlistenByKey); + }; +} +function load(image, src) { + return new Promise((resolve, reject) => { + function handleLoad() { + unlisten(); + resolve(image); + } + function handleError() { + unlisten(); + reject(new Error("Image load error")); + } + function unlisten() { + image.removeEventListener("load", handleLoad); + image.removeEventListener("error", handleError); + } + image.addEventListener("load", handleLoad); + image.addEventListener("error", handleError); + if (src) { + image.src = src; + } + }); +} +function decodeFallback(image, src) { + if (src) { + image.src = src; + } + return IMAGE_DECODE ? new Promise( + (resolve, reject) => image.decode().then(() => resolve(image), reject) + ) : load(image); +} +let taintedTestContext = null; +class IconImage extends EventTarget { + /** + * @param {HTMLImageElement|HTMLCanvasElement|ImageBitmap} image Image. + * @param {string|undefined} src Src. + * @param {?string} crossOrigin Cross origin. + * @param {import("../ImageState.js").default} imageState Image state. + * @param {import("../color.js").Color} color Color. + */ + constructor(image, src, crossOrigin, imageState, color) { + super(); + this.hitDetectionImage_ = null; + this.image_ = image; + this.crossOrigin_ = crossOrigin; + this.canvas_ = {}; + this.color_ = color; + this.imageState_ = imageState === void 0 ? ImageState.IDLE : imageState; + this.size_ = image && image.width && image.height ? [image.width, image.height] : null; + this.src_ = src; + this.tainted_; + } + /** + * @private + */ + initializeImage_() { + this.image_ = new Image(); + if (this.crossOrigin_ !== null) { + this.image_.crossOrigin = this.crossOrigin_; + } + } + /** + * @private + * @return {boolean} The image canvas is tainted. + */ + isTainted_() { + if (this.tainted_ === void 0 && this.imageState_ === ImageState.LOADED) { + if (!taintedTestContext) { + taintedTestContext = createCanvasContext2D(1, 1, void 0, { + willReadFrequently: true + }); + } + taintedTestContext.drawImage(this.image_, 0, 0); + try { + taintedTestContext.getImageData(0, 0, 1, 1); + this.tainted_ = false; + } catch (e) { + taintedTestContext = null; + this.tainted_ = true; + } + } + return this.tainted_ === true; + } + /** + * @private + */ + dispatchChangeEvent_() { + this.dispatchEvent(EventType.CHANGE); + } + /** + * @private + */ + handleImageError_() { + this.imageState_ = ImageState.ERROR; + this.dispatchChangeEvent_(); + } + /** + * @private + */ + handleImageLoad_() { + this.imageState_ = ImageState.LOADED; + this.size_ = [this.image_.width, this.image_.height]; + this.dispatchChangeEvent_(); + } + /** + * @param {number} pixelRatio Pixel ratio. + * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image or Canvas element or image bitmap. + */ + getImage(pixelRatio) { + if (!this.image_) { + this.initializeImage_(); + } + this.replaceColor_(pixelRatio); + return this.canvas_[pixelRatio] ? this.canvas_[pixelRatio] : this.image_; + } + /** + * @param {number} pixelRatio Pixel ratio. + * @return {number} Image or Canvas element. + */ + getPixelRatio(pixelRatio) { + this.replaceColor_(pixelRatio); + return this.canvas_[pixelRatio] ? pixelRatio : 1; + } + /** + * @return {import("../ImageState.js").default} Image state. + */ + getImageState() { + return this.imageState_; + } + /** + * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image element. + */ + getHitDetectionImage() { + if (!this.image_) { + this.initializeImage_(); + } + if (!this.hitDetectionImage_) { + if (this.isTainted_()) { + const width = this.size_[0]; + const height = this.size_[1]; + const context = createCanvasContext2D(width, height); + context.fillRect(0, 0, width, height); + this.hitDetectionImage_ = context.canvas; + } else { + this.hitDetectionImage_ = this.image_; + } + } + return this.hitDetectionImage_; + } + /** + * Get the size of the icon (in pixels). + * @return {import("../size.js").Size} Image size. + */ + getSize() { + return this.size_; + } + /** + * @return {string|undefined} Image src. + */ + getSrc() { + return this.src_; + } + /** + * Load not yet loaded URI. + */ + load() { + if (this.imageState_ !== ImageState.IDLE) { + return; + } + if (!this.image_) { + this.initializeImage_(); + } + this.imageState_ = ImageState.LOADING; + try { + if (this.src_ !== void 0) { + this.image_.src = this.src_; + } + } catch (e) { + this.handleImageError_(); + } + if (this.image_ instanceof HTMLImageElement) { + decodeFallback(this.image_, this.src_).then((image) => { + this.image_ = image; + this.handleImageLoad_(); + }).catch(this.handleImageError_.bind(this)); + } + } + /** + * @param {number} pixelRatio Pixel ratio. + * @private + */ + replaceColor_(pixelRatio) { + if (!this.color_ || this.canvas_[pixelRatio] || this.imageState_ !== ImageState.LOADED) { + return; + } + const image = this.image_; + const canvas = document.createElement("canvas"); + canvas.width = Math.ceil(image.width * pixelRatio); + canvas.height = Math.ceil(image.height * pixelRatio); + const ctx = canvas.getContext("2d"); + ctx.scale(pixelRatio, pixelRatio); + ctx.drawImage(image, 0, 0); + ctx.globalCompositeOperation = "multiply"; + ctx.fillStyle = asString(this.color_); + ctx.fillRect(0, 0, canvas.width / pixelRatio, canvas.height / pixelRatio); + ctx.globalCompositeOperation = "destination-in"; + ctx.drawImage(image, 0, 0); + this.canvas_[pixelRatio] = canvas; + } +} +function get(image, cacheKey, crossOrigin, imageState, color) { + let iconImage = cacheKey === void 0 ? void 0 : shared.get(cacheKey, crossOrigin, color); + if (!iconImage) { + iconImage = new IconImage( + image, + image instanceof HTMLImageElement ? image.src || void 0 : cacheKey, + crossOrigin, + imageState, + color + ); + shared.set(cacheKey, crossOrigin, color, iconImage); + } + return iconImage; +} +function calculateScale(width, height, wantedWidth, wantedHeight) { + if (wantedWidth !== void 0 && wantedHeight !== void 0) { + return [wantedWidth / width, wantedHeight / height]; + } + if (wantedWidth !== void 0) { + return wantedWidth / width; + } + if (wantedHeight !== void 0) { + return wantedHeight / height; + } + return 1; +} +class Icon extends ImageStyle$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options || {}; + const opacity = options.opacity !== void 0 ? options.opacity : 1; + const rotation = options.rotation !== void 0 ? options.rotation : 0; + const scale2 = options.scale !== void 0 ? options.scale : 1; + const rotateWithView = options.rotateWithView !== void 0 ? options.rotateWithView : false; + super({ + opacity, + rotation, + scale: scale2, + displacement: options.displacement !== void 0 ? options.displacement : [0, 0], + rotateWithView, + declutterMode: options.declutterMode + }); + this.anchor_ = options.anchor !== void 0 ? options.anchor : [0.5, 0.5]; + this.normalizedAnchor_ = null; + this.anchorOrigin_ = options.anchorOrigin !== void 0 ? options.anchorOrigin : "top-left"; + this.anchorXUnits_ = options.anchorXUnits !== void 0 ? options.anchorXUnits : "fraction"; + this.anchorYUnits_ = options.anchorYUnits !== void 0 ? options.anchorYUnits : "fraction"; + this.crossOrigin_ = options.crossOrigin !== void 0 ? options.crossOrigin : null; + const image = options.img !== void 0 ? options.img : null; + let cacheKey = options.src; + assert( + !(cacheKey !== void 0 && image), + "`image` and `src` cannot be provided at the same time" + ); + if ((cacheKey === void 0 || cacheKey.length === 0) && image) { + cacheKey = /** @type {HTMLImageElement} */ + image.src || getUid(image); + } + assert( + cacheKey !== void 0 && cacheKey.length > 0, + "A defined and non-empty `src` or `image` must be provided" + ); + assert( + !((options.width !== void 0 || options.height !== void 0) && options.scale !== void 0), + "`width` or `height` cannot be provided together with `scale`" + ); + let imageState; + if (options.src !== void 0) { + imageState = ImageState.IDLE; + } else if (image !== void 0) { + if (image instanceof HTMLImageElement) { + if (image.complete) { + imageState = image.src ? ImageState.LOADED : ImageState.IDLE; + } else { + imageState = ImageState.LOADING; + } + } else { + imageState = ImageState.LOADED; + } + } + this.color_ = options.color !== void 0 ? asArray(options.color) : null; + this.iconImage_ = get( + image, + /** @type {string} */ + cacheKey, + this.crossOrigin_, + imageState, + this.color_ + ); + this.offset_ = options.offset !== void 0 ? options.offset : [0, 0]; + this.offsetOrigin_ = options.offsetOrigin !== void 0 ? options.offsetOrigin : "top-left"; + this.origin_ = null; + this.size_ = options.size !== void 0 ? options.size : null; + if (options.width !== void 0 || options.height !== void 0) { + let width, height; + if (options.size) { + [width, height] = options.size; + } else { + const image2 = this.getImage(1); + if (image2.width && image2.height) { + width = image2.width; + height = image2.height; + } else if (image2 instanceof HTMLImageElement) { + this.initialOptions_ = options; + const onload = () => { + this.unlistenImageChange(onload); + if (!this.initialOptions_) { + return; + } + const imageSize = this.iconImage_.getSize(); + this.setScale( + calculateScale( + imageSize[0], + imageSize[1], + options.width, + options.height + ) + ); + }; + this.listenImageChange(onload); + return; + } + } + if (width !== void 0) { + this.setScale( + calculateScale(width, height, options.width, options.height) + ); + } + } + } + /** + * Clones the style. The underlying Image/HTMLCanvasElement is not cloned. + * @return {Icon} The cloned style. + * @api + */ + clone() { + let scale2, width, height; + if (this.initialOptions_) { + width = this.initialOptions_.width; + height = this.initialOptions_.height; + } else { + scale2 = this.getScale(); + scale2 = Array.isArray(scale2) ? scale2.slice() : scale2; + } + return new Icon({ + anchor: this.anchor_.slice(), + anchorOrigin: this.anchorOrigin_, + anchorXUnits: this.anchorXUnits_, + anchorYUnits: this.anchorYUnits_, + color: this.color_ && this.color_.slice ? this.color_.slice() : this.color_ || void 0, + crossOrigin: this.crossOrigin_, + offset: this.offset_.slice(), + offsetOrigin: this.offsetOrigin_, + opacity: this.getOpacity(), + rotateWithView: this.getRotateWithView(), + rotation: this.getRotation(), + scale: scale2, + width, + height, + size: this.size_ !== null ? this.size_.slice() : void 0, + src: this.getSrc(), + displacement: this.getDisplacement().slice(), + declutterMode: this.getDeclutterMode() + }); + } + /** + * Get the anchor point in pixels. The anchor determines the center point for the + * symbolizer. + * @return {Array} Anchor. + * @api + */ + getAnchor() { + let anchor = this.normalizedAnchor_; + if (!anchor) { + anchor = this.anchor_; + const size = this.getSize(); + if (this.anchorXUnits_ == "fraction" || this.anchorYUnits_ == "fraction") { + if (!size) { + return null; + } + anchor = this.anchor_.slice(); + if (this.anchorXUnits_ == "fraction") { + anchor[0] *= size[0]; + } + if (this.anchorYUnits_ == "fraction") { + anchor[1] *= size[1]; + } + } + if (this.anchorOrigin_ != "top-left") { + if (!size) { + return null; + } + if (anchor === this.anchor_) { + anchor = this.anchor_.slice(); + } + if (this.anchorOrigin_ == "top-right" || this.anchorOrigin_ == "bottom-right") { + anchor[0] = -anchor[0] + size[0]; + } + if (this.anchorOrigin_ == "bottom-left" || this.anchorOrigin_ == "bottom-right") { + anchor[1] = -anchor[1] + size[1]; + } + } + this.normalizedAnchor_ = anchor; + } + const displacement = this.getDisplacement(); + const scale2 = this.getScaleArray(); + return [ + anchor[0] - displacement[0] / scale2[0], + anchor[1] + displacement[1] / scale2[1] + ]; + } + /** + * Set the anchor point. The anchor determines the center point for the + * symbolizer. + * + * @param {Array} anchor Anchor. + * @api + */ + setAnchor(anchor) { + this.anchor_ = anchor; + this.normalizedAnchor_ = null; + } + /** + * Get the icon color. + * @return {import("../color.js").Color} Color. + * @api + */ + getColor() { + return this.color_; + } + /** + * Get the image icon. + * @param {number} pixelRatio Pixel ratio. + * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image or Canvas element. If the Icon + * style was configured with `src` or with a not let loaded `img`, an `ImageBitmap` will be returned. + * @api + */ + getImage(pixelRatio) { + return this.iconImage_.getImage(pixelRatio); + } + /** + * Get the pixel ratio. + * @param {number} pixelRatio Pixel ratio. + * @return {number} The pixel ratio of the image. + * @api + */ + getPixelRatio(pixelRatio) { + return this.iconImage_.getPixelRatio(pixelRatio); + } + /** + * @return {import("../size.js").Size} Image size. + */ + getImageSize() { + return this.iconImage_.getSize(); + } + /** + * @return {import("../ImageState.js").default} Image state. + */ + getImageState() { + return this.iconImage_.getImageState(); + } + /** + * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image element. + */ + getHitDetectionImage() { + return this.iconImage_.getHitDetectionImage(); + } + /** + * Get the origin of the symbolizer. + * @return {Array} Origin. + * @api + */ + getOrigin() { + if (this.origin_) { + return this.origin_; + } + let offset = this.offset_; + if (this.offsetOrigin_ != "top-left") { + const size = this.getSize(); + const iconImageSize = this.iconImage_.getSize(); + if (!size || !iconImageSize) { + return null; + } + offset = offset.slice(); + if (this.offsetOrigin_ == "top-right" || this.offsetOrigin_ == "bottom-right") { + offset[0] = iconImageSize[0] - size[0] - offset[0]; + } + if (this.offsetOrigin_ == "bottom-left" || this.offsetOrigin_ == "bottom-right") { + offset[1] = iconImageSize[1] - size[1] - offset[1]; + } + } + this.origin_ = offset; + return this.origin_; + } + /** + * Get the image URL. + * @return {string|undefined} Image src. + * @api + */ + getSrc() { + return this.iconImage_.getSrc(); + } + /** + * Get the size of the icon (in pixels). + * @return {import("../size.js").Size} Image size. + * @api + */ + getSize() { + return !this.size_ ? this.iconImage_.getSize() : this.size_; + } + /** + * Get the width of the icon (in pixels). Will return undefined when the icon image is not yet loaded. + * @return {number} Icon width (in pixels). + * @api + */ + getWidth() { + const scale2 = this.getScaleArray(); + if (this.size_) { + return this.size_[0] * scale2[0]; + } + if (this.iconImage_.getImageState() == ImageState.LOADED) { + return this.iconImage_.getSize()[0] * scale2[0]; + } + return void 0; + } + /** + * Get the height of the icon (in pixels). Will return undefined when the icon image is not yet loaded. + * @return {number} Icon height (in pixels). + * @api + */ + getHeight() { + const scale2 = this.getScaleArray(); + if (this.size_) { + return this.size_[1] * scale2[1]; + } + if (this.iconImage_.getImageState() == ImageState.LOADED) { + return this.iconImage_.getSize()[1] * scale2[1]; + } + return void 0; + } + /** + * Set the scale. + * + * @param {number|import("../size.js").Size} scale Scale. + * @api + */ + setScale(scale2) { + delete this.initialOptions_; + super.setScale(scale2); + } + /** + * @param {function(import("../events/Event.js").default): void} listener Listener function. + */ + listenImageChange(listener) { + this.iconImage_.addEventListener(EventType.CHANGE, listener); + } + /** + * Load not yet loaded URI. + * When rendering a feature with an icon style, the vector renderer will + * automatically call this method. However, you might want to call this + * method yourself for preloading or other purposes. + * @api + */ + load() { + this.iconImage_.load(); + } + /** + * @param {function(import("../events/Event.js").default): void} listener Listener function. + */ + unlistenImageChange(listener) { + this.iconImage_.removeEventListener(EventType.CHANGE, listener); + } +} +const OlIcon = Icon; +class Feature extends BaseObject$1 { + /** + * @param {Geometry|ObjectWithGeometry} [geometryOrProperties] + * You may pass a Geometry object directly, or an object literal containing + * properties. If you pass an object literal, you may include a Geometry + * associated with a `geometry` key. + */ + constructor(geometryOrProperties) { + super(); + this.on; + this.once; + this.un; + this.id_ = void 0; + this.geometryName_ = "geometry"; + this.style_ = null; + this.styleFunction_ = void 0; + this.geometryChangeKey_ = null; + this.addChangeListener(this.geometryName_, this.handleGeometryChanged_); + if (geometryOrProperties) { + if (typeof /** @type {?} */ + geometryOrProperties.getSimplifiedGeometry === "function") { + const geometry = ( + /** @type {Geometry} */ + geometryOrProperties + ); + this.setGeometry(geometry); + } else { + const properties = geometryOrProperties; + this.setProperties(properties); + } + } + } + /** + * Clone this feature. If the original feature has a geometry it + * is also cloned. The feature id is not set in the clone. + * @return {Feature} The clone. + * @api + */ + clone() { + const clone2 = ( + /** @type {Feature} */ + new Feature(this.hasProperties() ? this.getProperties() : null) + ); + clone2.setGeometryName(this.getGeometryName()); + const geometry = this.getGeometry(); + if (geometry) { + clone2.setGeometry( + /** @type {Geometry} */ + geometry.clone() + ); + } + const style = this.getStyle(); + if (style) { + clone2.setStyle(style); + } + return clone2; + } + /** + * Get the feature's default geometry. A feature may have any number of named + * geometries. The "default" geometry (the one that is rendered by default) is + * set when calling {@link module:ol/Feature~Feature#setGeometry}. + * @return {Geometry|undefined} The default geometry for the feature. + * @api + * @observable + */ + getGeometry() { + return ( + /** @type {Geometry|undefined} */ + this.get(this.geometryName_) + ); + } + /** + * Get the feature identifier. This is a stable identifier for the feature and + * is either set when reading data from a remote source or set explicitly by + * calling {@link module:ol/Feature~Feature#setId}. + * @return {number|string|undefined} Id. + * @api + */ + getId() { + return this.id_; + } + /** + * Get the name of the feature's default geometry. By default, the default + * geometry is named `geometry`. + * @return {string} Get the property name associated with the default geometry + * for this feature. + * @api + */ + getGeometryName() { + return this.geometryName_; + } + /** + * Get the feature's style. Will return what was provided to the + * {@link module:ol/Feature~Feature#setStyle} method. + * @return {import("./style/Style.js").StyleLike|undefined} The feature style. + * @api + */ + getStyle() { + return this.style_; + } + /** + * Get the feature's style function. + * @return {import("./style/Style.js").StyleFunction|undefined} Return a function + * representing the current style of this feature. + * @api + */ + getStyleFunction() { + return this.styleFunction_; + } + /** + * @private + */ + handleGeometryChange_() { + this.changed(); + } + /** + * @private + */ + handleGeometryChanged_() { + if (this.geometryChangeKey_) { + unlistenByKey(this.geometryChangeKey_); + this.geometryChangeKey_ = null; + } + const geometry = this.getGeometry(); + if (geometry) { + this.geometryChangeKey_ = listen( + geometry, + EventType.CHANGE, + this.handleGeometryChange_, + this + ); + } + this.changed(); + } + /** + * Set the default geometry for the feature. This will update the property + * with the name returned by {@link module:ol/Feature~Feature#getGeometryName}. + * @param {Geometry|undefined} geometry The new geometry. + * @api + * @observable + */ + setGeometry(geometry) { + this.set(this.geometryName_, geometry); + } + /** + * Set the style for the feature to override the layer style. This can be a + * single style object, an array of styles, or a function that takes a + * resolution and returns an array of styles. To unset the feature style, call + * `setStyle()` without arguments or a falsey value. + * @param {import("./style/Style.js").StyleLike} [style] Style for this feature. + * @api + * @fires module:ol/events/Event~BaseEvent#event:change + */ + setStyle(style) { + this.style_ = style; + this.styleFunction_ = !style ? void 0 : createStyleFunction(style); + this.changed(); + } + /** + * Set the feature id. The feature id is considered stable and may be used when + * requesting features or comparing identifiers returned from a remote source. + * The feature id can be used with the + * {@link module:ol/source/Vector~VectorSource#getFeatureById} method. + * @param {number|string|undefined} id The feature id. + * @api + * @fires module:ol/events/Event~BaseEvent#event:change + */ + setId(id) { + this.id_ = id; + this.changed(); + } + /** + * Set the property name to be used when getting the feature's default geometry. + * When calling {@link module:ol/Feature~Feature#getGeometry}, the value of the property with + * this name will be returned. + * @param {string} name The property name of the default geometry. + * @api + */ + setGeometryName(name) { + this.removeChangeListener(this.geometryName_, this.handleGeometryChanged_); + this.geometryName_ = name; + this.addChangeListener(this.geometryName_, this.handleGeometryChanged_); + this.handleGeometryChanged_(); + } +} +function createStyleFunction(obj) { + if (typeof obj === "function") { + return obj; + } + let styles; + if (Array.isArray(obj)) { + styles = obj; + } else { + assert( + typeof /** @type {?} */ + obj.getZIndex === "function", + "Expected an `ol/style/Style` or an array of `ol/style/Style.js`" + ); + const style = ( + /** @type {import("./style/Style.js").default} */ + obj + ); + styles = [style]; + } + return function() { + return styles; + }; +} +const Feature$1 = Feature; +class GeometryCollection extends Geometry$1 { + /** + * @param {Array} [geometries] Geometries. + */ + constructor(geometries) { + super(); + this.geometries_ = geometries ? geometries : null; + this.changeEventsKeys_ = []; + this.listenGeometriesChange_(); + } + /** + * @private + */ + unlistenGeometriesChange_() { + this.changeEventsKeys_.forEach(unlistenByKey); + this.changeEventsKeys_.length = 0; + } + /** + * @private + */ + listenGeometriesChange_() { + if (!this.geometries_) { + return; + } + for (let i = 0, ii = this.geometries_.length; i < ii; ++i) { + this.changeEventsKeys_.push( + listen(this.geometries_[i], EventType.CHANGE, this.changed, this) + ); + } + } + /** + * Make a complete copy of the geometry. + * @return {!GeometryCollection} Clone. + * @api + */ + clone() { + const geometryCollection = new GeometryCollection(null); + geometryCollection.setGeometries(this.geometries_); + geometryCollection.applyProperties(this); + return geometryCollection; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { + return minSquaredDistance; + } + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + minSquaredDistance = geometries[i].closestPointXY( + x, + y, + closestPoint, + minSquaredDistance + ); + } + return minSquaredDistance; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ + containsXY(x, y) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + if (geometries[i].containsXY(x, y)) { + return true; + } + } + return false; + } + /** + * @param {import("../extent.js").Extent} extent Extent. + * @protected + * @return {import("../extent.js").Extent} extent Extent. + */ + computeExtent(extent) { + createOrUpdateEmpty(extent); + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + extend$1(extent, geometries[i].getExtent()); + } + return extent; + } + /** + * Return the geometries that make up this geometry collection. + * @return {Array} Geometries. + * @api + */ + getGeometries() { + return cloneGeometries(this.geometries_); + } + /** + * @return {Array} Geometries. + */ + getGeometriesArray() { + return this.geometries_; + } + /** + * @return {Array} Geometries. + */ + getGeometriesArrayRecursive() { + let geometriesArray = []; + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + if (geometries[i].getType() === this.getType()) { + geometriesArray = geometriesArray.concat( + /** @type {GeometryCollection} */ + geometries[i].getGeometriesArrayRecursive() + ); + } else { + geometriesArray.push(geometries[i]); + } + } + return geometriesArray; + } + /** + * Create a simplified version of this geometry using the Douglas Peucker algorithm. + * @param {number} squaredTolerance Squared tolerance. + * @return {GeometryCollection} Simplified GeometryCollection. + */ + getSimplifiedGeometry(squaredTolerance) { + if (this.simplifiedGeometryRevision !== this.getRevision()) { + this.simplifiedGeometryMaxMinSquaredTolerance = 0; + this.simplifiedGeometryRevision = this.getRevision(); + } + if (squaredTolerance < 0 || this.simplifiedGeometryMaxMinSquaredTolerance !== 0 && squaredTolerance < this.simplifiedGeometryMaxMinSquaredTolerance) { + return this; + } + const simplifiedGeometries = []; + const geometries = this.geometries_; + let simplified = false; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + const geometry = geometries[i]; + const simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance); + simplifiedGeometries.push(simplifiedGeometry); + if (simplifiedGeometry !== geometry) { + simplified = true; + } + } + if (simplified) { + const simplifiedGeometryCollection = new GeometryCollection(null); + simplifiedGeometryCollection.setGeometriesArray(simplifiedGeometries); + return simplifiedGeometryCollection; + } + this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance; + return this; + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "GeometryCollection"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + if (geometries[i].intersectsExtent(extent)) { + return true; + } + } + return false; + } + /** + * @return {boolean} Is empty. + */ + isEmpty() { + return this.geometries_.length === 0; + } + /** + * Rotate the geometry around a given coordinate. This modifies the geometry + * coordinates in place. + * @param {number} angle Rotation angle in radians. + * @param {import("../coordinate.js").Coordinate} anchor The rotation center. + * @api + */ + rotate(angle, anchor) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + geometries[i].rotate(angle, anchor); + } + this.changed(); + } + /** + * Scale the geometry (with an optional origin). This modifies the geometry + * coordinates in place. + * @abstract + * @param {number} sx The scaling factor in the x-direction. + * @param {number} [sy] The scaling factor in the y-direction (defaults to sx). + * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center + * of the geometry extent). + * @api + */ + scale(sx, sy, anchor) { + if (!anchor) { + anchor = getCenter(this.getExtent()); + } + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + geometries[i].scale(sx, sy, anchor); + } + this.changed(); + } + /** + * Set the geometries that make up this geometry collection. + * @param {Array} geometries Geometries. + * @api + */ + setGeometries(geometries) { + this.setGeometriesArray(cloneGeometries(geometries)); + } + /** + * @param {Array} geometries Geometries. + */ + setGeometriesArray(geometries) { + this.unlistenGeometriesChange_(); + this.geometries_ = geometries; + this.listenGeometriesChange_(); + this.changed(); + } + /** + * Apply a transform function to the coordinates of the geometry. + * The geometry is modified in place. + * If you do not want the geometry modified in place, first `clone()` it and + * then use this function on the clone. + * @param {import("../proj.js").TransformFunction} transformFn Transform function. + * Called with a flat array of geometry coordinates. + * @api + */ + applyTransform(transformFn) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + geometries[i].applyTransform(transformFn); + } + this.changed(); + } + /** + * Translate the geometry. This modifies the geometry coordinates in place. If + * instead you want a new geometry, first `clone()` this geometry. + * @param {number} deltaX Delta X. + * @param {number} deltaY Delta Y. + * @api + */ + translate(deltaX, deltaY) { + const geometries = this.geometries_; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + geometries[i].translate(deltaX, deltaY); + } + this.changed(); + } + /** + * Clean up. + */ + disposeInternal() { + this.unlistenGeometriesChange_(); + super.disposeInternal(); + } +} +function cloneGeometries(geometries) { + const clonedGeometries = []; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + clonedGeometries.push(geometries[i].clone()); + } + return clonedGeometries; +} +const GeometryCollection$1 = GeometryCollection; +class FeatureFormat { + constructor() { + this.dataProjection = void 0; + this.defaultFeatureProjection = void 0; + this.supportedMediaTypes = null; + } + /** + * Adds the data projection to the read options. + * @param {Document|Element|Object|string} source Source. + * @param {ReadOptions} [options] Options. + * @return {ReadOptions|undefined} Options. + * @protected + */ + getReadOptions(source, options) { + if (options) { + let dataProjection = options.dataProjection ? get$1(options.dataProjection) : this.readProjection(source); + if (options.extent && dataProjection && dataProjection.getUnits() === "tile-pixels") { + dataProjection = get$1(dataProjection); + dataProjection.setWorldExtent(options.extent); + } + options = { + dataProjection, + featureProjection: options.featureProjection + }; + } + return this.adaptOptions(options); + } + /** + * Sets the `dataProjection` on the options, if no `dataProjection` + * is set. + * @param {WriteOptions|ReadOptions|undefined} options + * Options. + * @protected + * @return {WriteOptions|ReadOptions|undefined} + * Updated options. + */ + adaptOptions(options) { + return Object.assign( + { + dataProjection: this.dataProjection, + featureProjection: this.defaultFeatureProjection + }, + options + ); + } + /** + * @abstract + * @return {Type} The format type. + */ + getType() { + return abstract(); + } + /** + * Read a single feature from a source. + * + * @abstract + * @param {Document|Element|Object|string} source Source. + * @param {ReadOptions} [options] Read options. + * @return {import("../Feature.js").FeatureLike} Feature. + */ + readFeature(source, options) { + return abstract(); + } + /** + * Read all features from a source. + * + * @abstract + * @param {Document|Element|ArrayBuffer|Object|string} source Source. + * @param {ReadOptions} [options] Read options. + * @return {Array} Features. + */ + readFeatures(source, options) { + return abstract(); + } + /** + * Read a single geometry from a source. + * + * @abstract + * @param {Document|Element|Object|string} source Source. + * @param {ReadOptions} [options] Read options. + * @return {import("../geom/Geometry.js").default} Geometry. + */ + readGeometry(source, options) { + return abstract(); + } + /** + * Read the projection from a source. + * + * @abstract + * @param {Document|Element|Object|string} source Source. + * @return {import("../proj/Projection.js").default|undefined} Projection. + */ + readProjection(source) { + return abstract(); + } + /** + * Encode a feature in this format. + * + * @abstract + * @param {import("../Feature.js").default} feature Feature. + * @param {WriteOptions} [options] Write options. + * @return {string|ArrayBuffer} Result. + */ + writeFeature(feature, options) { + return abstract(); + } + /** + * Encode an array of features in this format. + * + * @abstract + * @param {Array} features Features. + * @param {WriteOptions} [options] Write options. + * @return {string|ArrayBuffer} Result. + */ + writeFeatures(features, options) { + return abstract(); + } + /** + * Write a single geometry in this format. + * + * @abstract + * @param {import("../geom/Geometry.js").default} geometry Geometry. + * @param {WriteOptions} [options] Write options. + * @return {string|ArrayBuffer} Result. + */ + writeGeometry(geometry, options) { + return abstract(); + } +} +function transformGeometryWithOptions(geometry, write, options) { + const featureProjection = options ? get$1(options.featureProjection) : null; + const dataProjection = options ? get$1(options.dataProjection) : null; + let transformed; + if (featureProjection && dataProjection && !equivalent(featureProjection, dataProjection)) { + transformed = (write ? geometry.clone() : geometry).transform( + write ? featureProjection : dataProjection, + write ? dataProjection : featureProjection + ); + } else { + transformed = geometry; + } + if (write && options && /** @type {WriteOptions} */ + options.decimals !== void 0) { + const power = Math.pow( + 10, + /** @type {WriteOptions} */ + options.decimals + ); + const transform2 = function(coordinates2) { + for (let i = 0, ii = coordinates2.length; i < ii; ++i) { + coordinates2[i] = Math.round(coordinates2[i] * power) / power; + } + return coordinates2; + }; + if (transformed === geometry) { + transformed = geometry.clone(); + } + transformed.applyTransform(transform2); + } + return transformed; +} +class JSONFeature extends FeatureFormat { + constructor() { + super(); + } + /** + * @return {import("./Feature.js").Type} Format. + */ + getType() { + return "json"; + } + /** + * Read a feature. Only works for a single feature. Use `readFeatures` to + * read a feature collection. + * + * @param {ArrayBuffer|Document|Element|Object|string} source Source. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @return {import("../Feature.js").default} Feature. + * @api + */ + readFeature(source, options) { + return this.readFeatureFromObject( + getObject(source), + this.getReadOptions(source, options) + ); + } + /** + * Read all features. Works with both a single feature and a feature + * collection. + * + * @param {ArrayBuffer|Document|Element|Object|string} source Source. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @return {Array} Features. + * @api + */ + readFeatures(source, options) { + return this.readFeaturesFromObject( + getObject(source), + this.getReadOptions(source, options) + ); + } + /** + * @abstract + * @param {Object} object Object. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {import("../Feature.js").default} Feature. + */ + readFeatureFromObject(object, options) { + return abstract(); + } + /** + * @abstract + * @param {Object} object Object. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {Array} Features. + */ + readFeaturesFromObject(object, options) { + return abstract(); + } + /** + * Read a geometry. + * + * @param {ArrayBuffer|Document|Element|Object|string} source Source. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @return {import("../geom/Geometry.js").default} Geometry. + * @api + */ + readGeometry(source, options) { + return this.readGeometryFromObject( + getObject(source), + this.getReadOptions(source, options) + ); + } + /** + * @abstract + * @param {Object} object Object. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {import("../geom/Geometry.js").default} Geometry. + */ + readGeometryFromObject(object, options) { + return abstract(); + } + /** + * Read the projection. + * + * @param {ArrayBuffer|Document|Element|Object|string} source Source. + * @return {import("../proj/Projection.js").default} Projection. + * @api + */ + readProjection(source) { + return this.readProjectionFromObject(getObject(source)); + } + /** + * @abstract + * @param {Object} object Object. + * @protected + * @return {import("../proj/Projection.js").default} Projection. + */ + readProjectionFromObject(object) { + return abstract(); + } + /** + * Encode a feature as string. + * + * @param {import("../Feature.js").default} feature Feature. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {string} Encoded feature. + * @api + */ + writeFeature(feature, options) { + return JSON.stringify(this.writeFeatureObject(feature, options)); + } + /** + * @abstract + * @param {import("../Feature.js").default} feature Feature. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {Object} Object. + */ + writeFeatureObject(feature, options) { + return abstract(); + } + /** + * Encode an array of features as string. + * + * @param {Array} features Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {string} Encoded features. + * @api + */ + writeFeatures(features, options) { + return JSON.stringify(this.writeFeaturesObject(features, options)); + } + /** + * @abstract + * @param {Array} features Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {Object} Object. + */ + writeFeaturesObject(features, options) { + return abstract(); + } + /** + * Encode a geometry as string. + * + * @param {import("../geom/Geometry.js").default} geometry Geometry. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {string} Encoded geometry. + * @api + */ + writeGeometry(geometry, options) { + return JSON.stringify(this.writeGeometryObject(geometry, options)); + } + /** + * @abstract + * @param {import("../geom/Geometry.js").default} geometry Geometry. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {Object} Object. + */ + writeGeometryObject(geometry, options) { + return abstract(); + } +} +function getObject(source) { + if (typeof source === "string") { + const object = JSON.parse(source); + return object ? ( + /** @type {Object} */ + object + ) : null; + } + if (source !== null) { + return source; + } + return null; +} +const JSONFeature$1 = JSONFeature; +function interpolatePoint(flatCoordinates, offset, end, stride, fraction, dest, dimension) { + let o, t; + const n = (end - offset) / stride; + if (n === 1) { + o = offset; + } else if (n === 2) { + o = offset; + t = fraction; + } else if (n !== 0) { + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + let length = 0; + const cumulativeLengths = [0]; + for (let i = offset + stride; i < end; i += stride) { + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; + length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + cumulativeLengths.push(length); + x1 = x2; + y1 = y2; + } + const target = fraction * length; + const index = binarySearch(cumulativeLengths, target); + if (index < 0) { + t = (target - cumulativeLengths[-index - 2]) / (cumulativeLengths[-index - 1] - cumulativeLengths[-index - 2]); + o = offset + (-index - 2) * stride; + } else { + o = offset + index * stride; + } + } + dimension = dimension > 1 ? dimension : 2; + dest = dest ? dest : new Array(dimension); + for (let i = 0; i < dimension; ++i) { + dest[i] = o === void 0 ? NaN : t === void 0 ? flatCoordinates[o + i] : lerp(flatCoordinates[o + i], flatCoordinates[o + stride + i], t); + } + return dest; +} +function lineStringCoordinateAtM(flatCoordinates, offset, end, stride, m, extrapolate) { + if (end == offset) { + return null; + } + let coordinate; + if (m < flatCoordinates[offset + stride - 1]) { + if (extrapolate) { + coordinate = flatCoordinates.slice(offset, offset + stride); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + if (flatCoordinates[end - 1] < m) { + if (extrapolate) { + coordinate = flatCoordinates.slice(end - stride, end); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + if (m == flatCoordinates[offset + stride - 1]) { + return flatCoordinates.slice(offset, offset + stride); + } + let lo = offset / stride; + let hi = end / stride; + while (lo < hi) { + const mid = lo + hi >> 1; + if (m < flatCoordinates[(mid + 1) * stride - 1]) { + hi = mid; + } else { + lo = mid + 1; + } + } + const m0 = flatCoordinates[lo * stride - 1]; + if (m == m0) { + return flatCoordinates.slice((lo - 1) * stride, (lo - 1) * stride + stride); + } + const m1 = flatCoordinates[(lo + 1) * stride - 1]; + const t = (m - m0) / (m1 - m0); + coordinate = []; + for (let i = 0; i < stride - 1; ++i) { + coordinate.push( + lerp( + flatCoordinates[(lo - 1) * stride + i], + flatCoordinates[lo * stride + i], + t + ) + ); + } + coordinate.push(m); + return coordinate; +} +function lineStringsCoordinateAtM(flatCoordinates, offset, ends, stride, m, extrapolate, interpolate) { + if (interpolate) { + return lineStringCoordinateAtM( + flatCoordinates, + offset, + ends[ends.length - 1], + stride, + m, + extrapolate + ); + } + let coordinate; + if (m < flatCoordinates[stride - 1]) { + if (extrapolate) { + coordinate = flatCoordinates.slice(0, stride); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + if (flatCoordinates[flatCoordinates.length - 1] < m) { + if (extrapolate) { + coordinate = flatCoordinates.slice(flatCoordinates.length - stride); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + if (offset == end) { + continue; + } + if (m < flatCoordinates[offset + stride - 1]) { + return null; + } + if (m <= flatCoordinates[end - 1]) { + return lineStringCoordinateAtM( + flatCoordinates, + offset, + end, + stride, + m, + false + ); + } + offset = end; + } + return null; +} +function lineStringLength(flatCoordinates, offset, end, stride) { + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + let length = 0; + for (let i = offset + stride; i < end; i += stride) { + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; + length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + x1 = x2; + y1 = y2; + } + return length; +} +class LineString extends SimpleGeometry$1 { + /** + * @param {Array|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates2, layout) { + super(); + this.flatMidpoint_ = null; + this.flatMidpointRevision_ = -1; + this.maxDelta_ = -1; + this.maxDeltaRevision_ = -1; + if (layout !== void 0 && !Array.isArray(coordinates2[0])) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ + coordinates2 + ); + } else { + this.setCoordinates( + /** @type {Array} */ + coordinates2, + layout + ); + } + } + /** + * Append the passed coordinate to the coordinates of the linestring. + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @api + */ + appendCoordinate(coordinate) { + if (!this.flatCoordinates) { + this.flatCoordinates = coordinate.slice(); + } else { + extend$2(this.flatCoordinates, coordinate); + } + this.changed(); + } + /** + * Make a complete copy of the geometry. + * @return {!LineString} Clone. + * @api + */ + clone() { + const lineString = new LineString( + this.flatCoordinates.slice(), + this.layout + ); + lineString.applyProperties(this); + return lineString; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + maxSquaredDelta( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + 0 + ) + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return assignClosestPoint( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + this.maxDelta_, + false, + x, + y, + closestPoint, + minSquaredDistance + ); + } + /** + * Iterate over each segment, calling the provided callback. + * If the callback returns a truthy value the function returns that + * value immediately. Otherwise the function returns `false`. + * + * @param {function(this: S, import("../coordinate.js").Coordinate, import("../coordinate.js").Coordinate): T} callback Function + * called for each segment. The function will receive two arguments, the start and end coordinates of the segment. + * @return {T|boolean} Value. + * @template T,S + * @api + */ + forEachSegment(callback) { + return forEach( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + callback + ); + } + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * @param {number} m M. + * @param {boolean} [extrapolate] Extrapolate. Default is `false`. + * @return {import("../coordinate.js").Coordinate|null} Coordinate. + * @api + */ + getCoordinateAtM(m, extrapolate) { + if (this.layout != "XYM" && this.layout != "XYZM") { + return null; + } + extrapolate = extrapolate !== void 0 ? extrapolate : false; + return lineStringCoordinateAtM( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + m, + extrapolate + ); + } + /** + * Return the coordinates of the linestring. + * @return {Array} Coordinates. + * @api + */ + getCoordinates() { + return inflateCoordinates( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride + ); + } + /** + * Return the coordinate at the provided fraction along the linestring. + * The `fraction` is a number between 0 and 1, where 0 is the start of the + * linestring and 1 is the end. + * @param {number} fraction Fraction. + * @param {import("../coordinate.js").Coordinate} [dest] Optional coordinate whose values will + * be modified. If not provided, a new coordinate will be returned. + * @return {import("../coordinate.js").Coordinate} Coordinate of the interpolated point. + * @api + */ + getCoordinateAt(fraction, dest) { + return interpolatePoint( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + fraction, + dest, + this.stride + ); + } + /** + * Return the length of the linestring on projected plane. + * @return {number} Length (on projected plane). + * @api + */ + getLength() { + return lineStringLength( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride + ); + } + /** + * @return {Array} Flat midpoint. + */ + getFlatMidpoint() { + if (this.flatMidpointRevision_ != this.getRevision()) { + this.flatMidpoint_ = this.getCoordinateAt(0.5, this.flatMidpoint_); + this.flatMidpointRevision_ = this.getRevision(); + } + return this.flatMidpoint_; + } + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {LineString} Simplified LineString. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + const simplifiedFlatCoordinates = []; + simplifiedFlatCoordinates.length = douglasPeucker( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0 + ); + return new LineString(simplifiedFlatCoordinates, "XY"); + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "LineString"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return intersectsLineString( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + extent + ); + } + /** + * Set the coordinates of the linestring. + * @param {!Array} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates2, layout) { + this.setLayout(layout, coordinates2, 1); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = deflateCoordinates( + this.flatCoordinates, + 0, + coordinates2, + this.stride + ); + this.changed(); + } +} +const LineString$1 = LineString; +class MultiLineString extends SimpleGeometry$1 { + /** + * @param {Array|LineString>|Array} coordinates + * Coordinates or LineString geometries. (For internal use, flat coordinates in + * combination with `layout` and `ends` are also accepted.) + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @param {Array} [ends] Flat coordinate ends for internal use. + */ + constructor(coordinates2, layout, ends) { + super(); + this.ends_ = []; + this.maxDelta_ = -1; + this.maxDeltaRevision_ = -1; + if (Array.isArray(coordinates2[0])) { + this.setCoordinates( + /** @type {Array>} */ + coordinates2, + layout + ); + } else if (layout !== void 0 && ends) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ + coordinates2 + ); + this.ends_ = ends; + } else { + let layout2 = this.getLayout(); + const lineStrings = ( + /** @type {Array} */ + coordinates2 + ); + const flatCoordinates = []; + const ends2 = []; + for (let i = 0, ii = lineStrings.length; i < ii; ++i) { + const lineString = lineStrings[i]; + if (i === 0) { + layout2 = lineString.getLayout(); + } + extend$2(flatCoordinates, lineString.getFlatCoordinates()); + ends2.push(flatCoordinates.length); + } + this.setFlatCoordinates(layout2, flatCoordinates); + this.ends_ = ends2; + } + } + /** + * Append the passed linestring to the multilinestring. + * @param {LineString} lineString LineString. + * @api + */ + appendLineString(lineString) { + if (!this.flatCoordinates) { + this.flatCoordinates = lineString.getFlatCoordinates().slice(); + } else { + extend$2(this.flatCoordinates, lineString.getFlatCoordinates().slice()); + } + this.ends_.push(this.flatCoordinates.length); + this.changed(); + } + /** + * Make a complete copy of the geometry. + * @return {!MultiLineString} Clone. + * @api + */ + clone() { + const multiLineString = new MultiLineString( + this.flatCoordinates.slice(), + this.layout, + this.ends_.slice() + ); + multiLineString.applyProperties(this); + return multiLineString; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + arrayMaxSquaredDelta( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + 0 + ) + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return assignClosestArrayPoint( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + this.maxDelta_, + false, + x, + y, + closestPoint, + minSquaredDistance + ); + } + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * `interpolate` controls interpolation between consecutive LineStrings + * within the MultiLineString. If `interpolate` is `true` the coordinates + * will be linearly interpolated between the last coordinate of one LineString + * and the first coordinate of the next LineString. If `interpolate` is + * `false` then the function will return `null` for Ms falling between + * LineStrings. + * + * @param {number} m M. + * @param {boolean} [extrapolate] Extrapolate. Default is `false`. + * @param {boolean} [interpolate] Interpolate. Default is `false`. + * @return {import("../coordinate.js").Coordinate|null} Coordinate. + * @api + */ + getCoordinateAtM(m, extrapolate, interpolate) { + if (this.layout != "XYM" && this.layout != "XYZM" || this.flatCoordinates.length === 0) { + return null; + } + extrapolate = extrapolate !== void 0 ? extrapolate : false; + interpolate = interpolate !== void 0 ? interpolate : false; + return lineStringsCoordinateAtM( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + m, + extrapolate, + interpolate + ); + } + /** + * Return the coordinates of the multilinestring. + * @return {Array>} Coordinates. + * @api + */ + getCoordinates() { + return inflateCoordinatesArray( + this.flatCoordinates, + 0, + this.ends_, + this.stride + ); + } + /** + * @return {Array} Ends. + */ + getEnds() { + return this.ends_; + } + /** + * Return the linestring at the specified index. + * @param {number} index Index. + * @return {LineString} LineString. + * @api + */ + getLineString(index) { + if (index < 0 || this.ends_.length <= index) { + return null; + } + return new LineString$1( + this.flatCoordinates.slice( + index === 0 ? 0 : this.ends_[index - 1], + this.ends_[index] + ), + this.layout + ); + } + /** + * Return the linestrings of this multilinestring. + * @return {Array} LineStrings. + * @api + */ + getLineStrings() { + const flatCoordinates = this.flatCoordinates; + const ends = this.ends_; + const layout = this.layout; + const lineStrings = []; + let offset = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const lineString = new LineString$1( + flatCoordinates.slice(offset, end), + layout + ); + lineStrings.push(lineString); + offset = end; + } + return lineStrings; + } + /** + * @return {Array} Flat midpoints. + */ + getFlatMidpoints() { + const midpoints = []; + const flatCoordinates = this.flatCoordinates; + let offset = 0; + const ends = this.ends_; + const stride = this.stride; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const midpoint = interpolatePoint( + flatCoordinates, + offset, + end, + stride, + 0.5 + ); + extend$2(midpoints, midpoint); + offset = end; + } + return midpoints; + } + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {MultiLineString} Simplified MultiLineString. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + const simplifiedFlatCoordinates = []; + const simplifiedEnds = []; + simplifiedFlatCoordinates.length = douglasPeuckerArray( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0, + simplifiedEnds + ); + return new MultiLineString(simplifiedFlatCoordinates, "XY", simplifiedEnds); + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "MultiLineString"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return intersectsLineStringArray( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + extent + ); + } + /** + * Set the coordinates of the multilinestring. + * @param {!Array>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates2, layout) { + this.setLayout(layout, coordinates2, 2); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + const ends = deflateCoordinatesArray( + this.flatCoordinates, + 0, + coordinates2, + this.stride, + this.ends_ + ); + this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1]; + this.changed(); + } +} +const MultiLineString$1 = MultiLineString; +class MultiPoint extends SimpleGeometry$1 { + /** + * @param {Array|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates2, layout) { + super(); + if (layout && !Array.isArray(coordinates2[0])) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ + coordinates2 + ); + } else { + this.setCoordinates( + /** @type {Array} */ + coordinates2, + layout + ); + } + } + /** + * Append the passed point to this multipoint. + * @param {Point} point Point. + * @api + */ + appendPoint(point) { + if (!this.flatCoordinates) { + this.flatCoordinates = point.getFlatCoordinates().slice(); + } else { + extend$2(this.flatCoordinates, point.getFlatCoordinates()); + } + this.changed(); + } + /** + * Make a complete copy of the geometry. + * @return {!MultiPoint} Clone. + * @api + */ + clone() { + const multiPoint = new MultiPoint( + this.flatCoordinates.slice(), + this.layout + ); + multiPoint.applyProperties(this); + return multiPoint; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { + return minSquaredDistance; + } + const flatCoordinates = this.flatCoordinates; + const stride = this.stride; + for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) { + const squaredDistance$1 = squaredDistance( + x, + y, + flatCoordinates[i], + flatCoordinates[i + 1] + ); + if (squaredDistance$1 < minSquaredDistance) { + minSquaredDistance = squaredDistance$1; + for (let j = 0; j < stride; ++j) { + closestPoint[j] = flatCoordinates[i + j]; + } + closestPoint.length = stride; + } + } + return minSquaredDistance; + } + /** + * Return the coordinates of the multipoint. + * @return {Array} Coordinates. + * @api + */ + getCoordinates() { + return inflateCoordinates( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride + ); + } + /** + * Return the point at the specified index. + * @param {number} index Index. + * @return {Point} Point. + * @api + */ + getPoint(index) { + const n = !this.flatCoordinates ? 0 : this.flatCoordinates.length / this.stride; + if (index < 0 || n <= index) { + return null; + } + return new OlPoint( + this.flatCoordinates.slice( + index * this.stride, + (index + 1) * this.stride + ), + this.layout + ); + } + /** + * Return the points of this multipoint. + * @return {Array} Points. + * @api + */ + getPoints() { + const flatCoordinates = this.flatCoordinates; + const layout = this.layout; + const stride = this.stride; + const points = []; + for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) { + const point = new OlPoint(flatCoordinates.slice(i, i + stride), layout); + points.push(point); + } + return points; + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "MultiPoint"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + const flatCoordinates = this.flatCoordinates; + const stride = this.stride; + for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) { + const x = flatCoordinates[i]; + const y = flatCoordinates[i + 1]; + if (containsXY(extent, x, y)) { + return true; + } + } + return false; + } + /** + * Set the coordinates of the multipoint. + * @param {!Array} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates2, layout) { + this.setLayout(layout, coordinates2, 1); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = deflateCoordinates( + this.flatCoordinates, + 0, + coordinates2, + this.stride + ); + this.changed(); + } +} +const MultiPoint$1 = MultiPoint; +function linearRingss(flatCoordinates, offset, endss, stride) { + const flatCenters = []; + let extent = createEmpty(); + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + extent = createOrUpdateFromFlatCoordinates( + flatCoordinates, + offset, + ends[0], + stride + ); + flatCenters.push((extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2); + offset = ends[ends.length - 1]; + } + return flatCenters; +} +class MultiPolygon extends SimpleGeometry$1 { + /** + * @param {Array>|Polygon>|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` and `endss` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @param {Array>} [endss] Array of ends for internal use with flat coordinates. + */ + constructor(coordinates2, layout, endss) { + super(); + this.endss_ = []; + this.flatInteriorPointsRevision_ = -1; + this.flatInteriorPoints_ = null; + this.maxDelta_ = -1; + this.maxDeltaRevision_ = -1; + this.orientedRevision_ = -1; + this.orientedFlatCoordinates_ = null; + if (!endss && !Array.isArray(coordinates2[0])) { + let thisLayout = this.getLayout(); + const polygons = ( + /** @type {Array} */ + coordinates2 + ); + const flatCoordinates = []; + const thisEndss = []; + for (let i = 0, ii = polygons.length; i < ii; ++i) { + const polygon = polygons[i]; + if (i === 0) { + thisLayout = polygon.getLayout(); + } + const offset = flatCoordinates.length; + const ends = polygon.getEnds(); + for (let j = 0, jj = ends.length; j < jj; ++j) { + ends[j] += offset; + } + extend$2(flatCoordinates, polygon.getFlatCoordinates()); + thisEndss.push(ends); + } + layout = thisLayout; + coordinates2 = flatCoordinates; + endss = thisEndss; + } + if (layout !== void 0 && endss) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ + coordinates2 + ); + this.endss_ = endss; + } else { + this.setCoordinates( + /** @type {Array>>} */ + coordinates2, + layout + ); + } + } + /** + * Append the passed polygon to this multipolygon. + * @param {Polygon} polygon Polygon. + * @api + */ + appendPolygon(polygon) { + let ends; + if (!this.flatCoordinates) { + this.flatCoordinates = polygon.getFlatCoordinates().slice(); + ends = polygon.getEnds().slice(); + this.endss_.push(); + } else { + const offset = this.flatCoordinates.length; + extend$2(this.flatCoordinates, polygon.getFlatCoordinates()); + ends = polygon.getEnds().slice(); + for (let i = 0, ii = ends.length; i < ii; ++i) { + ends[i] += offset; + } + } + this.endss_.push(ends); + this.changed(); + } + /** + * Make a complete copy of the geometry. + * @return {!MultiPolygon} Clone. + * @api + */ + clone() { + const len = this.endss_.length; + const newEndss = new Array(len); + for (let i = 0; i < len; ++i) { + newEndss[i] = this.endss_[i].slice(); + } + const multiPolygon = new MultiPolygon( + this.flatCoordinates.slice(), + this.layout, + newEndss + ); + multiPolygon.applyProperties(this); + return multiPolygon; + } + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + multiArrayMaxSquaredDelta( + this.flatCoordinates, + 0, + this.endss_, + this.stride, + 0 + ) + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return assignClosestMultiArrayPoint( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + this.maxDelta_, + true, + x, + y, + closestPoint, + minSquaredDistance + ); + } + /** + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ + containsXY(x, y) { + return linearRingssContainsXY( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + x, + y + ); + } + /** + * Return the area of the multipolygon on projected plane. + * @return {number} Area (on projected plane). + * @api + */ + getArea() { + return linearRingss$1( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride + ); + } + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for multi-polygons. + * + * @param {boolean} [right] Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @return {Array>>} Coordinates. + * @api + */ + getCoordinates(right) { + let flatCoordinates; + if (right !== void 0) { + flatCoordinates = this.getOrientedFlatCoordinates().slice(); + orientLinearRingsArray( + flatCoordinates, + 0, + this.endss_, + this.stride, + right + ); + } else { + flatCoordinates = this.flatCoordinates; + } + return inflateMultiCoordinatesArray( + flatCoordinates, + 0, + this.endss_, + this.stride + ); + } + /** + * @return {Array>} Endss. + */ + getEndss() { + return this.endss_; + } + /** + * @return {Array} Flat interior points. + */ + getFlatInteriorPoints() { + if (this.flatInteriorPointsRevision_ != this.getRevision()) { + const flatCenters = linearRingss( + this.flatCoordinates, + 0, + this.endss_, + this.stride + ); + this.flatInteriorPoints_ = getInteriorPointsOfMultiArray( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + flatCenters + ); + this.flatInteriorPointsRevision_ = this.getRevision(); + } + return this.flatInteriorPoints_; + } + /** + * Return the interior points as {@link module:ol/geom/MultiPoint~MultiPoint multipoint}. + * @return {MultiPoint} Interior points as XYM coordinates, where M is + * the length of the horizontal intersection that the point belongs to. + * @api + */ + getInteriorPoints() { + return new MultiPoint$1(this.getFlatInteriorPoints().slice(), "XYM"); + } + /** + * @return {Array} Oriented flat coordinates. + */ + getOrientedFlatCoordinates() { + if (this.orientedRevision_ != this.getRevision()) { + const flatCoordinates = this.flatCoordinates; + if (linearRingssAreOriented(flatCoordinates, 0, this.endss_, this.stride)) { + this.orientedFlatCoordinates_ = flatCoordinates; + } else { + this.orientedFlatCoordinates_ = flatCoordinates.slice(); + this.orientedFlatCoordinates_.length = orientLinearRingsArray( + this.orientedFlatCoordinates_, + 0, + this.endss_, + this.stride + ); + } + this.orientedRevision_ = this.getRevision(); + } + return this.orientedFlatCoordinates_; + } + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {MultiPolygon} Simplified MultiPolygon. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + const simplifiedFlatCoordinates = []; + const simplifiedEndss = []; + simplifiedFlatCoordinates.length = quantizeMultiArray( + this.flatCoordinates, + 0, + this.endss_, + this.stride, + Math.sqrt(squaredTolerance), + simplifiedFlatCoordinates, + 0, + simplifiedEndss + ); + return new MultiPolygon(simplifiedFlatCoordinates, "XY", simplifiedEndss); + } + /** + * Return the polygon at the specified index. + * @param {number} index Index. + * @return {Polygon} Polygon. + * @api + */ + getPolygon(index) { + if (index < 0 || this.endss_.length <= index) { + return null; + } + let offset; + if (index === 0) { + offset = 0; + } else { + const prevEnds = this.endss_[index - 1]; + offset = prevEnds[prevEnds.length - 1]; + } + const ends = this.endss_[index].slice(); + const end = ends[ends.length - 1]; + if (offset !== 0) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + ends[i] -= offset; + } + } + return new Polygon$1( + this.flatCoordinates.slice(offset, end), + this.layout, + ends + ); + } + /** + * Return the polygons of this multipolygon. + * @return {Array} Polygons. + * @api + */ + getPolygons() { + const layout = this.layout; + const flatCoordinates = this.flatCoordinates; + const endss = this.endss_; + const polygons = []; + let offset = 0; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i].slice(); + const end = ends[ends.length - 1]; + if (offset !== 0) { + for (let j = 0, jj = ends.length; j < jj; ++j) { + ends[j] -= offset; + } + } + const polygon = new Polygon$1( + flatCoordinates.slice(offset, end), + layout, + ends + ); + polygons.push(polygon); + offset = end; + } + return polygons; + } + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return "MultiPolygon"; + } + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return intersectsLinearRingMultiArray( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + extent + ); + } + /** + * Set the coordinates of the multipolygon. + * @param {!Array>>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates2, layout) { + this.setLayout(layout, coordinates2, 3); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + const endss = deflateMultiCoordinatesArray( + this.flatCoordinates, + 0, + coordinates2, + this.stride, + this.endss_ + ); + if (endss.length === 0) { + this.flatCoordinates.length = 0; + } else { + const lastEnds = endss[endss.length - 1]; + this.flatCoordinates.length = lastEnds.length === 0 ? 0 : lastEnds[lastEnds.length - 1]; + } + this.changed(); + } +} +const MultiPolygon$1 = MultiPolygon; +class GeoJSON extends JSONFeature$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + super(); + this.dataProjection = get$1( + options.dataProjection ? options.dataProjection : "EPSG:4326" + ); + if (options.featureProjection) { + this.defaultFeatureProjection = get$1(options.featureProjection); + } + this.geometryName_ = options.geometryName; + this.extractGeometryName_ = options.extractGeometryName; + this.supportedMediaTypes = [ + "application/geo+json", + "application/vnd.geo+json" + ]; + } + /** + * @param {Object} object Object. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {import("../Feature.js").default} Feature. + */ + readFeatureFromObject(object, options) { + let geoJSONFeature = null; + if (object["type"] === "Feature") { + geoJSONFeature = /** @type {GeoJSONFeature} */ + object; + } else { + geoJSONFeature = { + "type": "Feature", + "geometry": ( + /** @type {GeoJSONGeometry} */ + object + ), + "properties": null + }; + } + const geometry = readGeometry(geoJSONFeature["geometry"], options); + const feature = new Feature$1(); + if (this.geometryName_) { + feature.setGeometryName(this.geometryName_); + } else if (this.extractGeometryName_ && "geometry_name" in geoJSONFeature !== void 0) { + feature.setGeometryName(geoJSONFeature["geometry_name"]); + } + feature.setGeometry(geometry); + if ("id" in geoJSONFeature) { + feature.setId(geoJSONFeature["id"]); + } + if (geoJSONFeature["properties"]) { + feature.setProperties(geoJSONFeature["properties"], true); + } + return feature; + } + /** + * @param {Object} object Object. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {Array} Features. + */ + readFeaturesFromObject(object, options) { + const geoJSONObject = ( + /** @type {GeoJSONObject} */ + object + ); + let features = null; + if (geoJSONObject["type"] === "FeatureCollection") { + const geoJSONFeatureCollection = ( + /** @type {GeoJSONFeatureCollection} */ + object + ); + features = []; + const geoJSONFeatures = geoJSONFeatureCollection["features"]; + for (let i = 0, ii = geoJSONFeatures.length; i < ii; ++i) { + features.push(this.readFeatureFromObject(geoJSONFeatures[i], options)); + } + } else { + features = [this.readFeatureFromObject(object, options)]; + } + return features; + } + /** + * @param {GeoJSONGeometry} object Object. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {import("../geom/Geometry.js").default} Geometry. + */ + readGeometryFromObject(object, options) { + return readGeometry(object, options); + } + /** + * @param {Object} object Object. + * @protected + * @return {import("../proj/Projection.js").default} Projection. + */ + readProjectionFromObject(object) { + const crs = object["crs"]; + let projection; + if (crs) { + if (crs["type"] == "name") { + projection = get$1(crs["properties"]["name"]); + } else if (crs["type"] === "EPSG") { + projection = get$1("EPSG:" + crs["properties"]["code"]); + } else { + throw new Error("Unknown SRS type"); + } + } else { + projection = this.dataProjection; + } + return ( + /** @type {import("../proj/Projection.js").default} */ + projection + ); + } + /** + * Encode a feature as a GeoJSON Feature object. + * + * @param {import("../Feature.js").default} feature Feature. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {GeoJSONFeature} Object. + * @api + */ + writeFeatureObject(feature, options) { + options = this.adaptOptions(options); + const object = { + "type": "Feature", + geometry: null, + properties: null + }; + const id = feature.getId(); + if (id !== void 0) { + object.id = id; + } + if (!feature.hasProperties()) { + return object; + } + const properties = feature.getProperties(); + const geometry = feature.getGeometry(); + if (geometry) { + object.geometry = writeGeometry(geometry, options); + delete properties[feature.getGeometryName()]; + } + if (!isEmpty$1(properties)) { + object.properties = properties; + } + return object; + } + /** + * Encode an array of features as a GeoJSON object. + * + * @param {Array} features Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {GeoJSONFeatureCollection} GeoJSON Object. + * @api + */ + writeFeaturesObject(features, options) { + options = this.adaptOptions(options); + const objects = []; + for (let i = 0, ii = features.length; i < ii; ++i) { + objects.push(this.writeFeatureObject(features[i], options)); + } + return { + type: "FeatureCollection", + features: objects + }; + } + /** + * Encode a geometry as a GeoJSON object. + * + * @param {import("../geom/Geometry.js").default} geometry Geometry. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {GeoJSONGeometry|GeoJSONGeometryCollection} Object. + * @api + */ + writeGeometryObject(geometry, options) { + return writeGeometry(geometry, this.adaptOptions(options)); + } +} +function readGeometry(object, options) { + if (!object) { + return null; + } + let geometry; + switch (object["type"]) { + case "Point": { + geometry = readPointGeometry( + /** @type {GeoJSONPoint} */ + object + ); + break; + } + case "LineString": { + geometry = readLineStringGeometry( + /** @type {GeoJSONLineString} */ + object + ); + break; + } + case "Polygon": { + geometry = readPolygonGeometry( + /** @type {GeoJSONPolygon} */ + object + ); + break; + } + case "MultiPoint": { + geometry = readMultiPointGeometry( + /** @type {GeoJSONMultiPoint} */ + object + ); + break; + } + case "MultiLineString": { + geometry = readMultiLineStringGeometry( + /** @type {GeoJSONMultiLineString} */ + object + ); + break; + } + case "MultiPolygon": { + geometry = readMultiPolygonGeometry( + /** @type {GeoJSONMultiPolygon} */ + object + ); + break; + } + case "GeometryCollection": { + geometry = readGeometryCollectionGeometry( + /** @type {GeoJSONGeometryCollection} */ + object + ); + break; + } + default: { + throw new Error("Unsupported GeoJSON type: " + object["type"]); + } + } + return transformGeometryWithOptions(geometry, false, options); +} +function readGeometryCollectionGeometry(object, options) { + const geometries = object["geometries"].map( + /** + * @param {GeoJSONGeometry} geometry Geometry. + * @return {import("../geom/Geometry.js").default} geometry Geometry. + */ + function(geometry) { + return readGeometry(geometry, options); + } + ); + return new GeometryCollection$1(geometries); +} +function readPointGeometry(object) { + return new OlPoint(object["coordinates"]); +} +function readLineStringGeometry(object) { + return new LineString$1(object["coordinates"]); +} +function readMultiLineStringGeometry(object) { + return new MultiLineString$1(object["coordinates"]); +} +function readMultiPointGeometry(object) { + return new MultiPoint$1(object["coordinates"]); +} +function readMultiPolygonGeometry(object) { + return new MultiPolygon$1(object["coordinates"]); +} +function readPolygonGeometry(object) { + return new Polygon$1(object["coordinates"]); +} +function writeGeometry(geometry, options) { + geometry = transformGeometryWithOptions(geometry, true, options); + const type = geometry.getType(); + let geoJSON; + switch (type) { + case "Point": { + geoJSON = writePointGeometry( + /** @type {Point} */ + geometry + ); + break; + } + case "LineString": { + geoJSON = writeLineStringGeometry( + /** @type {LineString} */ + geometry + ); + break; + } + case "Polygon": { + geoJSON = writePolygonGeometry( + /** @type {Polygon} */ + geometry, + options + ); + break; + } + case "MultiPoint": { + geoJSON = writeMultiPointGeometry( + /** @type {MultiPoint} */ + geometry + ); + break; + } + case "MultiLineString": { + geoJSON = writeMultiLineStringGeometry( + /** @type {MultiLineString} */ + geometry + ); + break; + } + case "MultiPolygon": { + geoJSON = writeMultiPolygonGeometry( + /** @type {MultiPolygon} */ + geometry, + options + ); + break; + } + case "GeometryCollection": { + geoJSON = writeGeometryCollectionGeometry( + /** @type {GeometryCollection} */ + geometry, + options + ); + break; + } + case "Circle": { + geoJSON = { + type: "GeometryCollection", + geometries: [] + }; + break; + } + default: { + throw new Error("Unsupported geometry type: " + type); + } + } + return geoJSON; +} +function writeGeometryCollectionGeometry(geometry, options) { + options = Object.assign({}, options); + delete options.featureProjection; + const geometries = geometry.getGeometriesArray().map(function(geometry2) { + return writeGeometry(geometry2, options); + }); + return { + type: "GeometryCollection", + geometries + }; +} +function writeLineStringGeometry(geometry, options) { + return { + type: "LineString", + coordinates: geometry.getCoordinates() + }; +} +function writeMultiLineStringGeometry(geometry, options) { + return { + type: "MultiLineString", + coordinates: geometry.getCoordinates() + }; +} +function writeMultiPointGeometry(geometry, options) { + return { + type: "MultiPoint", + coordinates: geometry.getCoordinates() + }; +} +function writeMultiPolygonGeometry(geometry, options) { + let right; + if (options) { + right = options.rightHanded; + } + return { + type: "MultiPolygon", + coordinates: geometry.getCoordinates(right) + }; +} +function writePointGeometry(geometry, options) { + return { + type: "Point", + coordinates: geometry.getCoordinates() + }; +} +function writePolygonGeometry(geometry, options) { + let right; + if (options) { + right = options.rightHanded; + } + return { + type: "Polygon", + coordinates: geometry.getCoordinates(right) + }; +} +const OlGeoJson = GeoJSON; +const Property$1 = { + ELEMENT: "element", + MAP: "map", + OFFSET: "offset", + POSITION: "position", + POSITIONING: "positioning" +}; +class Overlay extends BaseObject$1 { + /** + * @param {Options} options Overlay options. + */ + constructor(options) { + super(); + this.on; + this.once; + this.un; + this.options = options; + this.id = options.id; + this.insertFirst = options.insertFirst !== void 0 ? options.insertFirst : true; + this.stopEvent = options.stopEvent !== void 0 ? options.stopEvent : true; + this.element = document.createElement("div"); + this.element.className = options.className !== void 0 ? options.className : "ol-overlay-container " + CLASS_SELECTABLE; + this.element.style.position = "absolute"; + this.element.style.pointerEvents = "auto"; + this.autoPan = options.autoPan === true ? {} : options.autoPan || void 0; + this.rendered = { + transform_: "", + visible: true + }; + this.mapPostrenderListenerKey = null; + this.addChangeListener(Property$1.ELEMENT, this.handleElementChanged); + this.addChangeListener(Property$1.MAP, this.handleMapChanged); + this.addChangeListener(Property$1.OFFSET, this.handleOffsetChanged); + this.addChangeListener(Property$1.POSITION, this.handlePositionChanged); + this.addChangeListener(Property$1.POSITIONING, this.handlePositioningChanged); + if (options.element !== void 0) { + this.setElement(options.element); + } + this.setOffset(options.offset !== void 0 ? options.offset : [0, 0]); + this.setPositioning(options.positioning || "top-left"); + if (options.position !== void 0) { + this.setPosition(options.position); + } + } + /** + * Get the DOM element of this overlay. + * @return {HTMLElement|undefined} The Element containing the overlay. + * @observable + * @api + */ + getElement() { + return ( + /** @type {HTMLElement|undefined} */ + this.get(Property$1.ELEMENT) + ); + } + /** + * Get the overlay identifier which is set on constructor. + * @return {number|string|undefined} Id. + * @api + */ + getId() { + return this.id; + } + /** + * Get the map associated with this overlay. + * @return {import("./Map.js").default|null} The map that the + * overlay is part of. + * @observable + * @api + */ + getMap() { + return ( + /** @type {import("./Map.js").default|null} */ + this.get(Property$1.MAP) || null + ); + } + /** + * Get the offset of this overlay. + * @return {Array} The offset. + * @observable + * @api + */ + getOffset() { + return ( + /** @type {Array} */ + this.get(Property$1.OFFSET) + ); + } + /** + * Get the current position of this overlay. + * @return {import("./coordinate.js").Coordinate|undefined} The spatial point that the overlay is + * anchored at. + * @observable + * @api + */ + getPosition() { + return ( + /** @type {import("./coordinate.js").Coordinate|undefined} */ + this.get(Property$1.POSITION) + ); + } + /** + * Get the current positioning of this overlay. + * @return {Positioning} How the overlay is positioned + * relative to its point on the map. + * @observable + * @api + */ + getPositioning() { + return ( + /** @type {Positioning} */ + this.get(Property$1.POSITIONING) + ); + } + /** + * @protected + */ + handleElementChanged() { + removeChildren(this.element); + const element = this.getElement(); + if (element) { + this.element.appendChild(element); + } + } + /** + * @protected + */ + handleMapChanged() { + if (this.mapPostrenderListenerKey) { + removeNode(this.element); + unlistenByKey(this.mapPostrenderListenerKey); + this.mapPostrenderListenerKey = null; + } + const map = this.getMap(); + if (map) { + this.mapPostrenderListenerKey = listen( + map, + MapEventType.POSTRENDER, + this.render, + this + ); + this.updatePixelPosition(); + const container = this.stopEvent ? map.getOverlayContainerStopEvent() : map.getOverlayContainer(); + if (this.insertFirst) { + container.insertBefore(this.element, container.childNodes[0] || null); + } else { + container.appendChild(this.element); + } + this.performAutoPan(); + } + } + /** + * @protected + */ + render() { + this.updatePixelPosition(); + } + /** + * @protected + */ + handleOffsetChanged() { + this.updatePixelPosition(); + } + /** + * @protected + */ + handlePositionChanged() { + this.updatePixelPosition(); + this.performAutoPan(); + } + /** + * @protected + */ + handlePositioningChanged() { + this.updatePixelPosition(); + } + /** + * Set the DOM element to be associated with this overlay. + * @param {HTMLElement|undefined} element The Element containing the overlay. + * @observable + * @api + */ + setElement(element) { + this.set(Property$1.ELEMENT, element); + } + /** + * Set the map to be associated with this overlay. + * @param {import("./Map.js").default|null} map The map that the + * overlay is part of. Pass `null` to just remove the overlay from the current map. + * @observable + * @api + */ + setMap(map) { + this.set(Property$1.MAP, map); + } + /** + * Set the offset for this overlay. + * @param {Array} offset Offset. + * @observable + * @api + */ + setOffset(offset) { + this.set(Property$1.OFFSET, offset); + } + /** + * Set the position for this overlay. If the position is `undefined` the + * overlay is hidden. + * @param {import("./coordinate.js").Coordinate|undefined} position The spatial point that the overlay + * is anchored at. + * @observable + * @api + */ + setPosition(position) { + this.set(Property$1.POSITION, position); + } + /** + * Pan the map so that the overlay is entirely visible in the current viewport + * (if necessary) using the configured autoPan parameters + * @protected + */ + performAutoPan() { + if (this.autoPan) { + this.panIntoView(this.autoPan); + } + } + /** + * Pan the map so that the overlay is entirely visible in the current viewport + * (if necessary). + * @param {PanIntoViewOptions} [panIntoViewOptions] Options for the pan action + * @api + */ + panIntoView(panIntoViewOptions) { + const map = this.getMap(); + if (!map || !map.getTargetElement() || !this.get(Property$1.POSITION)) { + return; + } + const mapRect = this.getRect(map.getTargetElement(), map.getSize()); + const element = this.getElement(); + const overlayRect = this.getRect(element, [ + outerWidth(element), + outerHeight(element) + ]); + panIntoViewOptions = panIntoViewOptions || {}; + const myMargin = panIntoViewOptions.margin === void 0 ? 20 : panIntoViewOptions.margin; + if (!containsExtent(mapRect, overlayRect)) { + const offsetLeft = overlayRect[0] - mapRect[0]; + const offsetRight = mapRect[2] - overlayRect[2]; + const offsetTop = overlayRect[1] - mapRect[1]; + const offsetBottom = mapRect[3] - overlayRect[3]; + const delta = [0, 0]; + if (offsetLeft < 0) { + delta[0] = offsetLeft - myMargin; + } else if (offsetRight < 0) { + delta[0] = Math.abs(offsetRight) + myMargin; + } + if (offsetTop < 0) { + delta[1] = offsetTop - myMargin; + } else if (offsetBottom < 0) { + delta[1] = Math.abs(offsetBottom) + myMargin; + } + if (delta[0] !== 0 || delta[1] !== 0) { + const center = ( + /** @type {import("./coordinate.js").Coordinate} */ + map.getView().getCenterInternal() + ); + const centerPx = map.getPixelFromCoordinateInternal(center); + if (!centerPx) { + return; + } + const newCenterPx = [centerPx[0] + delta[0], centerPx[1] + delta[1]]; + const panOptions = panIntoViewOptions.animation || {}; + map.getView().animateInternal({ + center: map.getCoordinateFromPixelInternal(newCenterPx), + duration: panOptions.duration, + easing: panOptions.easing + }); + } + } + } + /** + * Get the extent of an element relative to the document + * @param {HTMLElement} element The element. + * @param {import("./size.js").Size} size The size of the element. + * @return {import("./extent.js").Extent} The extent. + * @protected + */ + getRect(element, size) { + const box = element.getBoundingClientRect(); + const offsetX = box.left + window.pageXOffset; + const offsetY = box.top + window.pageYOffset; + return [offsetX, offsetY, offsetX + size[0], offsetY + size[1]]; + } + /** + * Set the positioning for this overlay. + * @param {Positioning} positioning how the overlay is + * positioned relative to its point on the map. + * @observable + * @api + */ + setPositioning(positioning) { + this.set(Property$1.POSITIONING, positioning); + } + /** + * Modify the visibility of the element. + * @param {boolean} visible Element visibility. + * @protected + */ + setVisible(visible) { + if (this.rendered.visible !== visible) { + this.element.style.display = visible ? "" : "none"; + this.rendered.visible = visible; + } + } + /** + * Update pixel position. + * @protected + */ + updatePixelPosition() { + const map = this.getMap(); + const position = this.getPosition(); + if (!map || !map.isRendered() || !position) { + this.setVisible(false); + return; + } + const pixel = map.getPixelFromCoordinate(position); + const mapSize = map.getSize(); + this.updateRenderedPosition(pixel, mapSize); + } + /** + * @param {import("./pixel.js").Pixel} pixel The pixel location. + * @param {import("./size.js").Size|undefined} mapSize The map size. + * @protected + */ + updateRenderedPosition(pixel, mapSize) { + const style = this.element.style; + const offset = this.getOffset(); + const positioning = this.getPositioning(); + this.setVisible(true); + const x = Math.round(pixel[0] + offset[0]) + "px"; + const y = Math.round(pixel[1] + offset[1]) + "px"; + let posX = "0%"; + let posY = "0%"; + if (positioning == "bottom-right" || positioning == "center-right" || positioning == "top-right") { + posX = "-100%"; + } else if (positioning == "bottom-center" || positioning == "center-center" || positioning == "top-center") { + posX = "-50%"; + } + if (positioning == "bottom-left" || positioning == "bottom-center" || positioning == "bottom-right") { + posY = "-100%"; + } else if (positioning == "center-left" || positioning == "center-center" || positioning == "center-right") { + posY = "-50%"; + } + const transform2 = `translate(${posX}, ${posY}) translate(${x}, ${y})`; + if (this.rendered.transform_ != transform2) { + this.rendered.transform_ = transform2; + style.transform = transform2; + } + } + /** + * returns the options this Overlay has been created with + * @return {Options} overlay options + */ + getOptions() { + return this.options; + } +} +const OlOverlay = Overlay; +function quickselect(arr, k, left, right, compare) { + quickselectStep(arr, k, left || 0, right || arr.length - 1, compare || defaultCompare); +} +function quickselectStep(arr, k, left, right, compare) { + while (right > left) { + if (right - left > 600) { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + quickselectStep(arr, k, newLeft, newRight, compare); + } + var t = arr[k]; + var i = left; + var j = right; + swap(arr, left, k); + if (compare(arr[right], t) > 0) + swap(arr, left, right); + while (i < j) { + swap(arr, i, j); + i++; + j--; + while (compare(arr[i], t) < 0) + i++; + while (compare(arr[j], t) > 0) + j--; + } + if (compare(arr[left], t) === 0) + swap(arr, left, j); + else { + j++; + swap(arr, j, right); + } + if (j <= k) + left = j + 1; + if (k <= j) + right = j - 1; + } +} +function swap(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} +let RBush$2 = class RBush { + constructor(maxEntries = 9) { + this._maxEntries = Math.max(4, maxEntries); + this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4)); + this.clear(); + } + all() { + return this._all(this.data, []); + } + search(bbox) { + let node = this.data; + const result = []; + if (!intersects(bbox, node)) + return result; + const toBBox = this.toBBox; + const nodesToSearch = []; + while (node) { + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + const childBBox = node.leaf ? toBBox(child) : child; + if (intersects(bbox, childBBox)) { + if (node.leaf) + result.push(child); + else if (contains(bbox, childBBox)) + this._all(child, result); + else + nodesToSearch.push(child); + } + } + node = nodesToSearch.pop(); + } + return result; + } + collides(bbox) { + let node = this.data; + if (!intersects(bbox, node)) + return false; + const nodesToSearch = []; + while (node) { + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + const childBBox = node.leaf ? this.toBBox(child) : child; + if (intersects(bbox, childBBox)) { + if (node.leaf || contains(bbox, childBBox)) + return true; + nodesToSearch.push(child); + } + } + node = nodesToSearch.pop(); + } + return false; + } + load(data) { + if (!(data && data.length)) + return this; + if (data.length < this._minEntries) { + for (let i = 0; i < data.length; i++) { + this.insert(data[i]); + } + return this; + } + let node = this._build(data.slice(), 0, data.length - 1, 0); + if (!this.data.children.length) { + this.data = node; + } else if (this.data.height === node.height) { + this._splitRoot(this.data, node); + } else { + if (this.data.height < node.height) { + const tmpNode = this.data; + this.data = node; + node = tmpNode; + } + this._insert(node, this.data.height - node.height - 1, true); + } + return this; + } + insert(item) { + if (item) + this._insert(item, this.data.height - 1); + return this; + } + clear() { + this.data = createNode([]); + return this; + } + remove(item, equalsFn) { + if (!item) + return this; + let node = this.data; + const bbox = this.toBBox(item); + const path = []; + const indexes = []; + let i, parent, goingUp; + while (node || path.length) { + if (!node) { + node = path.pop(); + parent = path[path.length - 1]; + i = indexes.pop(); + goingUp = true; + } + if (node.leaf) { + const index = findItem(item, node.children, equalsFn); + if (index !== -1) { + node.children.splice(index, 1); + path.push(node); + this._condense(path); + return this; + } + } + if (!goingUp && !node.leaf && contains(node, bbox)) { + path.push(node); + indexes.push(i); + i = 0; + parent = node; + node = node.children[0]; + } else if (parent) { + i++; + node = parent.children[i]; + goingUp = false; + } else + node = null; + } + return this; + } + toBBox(item) { + return item; + } + compareMinX(a, b) { + return a.minX - b.minX; + } + compareMinY(a, b) { + return a.minY - b.minY; + } + toJSON() { + return this.data; + } + fromJSON(data) { + this.data = data; + return this; + } + _all(node, result) { + const nodesToSearch = []; + while (node) { + if (node.leaf) + result.push(...node.children); + else + nodesToSearch.push(...node.children); + node = nodesToSearch.pop(); + } + return result; + } + _build(items, left, right, height) { + const N = right - left + 1; + let M2 = this._maxEntries; + let node; + if (N <= M2) { + node = createNode(items.slice(left, right + 1)); + calcBBox(node, this.toBBox); + return node; + } + if (!height) { + height = Math.ceil(Math.log(N) / Math.log(M2)); + M2 = Math.ceil(N / Math.pow(M2, height - 1)); + } + node = createNode([]); + node.leaf = false; + node.height = height; + const N2 = Math.ceil(N / M2); + const N1 = N2 * Math.ceil(Math.sqrt(M2)); + multiSelect(items, left, right, N1, this.compareMinX); + for (let i = left; i <= right; i += N1) { + const right2 = Math.min(i + N1 - 1, right); + multiSelect(items, i, right2, N2, this.compareMinY); + for (let j = i; j <= right2; j += N2) { + const right3 = Math.min(j + N2 - 1, right2); + node.children.push(this._build(items, j, right3, height - 1)); + } + } + calcBBox(node, this.toBBox); + return node; + } + _chooseSubtree(bbox, node, level2, path) { + while (true) { + path.push(node); + if (node.leaf || path.length - 1 === level2) + break; + let minArea = Infinity; + let minEnlargement = Infinity; + let targetNode; + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + const area = bboxArea(child); + const enlargement = enlargedArea(bbox, child) - area; + if (enlargement < minEnlargement) { + minEnlargement = enlargement; + minArea = area < minArea ? area : minArea; + targetNode = child; + } else if (enlargement === minEnlargement) { + if (area < minArea) { + minArea = area; + targetNode = child; + } + } + } + node = targetNode || node.children[0]; + } + return node; + } + _insert(item, level2, isNode) { + const bbox = isNode ? item : this.toBBox(item); + const insertPath = []; + const node = this._chooseSubtree(bbox, this.data, level2, insertPath); + node.children.push(item); + extend(node, bbox); + while (level2 >= 0) { + if (insertPath[level2].children.length > this._maxEntries) { + this._split(insertPath, level2); + level2--; + } else + break; + } + this._adjustParentBBoxes(bbox, insertPath, level2); + } + // split overflowed node into two + _split(insertPath, level2) { + const node = insertPath[level2]; + const M2 = node.children.length; + const m = this._minEntries; + this._chooseSplitAxis(node, m, M2); + const splitIndex = this._chooseSplitIndex(node, m, M2); + const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex)); + newNode.height = node.height; + newNode.leaf = node.leaf; + calcBBox(node, this.toBBox); + calcBBox(newNode, this.toBBox); + if (level2) + insertPath[level2 - 1].children.push(newNode); + else + this._splitRoot(node, newNode); + } + _splitRoot(node, newNode) { + this.data = createNode([node, newNode]); + this.data.height = node.height + 1; + this.data.leaf = false; + calcBBox(this.data, this.toBBox); + } + _chooseSplitIndex(node, m, M2) { + let index; + let minOverlap = Infinity; + let minArea = Infinity; + for (let i = m; i <= M2 - m; i++) { + const bbox1 = distBBox(node, 0, i, this.toBBox); + const bbox2 = distBBox(node, i, M2, this.toBBox); + const overlap = intersectionArea(bbox1, bbox2); + const area = bboxArea(bbox1) + bboxArea(bbox2); + if (overlap < minOverlap) { + minOverlap = overlap; + index = i; + minArea = area < minArea ? area : minArea; + } else if (overlap === minOverlap) { + if (area < minArea) { + minArea = area; + index = i; + } + } + } + return index || M2 - m; + } + // sorts node children by the best axis for split + _chooseSplitAxis(node, m, M2) { + const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX; + const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY; + const xMargin = this._allDistMargin(node, m, M2, compareMinX); + const yMargin = this._allDistMargin(node, m, M2, compareMinY); + if (xMargin < yMargin) + node.children.sort(compareMinX); + } + // total margin of all possible split distributions where each node is at least m full + _allDistMargin(node, m, M2, compare) { + node.children.sort(compare); + const toBBox = this.toBBox; + const leftBBox = distBBox(node, 0, m, toBBox); + const rightBBox = distBBox(node, M2 - m, M2, toBBox); + let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox); + for (let i = m; i < M2 - m; i++) { + const child = node.children[i]; + extend(leftBBox, node.leaf ? toBBox(child) : child); + margin += bboxMargin(leftBBox); + } + for (let i = M2 - m - 1; i >= m; i--) { + const child = node.children[i]; + extend(rightBBox, node.leaf ? toBBox(child) : child); + margin += bboxMargin(rightBBox); + } + return margin; + } + _adjustParentBBoxes(bbox, path, level2) { + for (let i = level2; i >= 0; i--) { + extend(path[i], bbox); + } + } + _condense(path) { + for (let i = path.length - 1, siblings; i >= 0; i--) { + if (path[i].children.length === 0) { + if (i > 0) { + siblings = path[i - 1].children; + siblings.splice(siblings.indexOf(path[i]), 1); + } else + this.clear(); + } else + calcBBox(path[i], this.toBBox); + } + } +}; +function findItem(item, items, equalsFn) { + if (!equalsFn) + return items.indexOf(item); + for (let i = 0; i < items.length; i++) { + if (equalsFn(item, items[i])) + return i; + } + return -1; +} +function calcBBox(node, toBBox) { + distBBox(node, 0, node.children.length, toBBox, node); +} +function distBBox(node, k, p, toBBox, destNode) { + if (!destNode) + destNode = createNode(null); + destNode.minX = Infinity; + destNode.minY = Infinity; + destNode.maxX = -Infinity; + destNode.maxY = -Infinity; + for (let i = k; i < p; i++) { + const child = node.children[i]; + extend(destNode, node.leaf ? toBBox(child) : child); + } + return destNode; +} +function extend(a, b) { + a.minX = Math.min(a.minX, b.minX); + a.minY = Math.min(a.minY, b.minY); + a.maxX = Math.max(a.maxX, b.maxX); + a.maxY = Math.max(a.maxY, b.maxY); + return a; +} +function compareNodeMinX(a, b) { + return a.minX - b.minX; +} +function compareNodeMinY(a, b) { + return a.minY - b.minY; +} +function bboxArea(a) { + return (a.maxX - a.minX) * (a.maxY - a.minY); +} +function bboxMargin(a) { + return a.maxX - a.minX + (a.maxY - a.minY); +} +function enlargedArea(a, b) { + return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY)); +} +function intersectionArea(a, b) { + const minX = Math.max(a.minX, b.minX); + const minY = Math.max(a.minY, b.minY); + const maxX = Math.min(a.maxX, b.maxX); + const maxY = Math.min(a.maxY, b.maxY); + return Math.max(0, maxX - minX) * Math.max(0, maxY - minY); +} +function contains(a, b) { + return a.minX <= b.minX && a.minY <= b.minY && b.maxX <= a.maxX && b.maxY <= a.maxY; +} +function intersects(a, b) { + return b.minX <= a.maxX && b.minY <= a.maxY && b.maxX >= a.minX && b.maxY >= a.minY; +} +function createNode(children) { + return { + children, + height: 1, + leaf: true, + minX: Infinity, + minY: Infinity, + maxX: -Infinity, + maxY: -Infinity + }; +} +function multiSelect(arr, left, right, n, compare) { + const stack = [left, right]; + while (stack.length) { + right = stack.pop(); + left = stack.pop(); + if (right - left <= n) + continue; + const mid = left + Math.ceil((right - left) / n / 2) * n; + quickselect(arr, mid, left, right, compare); + stack.push(left, mid, mid, right); + } +} +class RBush2 { + /** + * @param {number} [maxEntries] Max entries. + */ + constructor(maxEntries) { + this.rbush_ = new RBush$2(maxEntries); + this.items_ = {}; + } + /** + * Insert a value into the RBush. + * @param {import("../extent.js").Extent} extent Extent. + * @param {T} value Value. + */ + insert(extent, value) { + const item = { + minX: extent[0], + minY: extent[1], + maxX: extent[2], + maxY: extent[3], + value + }; + this.rbush_.insert(item); + this.items_[getUid(value)] = item; + } + /** + * Bulk-insert values into the RBush. + * @param {Array} extents Extents. + * @param {Array} values Values. + */ + load(extents, values) { + const items = new Array(values.length); + for (let i = 0, l = values.length; i < l; i++) { + const extent = extents[i]; + const value = values[i]; + const item = { + minX: extent[0], + minY: extent[1], + maxX: extent[2], + maxY: extent[3], + value + }; + items[i] = item; + this.items_[getUid(value)] = item; + } + this.rbush_.load(items); + } + /** + * Remove a value from the RBush. + * @param {T} value Value. + * @return {boolean} Removed. + */ + remove(value) { + const uid = getUid(value); + const item = this.items_[uid]; + delete this.items_[uid]; + return this.rbush_.remove(item) !== null; + } + /** + * Update the extent of a value in the RBush. + * @param {import("../extent.js").Extent} extent Extent. + * @param {T} value Value. + */ + update(extent, value) { + const item = this.items_[getUid(value)]; + const bbox = [item.minX, item.minY, item.maxX, item.maxY]; + if (!equals$1(bbox, extent)) { + this.remove(value); + this.insert(extent, value); + } + } + /** + * Return all values in the RBush. + * @return {Array} All. + */ + getAll() { + const items = this.rbush_.all(); + return items.map(function(item) { + return item.value; + }); + } + /** + * Return all values in the given extent. + * @param {import("../extent.js").Extent} extent Extent. + * @return {Array} All in extent. + */ + getInExtent(extent) { + const bbox = { + minX: extent[0], + minY: extent[1], + maxX: extent[2], + maxY: extent[3] + }; + const items = this.rbush_.search(bbox); + return items.map(function(item) { + return item.value; + }); + } + /** + * Calls a callback function with each value in the tree. + * If the callback returns a truthy value, this value is returned without + * checking the rest of the tree. + * @param {function(T): *} callback Callback. + * @return {*} Callback return value. + */ + forEach(callback) { + return this.forEach_(this.getAll(), callback); + } + /** + * Calls a callback function with each value in the provided extent. + * @param {import("../extent.js").Extent} extent Extent. + * @param {function(T): *} callback Callback. + * @return {*} Callback return value. + */ + forEachInExtent(extent, callback) { + return this.forEach_(this.getInExtent(extent), callback); + } + /** + * @param {Array} values Values. + * @param {function(T): *} callback Callback. + * @private + * @return {*} Callback return value. + */ + forEach_(values, callback) { + let result; + for (let i = 0, l = values.length; i < l; i++) { + result = callback(values[i]); + if (result) { + return result; + } + } + return result; + } + /** + * @return {boolean} Is empty. + */ + isEmpty() { + return isEmpty$1(this.items_); + } + /** + * Remove all values from the RBush. + */ + clear() { + this.rbush_.clear(); + this.items_ = {}; + } + /** + * @param {import("../extent.js").Extent} [extent] Extent. + * @return {import("../extent.js").Extent} Extent. + */ + getExtent(extent) { + const data = this.rbush_.toJSON(); + return createOrUpdate$2(data.minX, data.minY, data.maxX, data.maxY, extent); + } + /** + * @param {RBush} rbush R-Tree. + */ + concat(rbush) { + this.rbush_.load(rbush.rbush_.all()); + for (const i in rbush.items_) { + this.items_[i] = rbush.items_[i]; + } + } +} +const RBush$1 = RBush2; +class Source extends BaseObject$1 { + /** + * @param {Options} options Source options. + */ + constructor(options) { + super(); + this.projection = get$1(options.projection); + this.attributions_ = adaptAttributions(options.attributions); + this.attributionsCollapsible_ = options.attributionsCollapsible !== void 0 ? options.attributionsCollapsible : true; + this.loading = false; + this.state_ = options.state !== void 0 ? options.state : "ready"; + this.wrapX_ = options.wrapX !== void 0 ? options.wrapX : false; + this.interpolate_ = !!options.interpolate; + this.viewResolver = null; + this.viewRejector = null; + const self2 = this; + this.viewPromise_ = new Promise(function(resolve, reject) { + self2.viewResolver = resolve; + self2.viewRejector = reject; + }); + } + /** + * Get the attribution function for the source. + * @return {?Attribution} Attribution function. + * @api + */ + getAttributions() { + return this.attributions_; + } + /** + * @return {boolean} Attributions are collapsible. + * @api + */ + getAttributionsCollapsible() { + return this.attributionsCollapsible_; + } + /** + * Get the projection of the source. + * @return {import("../proj/Projection.js").default|null} Projection. + * @api + */ + getProjection() { + return this.projection; + } + /** + * @param {import("../proj/Projection").default} [projection] Projection. + * @return {Array|null} Resolutions. + */ + getResolutions(projection) { + return null; + } + /** + * @return {Promise} A promise for view-related properties. + */ + getView() { + return this.viewPromise_; + } + /** + * Get the state of the source, see {@link import("./Source.js").State} for possible states. + * @return {import("./Source.js").State} State. + * @api + */ + getState() { + return this.state_; + } + /** + * @return {boolean|undefined} Wrap X. + */ + getWrapX() { + return this.wrapX_; + } + /** + * @return {boolean} Use linear interpolation when resampling. + */ + getInterpolate() { + return this.interpolate_; + } + /** + * Refreshes the source. The source will be cleared, and data from the server will be reloaded. + * @api + */ + refresh() { + this.changed(); + } + /** + * Set the attributions of the source. + * @param {AttributionLike|undefined} attributions Attributions. + * Can be passed as `string`, `Array`, {@link module:ol/source/Source~Attribution}, + * or `undefined`. + * @api + */ + setAttributions(attributions) { + this.attributions_ = adaptAttributions(attributions); + this.changed(); + } + /** + * Set the state of the source. + * @param {import("./Source.js").State} state State. + */ + setState(state) { + this.state_ = state; + this.changed(); + } +} +function adaptAttributions(attributionLike) { + if (!attributionLike) { + return null; + } + if (Array.isArray(attributionLike)) { + return function(frameState) { + return attributionLike; + }; + } + if (typeof attributionLike === "function") { + return attributionLike; + } + return function(frameState) { + return [attributionLike]; + }; +} +const Source$1 = Source; +const VectorEventType = { + /** + * Triggered when a feature is added to the source. + * @event module:ol/source/Vector.VectorSourceEvent#addfeature + * @api + */ + ADDFEATURE: "addfeature", + /** + * Triggered when a feature is updated. + * @event module:ol/source/Vector.VectorSourceEvent#changefeature + * @api + */ + CHANGEFEATURE: "changefeature", + /** + * Triggered when the clear method is called on the source. + * @event module:ol/source/Vector.VectorSourceEvent#clear + * @api + */ + CLEAR: "clear", + /** + * Triggered when a feature is removed from the source. + * See {@link module:ol/source/Vector~VectorSource#clear source.clear()} for exceptions. + * @event module:ol/source/Vector.VectorSourceEvent#removefeature + * @api + */ + REMOVEFEATURE: "removefeature", + /** + * Triggered when features starts loading. + * @event module:ol/source/Vector.VectorSourceEvent#featuresloadstart + * @api + */ + FEATURESLOADSTART: "featuresloadstart", + /** + * Triggered when features finishes loading. + * @event module:ol/source/Vector.VectorSourceEvent#featuresloadend + * @api + */ + FEATURESLOADEND: "featuresloadend", + /** + * Triggered if feature loading results in an error. + * @event module:ol/source/Vector.VectorSourceEvent#featuresloaderror + * @api + */ + FEATURESLOADERROR: "featuresloaderror" +}; +function all(extent, resolution) { + return [[-Infinity, -Infinity, Infinity, Infinity]]; +} +let withCredentials = false; +function loadFeaturesXhr(url, format, extent, resolution, projection, success, failure) { + const xhr2 = new XMLHttpRequest(); + xhr2.open( + "GET", + typeof url === "function" ? url(extent, resolution, projection) : url, + true + ); + if (format.getType() == "arraybuffer") { + xhr2.responseType = "arraybuffer"; + } + xhr2.withCredentials = withCredentials; + xhr2.onload = function(event) { + if (!xhr2.status || xhr2.status >= 200 && xhr2.status < 300) { + const type = format.getType(); + let source; + if (type == "json" || type == "text") { + source = xhr2.responseText; + } else if (type == "xml") { + source = xhr2.responseXML; + if (!source) { + source = new DOMParser().parseFromString( + xhr2.responseText, + "application/xml" + ); + } + } else if (type == "arraybuffer") { + source = /** @type {ArrayBuffer} */ + xhr2.response; + } + if (source) { + success( + /** @type {Array} */ + format.readFeatures(source, { + extent, + featureProjection: projection + }), + format.readProjection(source) + ); + } else { + failure(); + } + } else { + failure(); + } + }; + xhr2.onerror = failure; + xhr2.send(); +} +function xhr(url, format) { + return function(extent, resolution, projection, success, failure) { + const source = ( + /** @type {import("./source/Vector").default} */ + this + ); + loadFeaturesXhr( + url, + format, + extent, + resolution, + projection, + /** + * @param {Array} features The loaded features. + * @param {import("./proj/Projection.js").default} dataProjection Data + * projection. + */ + function(features, dataProjection) { + source.addFeatures(features); + if (success !== void 0) { + success(features); + } + }, + /* FIXME handle error */ + failure ? failure : VOID + ); + }; +} +class VectorSourceEvent extends Event { + /** + * @param {string} type Type. + * @param {import("../Feature.js").default} [feature] Feature. + * @param {Array>} [features] Features. + */ + constructor(type, feature, features) { + super(type); + this.feature = feature; + this.features = features; + } +} +class VectorSource extends Source$1 { + /** + * @param {Options} [options] Vector source options. + */ + constructor(options) { + options = options || {}; + super({ + attributions: options.attributions, + interpolate: true, + projection: void 0, + state: "ready", + wrapX: options.wrapX !== void 0 ? options.wrapX : true + }); + this.on; + this.once; + this.un; + this.loader_ = VOID; + this.format_ = options.format; + this.overlaps_ = options.overlaps === void 0 ? true : options.overlaps; + this.url_ = options.url; + if (options.loader !== void 0) { + this.loader_ = options.loader; + } else if (this.url_ !== void 0) { + assert(this.format_, "`format` must be set when `url` is set"); + this.loader_ = xhr( + this.url_, + /** @type {import("../format/Feature.js").default} */ + this.format_ + ); + } + this.strategy_ = options.strategy !== void 0 ? options.strategy : all; + const useSpatialIndex = options.useSpatialIndex !== void 0 ? options.useSpatialIndex : true; + this.featuresRtree_ = useSpatialIndex ? new RBush$1() : null; + this.loadedExtentsRtree_ = new RBush$1(); + this.loadingExtentsCount_ = 0; + this.nullGeometryFeatures_ = {}; + this.idIndex_ = {}; + this.uidIndex_ = {}; + this.featureChangeKeys_ = {}; + this.featuresCollection_ = null; + let collection; + let features; + if (Array.isArray(options.features)) { + features = options.features; + } else if (options.features) { + collection = options.features; + features = collection.getArray(); + } + if (!useSpatialIndex && collection === void 0) { + collection = new Collection$1(features); + } + if (features !== void 0) { + this.addFeaturesInternal(features); + } + if (collection !== void 0) { + this.bindFeaturesCollection_(collection); + } + } + /** + * Add a single feature to the source. If you want to add a batch of features + * at once, call {@link module:ol/source/Vector~VectorSource#addFeatures #addFeatures()} + * instead. A feature will not be added to the source if feature with + * the same id is already there. The reason for this behavior is to avoid + * feature duplication when using bbox or tile loading strategies. + * Note: this also applies if an {@link module:ol/Collection~Collection} is used for features, + * meaning that if a feature with a duplicate id is added in the collection, it will + * be removed from it right away. + * @param {import("../Feature.js").default} feature Feature to add. + * @api + */ + addFeature(feature) { + this.addFeatureInternal(feature); + this.changed(); + } + /** + * Add a feature without firing a `change` event. + * @param {import("../Feature.js").default} feature Feature. + * @protected + */ + addFeatureInternal(feature) { + const featureKey = getUid(feature); + if (!this.addToIndex_(featureKey, feature)) { + if (this.featuresCollection_) { + this.featuresCollection_.remove(feature); + } + return; + } + this.setupChangeEvents_(featureKey, feature); + const geometry = feature.getGeometry(); + if (geometry) { + const extent = geometry.getExtent(); + if (this.featuresRtree_) { + this.featuresRtree_.insert(extent, feature); + } + } else { + this.nullGeometryFeatures_[featureKey] = feature; + } + this.dispatchEvent( + new VectorSourceEvent(VectorEventType.ADDFEATURE, feature) + ); + } + /** + * @param {string} featureKey Unique identifier for the feature. + * @param {import("../Feature.js").default} feature The feature. + * @private + */ + setupChangeEvents_(featureKey, feature) { + this.featureChangeKeys_[featureKey] = [ + listen(feature, EventType.CHANGE, this.handleFeatureChange_, this), + listen( + feature, + ObjectEventType.PROPERTYCHANGE, + this.handleFeatureChange_, + this + ) + ]; + } + /** + * @param {string} featureKey Unique identifier for the feature. + * @param {import("../Feature.js").default} feature The feature. + * @return {boolean} The feature is "valid", in the sense that it is also a + * candidate for insertion into the Rtree. + * @private + */ + addToIndex_(featureKey, feature) { + let valid = true; + const id = feature.getId(); + if (id !== void 0) { + if (!(id.toString() in this.idIndex_)) { + this.idIndex_[id.toString()] = feature; + } else { + valid = false; + } + } + if (valid) { + assert( + !(featureKey in this.uidIndex_), + "The passed `feature` was already added to the source" + ); + this.uidIndex_[featureKey] = feature; + } + return valid; + } + /** + * Add a batch of features to the source. + * @param {Array>} features Features to add. + * @api + */ + addFeatures(features) { + this.addFeaturesInternal(features); + this.changed(); + } + /** + * Add features without firing a `change` event. + * @param {Array>} features Features. + * @protected + */ + addFeaturesInternal(features) { + const extents = []; + const newFeatures = []; + const geometryFeatures = []; + for (let i = 0, length = features.length; i < length; i++) { + const feature = features[i]; + const featureKey = getUid(feature); + if (this.addToIndex_(featureKey, feature)) { + newFeatures.push(feature); + } + } + for (let i = 0, length = newFeatures.length; i < length; i++) { + const feature = newFeatures[i]; + const featureKey = getUid(feature); + this.setupChangeEvents_(featureKey, feature); + const geometry = feature.getGeometry(); + if (geometry) { + const extent = geometry.getExtent(); + extents.push(extent); + geometryFeatures.push(feature); + } else { + this.nullGeometryFeatures_[featureKey] = feature; + } + } + if (this.featuresRtree_) { + this.featuresRtree_.load(extents, geometryFeatures); + } + if (this.hasListener(VectorEventType.ADDFEATURE)) { + for (let i = 0, length = newFeatures.length; i < length; i++) { + this.dispatchEvent( + new VectorSourceEvent(VectorEventType.ADDFEATURE, newFeatures[i]) + ); + } + } + } + /** + * @param {!Collection>} collection Collection. + * @private + */ + bindFeaturesCollection_(collection) { + let modifyingCollection = false; + this.addEventListener( + VectorEventType.ADDFEATURE, + /** + * @param {VectorSourceEvent} evt The vector source event + */ + function(evt) { + if (!modifyingCollection) { + modifyingCollection = true; + collection.push(evt.feature); + modifyingCollection = false; + } + } + ); + this.addEventListener( + VectorEventType.REMOVEFEATURE, + /** + * @param {VectorSourceEvent} evt The vector source event + */ + function(evt) { + if (!modifyingCollection) { + modifyingCollection = true; + collection.remove(evt.feature); + modifyingCollection = false; + } + } + ); + collection.addEventListener( + CollectionEventType.ADD, + /** + * @param {import("../Collection.js").CollectionEvent>} evt The collection event + */ + (evt) => { + if (!modifyingCollection) { + modifyingCollection = true; + this.addFeature(evt.element); + modifyingCollection = false; + } + } + ); + collection.addEventListener( + CollectionEventType.REMOVE, + /** + * @param {import("../Collection.js").CollectionEvent>} evt The collection event + */ + (evt) => { + if (!modifyingCollection) { + modifyingCollection = true; + this.removeFeature(evt.element); + modifyingCollection = false; + } + } + ); + this.featuresCollection_ = collection; + } + /** + * Remove all features from the source. + * @param {boolean} [fast] Skip dispatching of {@link module:ol/source/Vector.VectorSourceEvent#event:removefeature} events. + * @api + */ + clear(fast) { + if (fast) { + for (const featureId in this.featureChangeKeys_) { + const keys = this.featureChangeKeys_[featureId]; + keys.forEach(unlistenByKey); + } + if (!this.featuresCollection_) { + this.featureChangeKeys_ = {}; + this.idIndex_ = {}; + this.uidIndex_ = {}; + } + } else { + if (this.featuresRtree_) { + const removeAndIgnoreReturn = (feature) => { + this.removeFeatureInternal(feature); + }; + this.featuresRtree_.forEach(removeAndIgnoreReturn); + for (const id in this.nullGeometryFeatures_) { + this.removeFeatureInternal(this.nullGeometryFeatures_[id]); + } + } + } + if (this.featuresCollection_) { + this.featuresCollection_.clear(); + } + if (this.featuresRtree_) { + this.featuresRtree_.clear(); + } + this.nullGeometryFeatures_ = {}; + const clearEvent = new VectorSourceEvent(VectorEventType.CLEAR); + this.dispatchEvent(clearEvent); + this.changed(); + } + /** + * Iterate through all features on the source, calling the provided callback + * with each one. If the callback returns any "truthy" value, iteration will + * stop and the function will return the same value. + * Note: this function only iterate through the feature that have a defined geometry. + * + * @param {function(import("../Feature.js").default): T} callback Called with each feature + * on the source. Return a truthy value to stop iteration. + * @return {T|undefined} The return value from the last call to the callback. + * @template T + * @api + */ + forEachFeature(callback) { + if (this.featuresRtree_) { + return this.featuresRtree_.forEach(callback); + } + if (this.featuresCollection_) { + this.featuresCollection_.forEach(callback); + } + } + /** + * Iterate through all features whose geometries contain the provided + * coordinate, calling the callback with each feature. If the callback returns + * a "truthy" value, iteration will stop and the function will return the same + * value. + * + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @param {function(import("../Feature.js").default): T} callback Called with each feature + * whose goemetry contains the provided coordinate. + * @return {T|undefined} The return value from the last call to the callback. + * @template T + */ + forEachFeatureAtCoordinateDirect(coordinate, callback) { + const extent = [coordinate[0], coordinate[1], coordinate[0], coordinate[1]]; + return this.forEachFeatureInExtent(extent, function(feature) { + const geometry = feature.getGeometry(); + if (geometry.intersectsCoordinate(coordinate)) { + return callback(feature); + } + return void 0; + }); + } + /** + * Iterate through all features whose bounding box intersects the provided + * extent (note that the feature's geometry may not intersect the extent), + * calling the callback with each feature. If the callback returns a "truthy" + * value, iteration will stop and the function will return the same value. + * + * If you are interested in features whose geometry intersects an extent, call + * the {@link module:ol/source/Vector~VectorSource#forEachFeatureIntersectingExtent #forEachFeatureIntersectingExtent()} method instead. + * + * When `useSpatialIndex` is set to false, this method will loop through all + * features, equivalent to {@link module:ol/source/Vector~VectorSource#forEachFeature #forEachFeature()}. + * + * @param {import("../extent.js").Extent} extent Extent. + * @param {function(import("../Feature.js").default): T} callback Called with each feature + * whose bounding box intersects the provided extent. + * @return {T|undefined} The return value from the last call to the callback. + * @template T + * @api + */ + forEachFeatureInExtent(extent, callback) { + if (this.featuresRtree_) { + return this.featuresRtree_.forEachInExtent(extent, callback); + } + if (this.featuresCollection_) { + this.featuresCollection_.forEach(callback); + } + } + /** + * Iterate through all features whose geometry intersects the provided extent, + * calling the callback with each feature. If the callback returns a "truthy" + * value, iteration will stop and the function will return the same value. + * + * If you only want to test for bounding box intersection, call the + * {@link module:ol/source/Vector~VectorSource#forEachFeatureInExtent #forEachFeatureInExtent()} method instead. + * + * @param {import("../extent.js").Extent} extent Extent. + * @param {function(import("../Feature.js").default): T} callback Called with each feature + * whose geometry intersects the provided extent. + * @return {T|undefined} The return value from the last call to the callback. + * @template T + * @api + */ + forEachFeatureIntersectingExtent(extent, callback) { + return this.forEachFeatureInExtent( + extent, + /** + * @param {import("../Feature.js").default} feature Feature. + * @return {T|undefined} The return value from the last call to the callback. + */ + function(feature) { + const geometry = feature.getGeometry(); + if (geometry.intersectsExtent(extent)) { + const result = callback(feature); + if (result) { + return result; + } + } + } + ); + } + /** + * Get the features collection associated with this source. Will be `null` + * unless the source was configured with `useSpatialIndex` set to `false`, or + * with an {@link module:ol/Collection~Collection} as `features`. + * @return {Collection>|null} The collection of features. + * @api + */ + getFeaturesCollection() { + return this.featuresCollection_; + } + /** + * Get a snapshot of the features currently on the source in random order. The returned array + * is a copy, the features are references to the features in the source. + * @return {Array>} Features. + * @api + */ + getFeatures() { + let features; + if (this.featuresCollection_) { + features = this.featuresCollection_.getArray().slice(0); + } else if (this.featuresRtree_) { + features = this.featuresRtree_.getAll(); + if (!isEmpty$1(this.nullGeometryFeatures_)) { + extend$2(features, Object.values(this.nullGeometryFeatures_)); + } + } + return ( + /** @type {Array>} */ + features + ); + } + /** + * Get all features whose geometry intersects the provided coordinate. + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @return {Array>} Features. + * @api + */ + getFeaturesAtCoordinate(coordinate) { + const features = []; + this.forEachFeatureAtCoordinateDirect(coordinate, function(feature) { + features.push(feature); + }); + return features; + } + /** + * Get all features whose bounding box intersects the provided extent. Note that this returns an array of + * all features intersecting the given extent in random order (so it may include + * features whose geometries do not intersect the extent). + * + * When `useSpatialIndex` is set to false, this method will return all + * features. + * + * @param {import("../extent.js").Extent} extent Extent. + * @param {import("../proj/Projection.js").default} [projection] Include features + * where `extent` exceeds the x-axis bounds of `projection` and wraps around the world. + * @return {Array>} Features. + * @api + */ + getFeaturesInExtent(extent, projection) { + if (this.featuresRtree_) { + const multiWorld = projection && projection.canWrapX() && this.getWrapX(); + if (!multiWorld) { + return this.featuresRtree_.getInExtent(extent); + } + const extents = wrapAndSliceX(extent, projection); + return [].concat( + ...extents.map((anExtent) => this.featuresRtree_.getInExtent(anExtent)) + ); + } + if (this.featuresCollection_) { + return this.featuresCollection_.getArray().slice(0); + } + return []; + } + /** + * Get the closest feature to the provided coordinate. + * + * This method is not available when the source is configured with + * `useSpatialIndex` set to `false`. + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @param {function(import("../Feature.js").default):boolean} [filter] Feature filter function. + * The filter function will receive one argument, the {@link module:ol/Feature~Feature feature} + * and it should return a boolean value. By default, no filtering is made. + * @return {import("../Feature.js").default} Closest feature. + * @api + */ + getClosestFeatureToCoordinate(coordinate, filter) { + const x = coordinate[0]; + const y = coordinate[1]; + let closestFeature = null; + const closestPoint = [NaN, NaN]; + let minSquaredDistance = Infinity; + const extent = [-Infinity, -Infinity, Infinity, Infinity]; + filter = filter ? filter : TRUE; + this.featuresRtree_.forEachInExtent( + extent, + /** + * @param {import("../Feature.js").default} feature Feature. + */ + function(feature) { + if (filter(feature)) { + const geometry = feature.getGeometry(); + const previousMinSquaredDistance = minSquaredDistance; + minSquaredDistance = geometry.closestPointXY( + x, + y, + closestPoint, + minSquaredDistance + ); + if (minSquaredDistance < previousMinSquaredDistance) { + closestFeature = feature; + const minDistance = Math.sqrt(minSquaredDistance); + extent[0] = x - minDistance; + extent[1] = y - minDistance; + extent[2] = x + minDistance; + extent[3] = y + minDistance; + } + } + } + ); + return closestFeature; + } + /** + * Get the extent of the features currently in the source. + * + * This method is not available when the source is configured with + * `useSpatialIndex` set to `false`. + * @param {import("../extent.js").Extent} [extent] Destination extent. If provided, no new extent + * will be created. Instead, that extent's coordinates will be overwritten. + * @return {import("../extent.js").Extent} Extent. + * @api + */ + getExtent(extent) { + return this.featuresRtree_.getExtent(extent); + } + /** + * Get a feature by its identifier (the value returned by feature.getId()). + * Note that the index treats string and numeric identifiers as the same. So + * `source.getFeatureById(2)` will return a feature with id `'2'` or `2`. + * + * @param {string|number} id Feature identifier. + * @return {import("../Feature.js").default|null} The feature (or `null` if not found). + * @api + */ + getFeatureById(id) { + const feature = this.idIndex_[id.toString()]; + return feature !== void 0 ? feature : null; + } + /** + * Get a feature by its internal unique identifier (using `getUid`). + * + * @param {string} uid Feature identifier. + * @return {import("../Feature.js").default|null} The feature (or `null` if not found). + */ + getFeatureByUid(uid) { + const feature = this.uidIndex_[uid]; + return feature !== void 0 ? feature : null; + } + /** + * Get the format associated with this source. + * + * @return {import("../format/Feature.js").default|undefined} The feature format. + * @api + */ + getFormat() { + return this.format_; + } + /** + * @return {boolean} The source can have overlapping geometries. + */ + getOverlaps() { + return this.overlaps_; + } + /** + * Get the url associated with this source. + * + * @return {string|import("../featureloader.js").FeatureUrlFunction|undefined} The url. + * @api + */ + getUrl() { + return this.url_; + } + /** + * @param {Event} event Event. + * @private + */ + handleFeatureChange_(event) { + const feature = ( + /** @type {import("../Feature.js").default} */ + event.target + ); + const featureKey = getUid(feature); + const geometry = feature.getGeometry(); + if (!geometry) { + if (!(featureKey in this.nullGeometryFeatures_)) { + if (this.featuresRtree_) { + this.featuresRtree_.remove(feature); + } + this.nullGeometryFeatures_[featureKey] = feature; + } + } else { + const extent = geometry.getExtent(); + if (featureKey in this.nullGeometryFeatures_) { + delete this.nullGeometryFeatures_[featureKey]; + if (this.featuresRtree_) { + this.featuresRtree_.insert(extent, feature); + } + } else { + if (this.featuresRtree_) { + this.featuresRtree_.update(extent, feature); + } + } + } + const id = feature.getId(); + if (id !== void 0) { + const sid = id.toString(); + if (this.idIndex_[sid] !== feature) { + this.removeFromIdIndex_(feature); + this.idIndex_[sid] = feature; + } + } else { + this.removeFromIdIndex_(feature); + this.uidIndex_[featureKey] = feature; + } + this.changed(); + this.dispatchEvent( + new VectorSourceEvent(VectorEventType.CHANGEFEATURE, feature) + ); + } + /** + * Returns true if the feature is contained within the source. + * @param {import("../Feature.js").default} feature Feature. + * @return {boolean} Has feature. + * @api + */ + hasFeature(feature) { + const id = feature.getId(); + if (id !== void 0) { + return id in this.idIndex_; + } + return getUid(feature) in this.uidIndex_; + } + /** + * @return {boolean} Is empty. + */ + isEmpty() { + if (this.featuresRtree_) { + return this.featuresRtree_.isEmpty() && isEmpty$1(this.nullGeometryFeatures_); + } + if (this.featuresCollection_) { + return this.featuresCollection_.getLength() === 0; + } + return true; + } + /** + * @param {import("../extent.js").Extent} extent Extent. + * @param {number} resolution Resolution. + * @param {import("../proj/Projection.js").default} projection Projection. + */ + loadFeatures(extent, resolution, projection) { + const loadedExtentsRtree = this.loadedExtentsRtree_; + const extentsToLoad = this.strategy_(extent, resolution, projection); + for (let i = 0, ii = extentsToLoad.length; i < ii; ++i) { + const extentToLoad = extentsToLoad[i]; + const alreadyLoaded = loadedExtentsRtree.forEachInExtent( + extentToLoad, + /** + * @param {{extent: import("../extent.js").Extent}} object Object. + * @return {boolean} Contains. + */ + function(object) { + return containsExtent(object.extent, extentToLoad); + } + ); + if (!alreadyLoaded) { + ++this.loadingExtentsCount_; + this.dispatchEvent( + new VectorSourceEvent(VectorEventType.FEATURESLOADSTART) + ); + this.loader_.call( + this, + extentToLoad, + resolution, + projection, + (features) => { + --this.loadingExtentsCount_; + this.dispatchEvent( + new VectorSourceEvent( + VectorEventType.FEATURESLOADEND, + void 0, + features + ) + ); + }, + () => { + --this.loadingExtentsCount_; + this.dispatchEvent( + new VectorSourceEvent(VectorEventType.FEATURESLOADERROR) + ); + } + ); + loadedExtentsRtree.insert(extentToLoad, { extent: extentToLoad.slice() }); + } + } + this.loading = this.loader_.length < 4 ? false : this.loadingExtentsCount_ > 0; + } + refresh() { + this.clear(true); + this.loadedExtentsRtree_.clear(); + super.refresh(); + } + /** + * Remove an extent from the list of loaded extents. + * @param {import("../extent.js").Extent} extent Extent. + * @api + */ + removeLoadedExtent(extent) { + const loadedExtentsRtree = this.loadedExtentsRtree_; + let obj; + loadedExtentsRtree.forEachInExtent(extent, function(object) { + if (equals$1(object.extent, extent)) { + obj = object; + return true; + } + }); + if (obj) { + loadedExtentsRtree.remove(obj); + } + } + /** + * Remove a single feature from the source. If you want to remove all features + * at once, use the {@link module:ol/source/Vector~VectorSource#clear #clear()} method + * instead. + * @param {import("../Feature.js").default} feature Feature to remove. + * @api + */ + removeFeature(feature) { + if (!feature) { + return; + } + const featureKey = getUid(feature); + if (featureKey in this.nullGeometryFeatures_) { + delete this.nullGeometryFeatures_[featureKey]; + } else { + if (this.featuresRtree_) { + this.featuresRtree_.remove(feature); + } + } + const result = this.removeFeatureInternal(feature); + if (result) { + this.changed(); + } + } + /** + * Remove feature without firing a `change` event. + * @param {import("../Feature.js").default} feature Feature. + * @return {import("../Feature.js").default|undefined} The removed feature + * (or undefined if the feature was not found). + * @protected + */ + removeFeatureInternal(feature) { + const featureKey = getUid(feature); + const featureChangeKeys = this.featureChangeKeys_[featureKey]; + if (!featureChangeKeys) { + return; + } + featureChangeKeys.forEach(unlistenByKey); + delete this.featureChangeKeys_[featureKey]; + const id = feature.getId(); + if (id !== void 0) { + delete this.idIndex_[id.toString()]; + } + delete this.uidIndex_[featureKey]; + this.dispatchEvent( + new VectorSourceEvent(VectorEventType.REMOVEFEATURE, feature) + ); + return feature; + } + /** + * Remove a feature from the id index. Called internally when the feature id + * may have changed. + * @param {import("../Feature.js").default} feature The feature. + * @return {boolean} Removed the feature from the index. + * @private + */ + removeFromIdIndex_(feature) { + let removed = false; + for (const id in this.idIndex_) { + if (this.idIndex_[id] === feature) { + delete this.idIndex_[id]; + removed = true; + break; + } + } + return removed; + } + /** + * Set the new loader of the source. The next render cycle will use the + * new loader. + * @param {import("../featureloader.js").FeatureLoader} loader The loader to set. + * @api + */ + setLoader(loader) { + this.loader_ = loader; + } + /** + * Points the source to a new url. The next render cycle will use the new url. + * @param {string|import("../featureloader.js").FeatureUrlFunction} url Url. + * @api + */ + setUrl(url) { + assert(this.format_, "`format` must be set when `url` is set"); + this.url_ = url; + this.setLoader(xhr(url, this.format_)); + } +} +const OlSourceVector = VectorSource; +class Tile extends EventTarget { + /** + * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {import("./TileState.js").default} state State. + * @param {Options} [options] Tile options. + */ + constructor(tileCoord, state, options) { + super(); + options = options ? options : {}; + this.tileCoord = tileCoord; + this.state = state; + this.interimTile = null; + this.key = ""; + this.transition_ = options.transition === void 0 ? 250 : options.transition; + this.transitionStarts_ = {}; + this.interpolate = !!options.interpolate; + } + /** + * @protected + */ + changed() { + this.dispatchEvent(EventType.CHANGE); + } + /** + * Called by the tile cache when the tile is removed from the cache due to expiry + */ + release() { + if (this.state === TileState.ERROR) { + this.setState(TileState.EMPTY); + } + } + /** + * @return {string} Key. + */ + getKey() { + return this.key + "/" + this.tileCoord; + } + /** + * Get the interim tile most suitable for rendering using the chain of interim + * tiles. This corresponds to the most recent tile that has been loaded, if no + * such tile exists, the original tile is returned. + * @return {!Tile} Best tile for rendering. + */ + getInterimTile() { + if (!this.interimTile) { + return this; + } + let tile = this.interimTile; + do { + if (tile.getState() == TileState.LOADED) { + this.transition_ = 0; + return tile; + } + tile = tile.interimTile; + } while (tile); + return this; + } + /** + * Goes through the chain of interim tiles and discards sections of the chain + * that are no longer relevant. + */ + refreshInterimChain() { + if (!this.interimTile) { + return; + } + let tile = this.interimTile; + let prev = this; + do { + if (tile.getState() == TileState.LOADED) { + tile.interimTile = null; + break; + } else if (tile.getState() == TileState.LOADING) { + prev = tile; + } else if (tile.getState() == TileState.IDLE) { + prev.interimTile = tile.interimTile; + } else { + prev = tile; + } + tile = prev.interimTile; + } while (tile); + } + /** + * Get the tile coordinate for this tile. + * @return {import("./tilecoord.js").TileCoord} The tile coordinate. + * @api + */ + getTileCoord() { + return this.tileCoord; + } + /** + * @return {import("./TileState.js").default} State. + */ + getState() { + return this.state; + } + /** + * Sets the state of this tile. If you write your own {@link module:ol/Tile~LoadFunction tileLoadFunction} , + * it is important to set the state correctly to {@link module:ol/TileState~ERROR} + * when the tile cannot be loaded. Otherwise the tile cannot be removed from + * the tile queue and will block other requests. + * @param {import("./TileState.js").default} state State. + * @api + */ + setState(state) { + if (this.state !== TileState.ERROR && this.state > state) { + throw new Error("Tile load sequence violation"); + } + this.state = state; + this.changed(); + } + /** + * Load the image or retry if loading previously failed. + * Loading is taken care of by the tile queue, and calling this method is + * only needed for preloading or for reloading in case of an error. + * @abstract + * @api + */ + load() { + abstract(); + } + /** + * Get the alpha value for rendering. + * @param {string} id An id for the renderer. + * @param {number} time The render frame time. + * @return {number} A number between 0 and 1. + */ + getAlpha(id, time) { + if (!this.transition_) { + return 1; + } + let start = this.transitionStarts_[id]; + if (!start) { + start = time; + this.transitionStarts_[id] = start; + } else if (start === -1) { + return 1; + } + const delta = time - start + 1e3 / 60; + if (delta >= this.transition_) { + return 1; + } + return easeIn(delta / this.transition_); + } + /** + * Determine if a tile is in an alpha transition. A tile is considered in + * transition if tile.getAlpha() has not yet been called or has been called + * and returned 1. + * @param {string} id An id for the renderer. + * @return {boolean} The tile is in transition. + */ + inTransition(id) { + if (!this.transition_) { + return false; + } + return this.transitionStarts_[id] !== -1; + } + /** + * Mark a transition as complete. + * @param {string} id An id for the renderer. + */ + endTransition(id) { + if (this.transition_) { + this.transitionStarts_[id] = -1; + } + } +} +const Tile$1 = Tile; +class ImageTile extends Tile$1 { + /** + * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {import("./TileState.js").default} state State. + * @param {string} src Image source URI. + * @param {?string} crossOrigin Cross origin. + * @param {import("./Tile.js").LoadFunction} tileLoadFunction Tile load function. + * @param {import("./Tile.js").Options} [options] Tile options. + */ + constructor(tileCoord, state, src, crossOrigin, tileLoadFunction, options) { + super(tileCoord, state, options); + this.crossOrigin_ = crossOrigin; + this.src_ = src; + this.key = src; + this.image_ = new Image(); + if (crossOrigin !== null) { + this.image_.crossOrigin = crossOrigin; + } + this.unlisten_ = null; + this.tileLoadFunction_ = tileLoadFunction; + } + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image. + * @api + */ + getImage() { + return this.image_; + } + /** + * Sets an HTML image element for this tile (may be a Canvas or preloaded Image). + * @param {HTMLCanvasElement|HTMLImageElement} element Element. + */ + setImage(element) { + this.image_ = element; + this.state = TileState.LOADED; + this.unlistenImage_(); + this.changed(); + } + /** + * Tracks loading or read errors. + * + * @private + */ + handleImageError_() { + this.state = TileState.ERROR; + this.unlistenImage_(); + this.image_ = getBlankImage(); + this.changed(); + } + /** + * Tracks successful image load. + * + * @private + */ + handleImageLoad_() { + const image = ( + /** @type {HTMLImageElement} */ + this.image_ + ); + if (image.naturalWidth && image.naturalHeight) { + this.state = TileState.LOADED; + } else { + this.state = TileState.EMPTY; + } + this.unlistenImage_(); + this.changed(); + } + /** + * Load the image or retry if loading previously failed. + * Loading is taken care of by the tile queue, and calling this method is + * only needed for preloading or for reloading in case of an error. + * + * To retry loading tiles on failed requests, use a custom `tileLoadFunction` + * that checks for error status codes and reloads only when the status code is + * 408, 429, 500, 502, 503 and 504, and only when not too many retries have been + * made already: + * + * ```js + * const retryCodes = [408, 429, 500, 502, 503, 504]; + * const retries = {}; + * source.setTileLoadFunction((tile, src) => { + * const image = tile.getImage(); + * fetch(src) + * .then((response) => { + * if (retryCodes.includes(response.status)) { + * retries[src] = (retries[src] || 0) + 1; + * if (retries[src] <= 3) { + * setTimeout(() => tile.load(), retries[src] * 1000); + * } + * return Promise.reject(); + * } + * return response.blob(); + * }) + * .then((blob) => { + * const imageUrl = URL.createObjectURL(blob); + * image.src = imageUrl; + * setTimeout(() => URL.revokeObjectURL(imageUrl), 5000); + * }) + * .catch(() => tile.setState(3)); // error + * }); + * ``` + * + * @api + */ + load() { + if (this.state == TileState.ERROR) { + this.state = TileState.IDLE; + this.image_ = new Image(); + if (this.crossOrigin_ !== null) { + this.image_.crossOrigin = this.crossOrigin_; + } + } + if (this.state == TileState.IDLE) { + this.state = TileState.LOADING; + this.changed(); + this.tileLoadFunction_(this, this.src_); + this.unlisten_ = listenImage( + this.image_, + this.handleImageLoad_.bind(this), + this.handleImageError_.bind(this) + ); + } + } + /** + * Discards event handlers which listen for load completion or errors. + * + * @private + */ + unlistenImage_() { + if (this.unlisten_) { + this.unlisten_(); + this.unlisten_ = null; + } + } +} +function getBlankImage() { + const ctx = createCanvasContext2D(1, 1); + ctx.fillStyle = "rgba(0,0,0,0)"; + ctx.fillRect(0, 0, 1, 1); + return ctx.canvas; +} +const ImageTile$1 = ImageTile; +const ERROR_THRESHOLD = 0.5; +const MAX_SUBDIVISION = 10; +const MAX_TRIANGLE_WIDTH = 0.25; +class Triangulation { + /** + * @param {import("../proj/Projection.js").default} sourceProj Source projection. + * @param {import("../proj/Projection.js").default} targetProj Target projection. + * @param {import("../extent.js").Extent} targetExtent Target extent to triangulate. + * @param {import("../extent.js").Extent} maxSourceExtent Maximal source extent that can be used. + * @param {number} errorThreshold Acceptable error (in source units). + * @param {?number} destinationResolution The (optional) resolution of the destination. + */ + constructor(sourceProj, targetProj, targetExtent, maxSourceExtent, errorThreshold, destinationResolution) { + this.sourceProj_ = sourceProj; + this.targetProj_ = targetProj; + let transformInvCache = {}; + const transformInv = getTransform(this.targetProj_, this.sourceProj_); + this.transformInv_ = function(c) { + const key = c[0] + "/" + c[1]; + if (!transformInvCache[key]) { + transformInvCache[key] = transformInv(c); + } + return transformInvCache[key]; + }; + this.maxSourceExtent_ = maxSourceExtent; + this.errorThresholdSquared_ = errorThreshold * errorThreshold; + this.triangles_ = []; + this.wrapsXInSource_ = false; + this.canWrapXInSource_ = this.sourceProj_.canWrapX() && !!maxSourceExtent && !!this.sourceProj_.getExtent() && getWidth(maxSourceExtent) >= getWidth(this.sourceProj_.getExtent()); + this.sourceWorldWidth_ = this.sourceProj_.getExtent() ? getWidth(this.sourceProj_.getExtent()) : null; + this.targetWorldWidth_ = this.targetProj_.getExtent() ? getWidth(this.targetProj_.getExtent()) : null; + const destinationTopLeft = getTopLeft(targetExtent); + const destinationTopRight = getTopRight(targetExtent); + const destinationBottomRight = getBottomRight(targetExtent); + const destinationBottomLeft = getBottomLeft(targetExtent); + const sourceTopLeft = this.transformInv_(destinationTopLeft); + const sourceTopRight = this.transformInv_(destinationTopRight); + const sourceBottomRight = this.transformInv_(destinationBottomRight); + const sourceBottomLeft = this.transformInv_(destinationBottomLeft); + const maxSubdivision = MAX_SUBDIVISION + (destinationResolution ? Math.max( + 0, + Math.ceil( + Math.log2( + getArea(targetExtent) / (destinationResolution * destinationResolution * 256 * 256) + ) + ) + ) : 0); + this.addQuad_( + destinationTopLeft, + destinationTopRight, + destinationBottomRight, + destinationBottomLeft, + sourceTopLeft, + sourceTopRight, + sourceBottomRight, + sourceBottomLeft, + maxSubdivision + ); + if (this.wrapsXInSource_) { + let leftBound = Infinity; + this.triangles_.forEach(function(triangle, i, arr) { + leftBound = Math.min( + leftBound, + triangle.source[0][0], + triangle.source[1][0], + triangle.source[2][0] + ); + }); + this.triangles_.forEach((triangle) => { + if (Math.max( + triangle.source[0][0], + triangle.source[1][0], + triangle.source[2][0] + ) - leftBound > this.sourceWorldWidth_ / 2) { + const newTriangle = [ + [triangle.source[0][0], triangle.source[0][1]], + [triangle.source[1][0], triangle.source[1][1]], + [triangle.source[2][0], triangle.source[2][1]] + ]; + if (newTriangle[0][0] - leftBound > this.sourceWorldWidth_ / 2) { + newTriangle[0][0] -= this.sourceWorldWidth_; + } + if (newTriangle[1][0] - leftBound > this.sourceWorldWidth_ / 2) { + newTriangle[1][0] -= this.sourceWorldWidth_; + } + if (newTriangle[2][0] - leftBound > this.sourceWorldWidth_ / 2) { + newTriangle[2][0] -= this.sourceWorldWidth_; + } + const minX = Math.min( + newTriangle[0][0], + newTriangle[1][0], + newTriangle[2][0] + ); + const maxX = Math.max( + newTriangle[0][0], + newTriangle[1][0], + newTriangle[2][0] + ); + if (maxX - minX < this.sourceWorldWidth_ / 2) { + triangle.source = newTriangle; + } + } + }); + } + transformInvCache = {}; + } + /** + * Adds triangle to the triangulation. + * @param {import("../coordinate.js").Coordinate} a The target a coordinate. + * @param {import("../coordinate.js").Coordinate} b The target b coordinate. + * @param {import("../coordinate.js").Coordinate} c The target c coordinate. + * @param {import("../coordinate.js").Coordinate} aSrc The source a coordinate. + * @param {import("../coordinate.js").Coordinate} bSrc The source b coordinate. + * @param {import("../coordinate.js").Coordinate} cSrc The source c coordinate. + * @private + */ + addTriangle_(a, b, c, aSrc, bSrc, cSrc) { + this.triangles_.push({ + source: [aSrc, bSrc, cSrc], + target: [a, b, c] + }); + } + /** + * Adds quad (points in clock-wise order) to the triangulation + * (and reprojects the vertices) if valid. + * Performs quad subdivision if needed to increase precision. + * + * @param {import("../coordinate.js").Coordinate} a The target a coordinate. + * @param {import("../coordinate.js").Coordinate} b The target b coordinate. + * @param {import("../coordinate.js").Coordinate} c The target c coordinate. + * @param {import("../coordinate.js").Coordinate} d The target d coordinate. + * @param {import("../coordinate.js").Coordinate} aSrc The source a coordinate. + * @param {import("../coordinate.js").Coordinate} bSrc The source b coordinate. + * @param {import("../coordinate.js").Coordinate} cSrc The source c coordinate. + * @param {import("../coordinate.js").Coordinate} dSrc The source d coordinate. + * @param {number} maxSubdivision Maximal allowed subdivision of the quad. + * @private + */ + addQuad_(a, b, c, d, aSrc, bSrc, cSrc, dSrc, maxSubdivision) { + const sourceQuadExtent = boundingExtent([aSrc, bSrc, cSrc, dSrc]); + const sourceCoverageX = this.sourceWorldWidth_ ? getWidth(sourceQuadExtent) / this.sourceWorldWidth_ : null; + const sourceWorldWidth = ( + /** @type {number} */ + this.sourceWorldWidth_ + ); + const wrapsX = this.sourceProj_.canWrapX() && sourceCoverageX > 0.5 && sourceCoverageX < 1; + let needsSubdivision = false; + if (maxSubdivision > 0) { + if (this.targetProj_.isGlobal() && this.targetWorldWidth_) { + const targetQuadExtent = boundingExtent([a, b, c, d]); + const targetCoverageX = getWidth(targetQuadExtent) / this.targetWorldWidth_; + needsSubdivision = targetCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision; + } + if (!wrapsX && this.sourceProj_.isGlobal() && sourceCoverageX) { + needsSubdivision = sourceCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision; + } + } + if (!needsSubdivision && this.maxSourceExtent_) { + if (isFinite(sourceQuadExtent[0]) && isFinite(sourceQuadExtent[1]) && isFinite(sourceQuadExtent[2]) && isFinite(sourceQuadExtent[3])) { + if (!intersects$1(sourceQuadExtent, this.maxSourceExtent_)) { + return; + } + } + } + let isNotFinite = 0; + if (!needsSubdivision) { + if (!isFinite(aSrc[0]) || !isFinite(aSrc[1]) || !isFinite(bSrc[0]) || !isFinite(bSrc[1]) || !isFinite(cSrc[0]) || !isFinite(cSrc[1]) || !isFinite(dSrc[0]) || !isFinite(dSrc[1])) { + if (maxSubdivision > 0) { + needsSubdivision = true; + } else { + isNotFinite = (!isFinite(aSrc[0]) || !isFinite(aSrc[1]) ? 8 : 0) + (!isFinite(bSrc[0]) || !isFinite(bSrc[1]) ? 4 : 0) + (!isFinite(cSrc[0]) || !isFinite(cSrc[1]) ? 2 : 0) + (!isFinite(dSrc[0]) || !isFinite(dSrc[1]) ? 1 : 0); + if (isNotFinite != 1 && isNotFinite != 2 && isNotFinite != 4 && isNotFinite != 8) { + return; + } + } + } + } + if (maxSubdivision > 0) { + if (!needsSubdivision) { + const center = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2]; + const centerSrc = this.transformInv_(center); + let dx; + if (wrapsX) { + const centerSrcEstimX = (modulo(aSrc[0], sourceWorldWidth) + modulo(cSrc[0], sourceWorldWidth)) / 2; + dx = centerSrcEstimX - modulo(centerSrc[0], sourceWorldWidth); + } else { + dx = (aSrc[0] + cSrc[0]) / 2 - centerSrc[0]; + } + const dy = (aSrc[1] + cSrc[1]) / 2 - centerSrc[1]; + const centerSrcErrorSquared = dx * dx + dy * dy; + needsSubdivision = centerSrcErrorSquared > this.errorThresholdSquared_; + } + if (needsSubdivision) { + if (Math.abs(a[0] - c[0]) <= Math.abs(a[1] - c[1])) { + const bc = [(b[0] + c[0]) / 2, (b[1] + c[1]) / 2]; + const bcSrc = this.transformInv_(bc); + const da = [(d[0] + a[0]) / 2, (d[1] + a[1]) / 2]; + const daSrc = this.transformInv_(da); + this.addQuad_( + a, + b, + bc, + da, + aSrc, + bSrc, + bcSrc, + daSrc, + maxSubdivision - 1 + ); + this.addQuad_( + da, + bc, + c, + d, + daSrc, + bcSrc, + cSrc, + dSrc, + maxSubdivision - 1 + ); + } else { + const ab = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + const abSrc = this.transformInv_(ab); + const cd = [(c[0] + d[0]) / 2, (c[1] + d[1]) / 2]; + const cdSrc = this.transformInv_(cd); + this.addQuad_( + a, + ab, + cd, + d, + aSrc, + abSrc, + cdSrc, + dSrc, + maxSubdivision - 1 + ); + this.addQuad_( + ab, + b, + c, + cd, + abSrc, + bSrc, + cSrc, + cdSrc, + maxSubdivision - 1 + ); + } + return; + } + } + if (wrapsX) { + if (!this.canWrapXInSource_) { + return; + } + this.wrapsXInSource_ = true; + } + if ((isNotFinite & 11) == 0) { + this.addTriangle_(a, c, d, aSrc, cSrc, dSrc); + } + if ((isNotFinite & 14) == 0) { + this.addTriangle_(a, c, b, aSrc, cSrc, bSrc); + } + if (isNotFinite) { + if ((isNotFinite & 13) == 0) { + this.addTriangle_(b, d, a, bSrc, dSrc, aSrc); + } + if ((isNotFinite & 7) == 0) { + this.addTriangle_(b, d, c, bSrc, dSrc, cSrc); + } + } + } + /** + * Calculates extent of the `source` coordinates from all the triangles. + * + * @return {import("../extent.js").Extent} Calculated extent. + */ + calculateSourceExtent() { + const extent = createEmpty(); + this.triangles_.forEach(function(triangle, i, arr) { + const src = triangle.source; + extendCoordinate(extent, src[0]); + extendCoordinate(extent, src[1]); + extendCoordinate(extent, src[2]); + }); + return extent; + } + /** + * @return {Array} Array of the calculated triangles. + */ + getTriangles() { + return this.triangles_; + } +} +const Triangulation$1 = Triangulation; +let brokenDiagonalRendering_; +const canvasPool$1 = []; +function drawTestTriangle(ctx, u1, v1, u2, v2) { + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(u1, v1); + ctx.lineTo(u2, v2); + ctx.closePath(); + ctx.save(); + ctx.clip(); + ctx.fillRect(0, 0, Math.max(u1, u2) + 1, Math.max(v1, v2)); + ctx.restore(); +} +function verifyBrokenDiagonalRendering(data, offset) { + return Math.abs(data[offset * 4] - 210) > 2 || Math.abs(data[offset * 4 + 3] - 0.75 * 255) > 2; +} +function isBrokenDiagonalRendering() { + if (brokenDiagonalRendering_ === void 0) { + const ctx = createCanvasContext2D(6, 6, canvasPool$1); + ctx.globalCompositeOperation = "lighter"; + ctx.fillStyle = "rgba(210, 0, 0, 0.75)"; + drawTestTriangle(ctx, 4, 5, 4, 0); + drawTestTriangle(ctx, 4, 5, 0, 5); + const data = ctx.getImageData(0, 0, 3, 3).data; + brokenDiagonalRendering_ = verifyBrokenDiagonalRendering(data, 0) || verifyBrokenDiagonalRendering(data, 4) || verifyBrokenDiagonalRendering(data, 8); + releaseCanvas(ctx); + canvasPool$1.push(ctx.canvas); + } + return brokenDiagonalRendering_; +} +function calculateSourceResolution(sourceProj, targetProj, targetCenter, targetResolution) { + const sourceCenter = transform(targetCenter, targetProj, sourceProj); + let sourceResolution = getPointResolution( + targetProj, + targetResolution, + targetCenter + ); + const targetMetersPerUnit = targetProj.getMetersPerUnit(); + if (targetMetersPerUnit !== void 0) { + sourceResolution *= targetMetersPerUnit; + } + const sourceMetersPerUnit = sourceProj.getMetersPerUnit(); + if (sourceMetersPerUnit !== void 0) { + sourceResolution /= sourceMetersPerUnit; + } + const sourceExtent = sourceProj.getExtent(); + if (!sourceExtent || containsCoordinate(sourceExtent, sourceCenter)) { + const compensationFactor = getPointResolution(sourceProj, sourceResolution, sourceCenter) / sourceResolution; + if (isFinite(compensationFactor) && compensationFactor > 0) { + sourceResolution /= compensationFactor; + } + } + return sourceResolution; +} +function calculateSourceExtentResolution(sourceProj, targetProj, targetExtent, targetResolution) { + const targetCenter = getCenter(targetExtent); + let sourceResolution = calculateSourceResolution( + sourceProj, + targetProj, + targetCenter, + targetResolution + ); + if (!isFinite(sourceResolution) || sourceResolution <= 0) { + forEachCorner(targetExtent, function(corner) { + sourceResolution = calculateSourceResolution( + sourceProj, + targetProj, + corner, + targetResolution + ); + return isFinite(sourceResolution) && sourceResolution > 0; + }); + } + return sourceResolution; +} +function render(width, height, pixelRatio, sourceResolution, sourceExtent, targetResolution, targetExtent, triangulation, sources, gutter, renderEdges, interpolate) { + const context = createCanvasContext2D( + Math.round(pixelRatio * width), + Math.round(pixelRatio * height), + canvasPool$1 + ); + if (!interpolate) { + context.imageSmoothingEnabled = false; + } + if (sources.length === 0) { + return context.canvas; + } + context.scale(pixelRatio, pixelRatio); + function pixelRound(value) { + return Math.round(value * pixelRatio) / pixelRatio; + } + context.globalCompositeOperation = "lighter"; + const sourceDataExtent = createEmpty(); + sources.forEach(function(src, i, arr) { + extend$1(sourceDataExtent, src.extent); + }); + const canvasWidthInUnits = getWidth(sourceDataExtent); + const canvasHeightInUnits = getHeight(sourceDataExtent); + const stitchContext = createCanvasContext2D( + Math.round(pixelRatio * canvasWidthInUnits / sourceResolution), + Math.round(pixelRatio * canvasHeightInUnits / sourceResolution), + canvasPool$1 + ); + if (!interpolate) { + stitchContext.imageSmoothingEnabled = false; + } + const stitchScale = pixelRatio / sourceResolution; + sources.forEach(function(src, i, arr) { + const xPos = src.extent[0] - sourceDataExtent[0]; + const yPos = -(src.extent[3] - sourceDataExtent[3]); + const srcWidth = getWidth(src.extent); + const srcHeight = getHeight(src.extent); + if (src.image.width > 0 && src.image.height > 0) { + stitchContext.drawImage( + src.image, + gutter, + gutter, + src.image.width - 2 * gutter, + src.image.height - 2 * gutter, + xPos * stitchScale, + yPos * stitchScale, + srcWidth * stitchScale, + srcHeight * stitchScale + ); + } + }); + const targetTopLeft = getTopLeft(targetExtent); + triangulation.getTriangles().forEach(function(triangle, i, arr) { + const source = triangle.source; + const target = triangle.target; + let x0 = source[0][0], y0 = source[0][1]; + let x1 = source[1][0], y1 = source[1][1]; + let x2 = source[2][0], y2 = source[2][1]; + const u0 = pixelRound((target[0][0] - targetTopLeft[0]) / targetResolution); + const v0 = pixelRound( + -(target[0][1] - targetTopLeft[1]) / targetResolution + ); + const u1 = pixelRound((target[1][0] - targetTopLeft[0]) / targetResolution); + const v1 = pixelRound( + -(target[1][1] - targetTopLeft[1]) / targetResolution + ); + const u2 = pixelRound((target[2][0] - targetTopLeft[0]) / targetResolution); + const v2 = pixelRound( + -(target[2][1] - targetTopLeft[1]) / targetResolution + ); + const sourceNumericalShiftX = x0; + const sourceNumericalShiftY = y0; + x0 = 0; + y0 = 0; + x1 -= sourceNumericalShiftX; + y1 -= sourceNumericalShiftY; + x2 -= sourceNumericalShiftX; + y2 -= sourceNumericalShiftY; + const augmentedMatrix = [ + [x1, y1, 0, 0, u1 - u0], + [x2, y2, 0, 0, u2 - u0], + [0, 0, x1, y1, v1 - v0], + [0, 0, x2, y2, v2 - v0] + ]; + const affineCoefs = solveLinearSystem(augmentedMatrix); + if (!affineCoefs) { + return; + } + context.save(); + context.beginPath(); + if (isBrokenDiagonalRendering() || !interpolate) { + context.moveTo(u1, v1); + const steps = 4; + const ud = u0 - u1; + const vd = v0 - v1; + for (let step = 0; step < steps; step++) { + context.lineTo( + u1 + pixelRound((step + 1) * ud / steps), + v1 + pixelRound(step * vd / (steps - 1)) + ); + if (step != steps - 1) { + context.lineTo( + u1 + pixelRound((step + 1) * ud / steps), + v1 + pixelRound((step + 1) * vd / (steps - 1)) + ); + } + } + context.lineTo(u2, v2); + } else { + context.moveTo(u1, v1); + context.lineTo(u0, v0); + context.lineTo(u2, v2); + } + context.clip(); + context.transform( + affineCoefs[0], + affineCoefs[2], + affineCoefs[1], + affineCoefs[3], + u0, + v0 + ); + context.translate( + sourceDataExtent[0] - sourceNumericalShiftX, + sourceDataExtent[3] - sourceNumericalShiftY + ); + context.scale( + sourceResolution / pixelRatio, + -sourceResolution / pixelRatio + ); + context.drawImage(stitchContext.canvas, 0, 0); + context.restore(); + }); + releaseCanvas(stitchContext); + canvasPool$1.push(stitchContext.canvas); + if (renderEdges) { + context.save(); + context.globalCompositeOperation = "source-over"; + context.strokeStyle = "black"; + context.lineWidth = 1; + triangulation.getTriangles().forEach(function(triangle, i, arr) { + const target = triangle.target; + const u0 = (target[0][0] - targetTopLeft[0]) / targetResolution; + const v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution; + const u1 = (target[1][0] - targetTopLeft[0]) / targetResolution; + const v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution; + const u2 = (target[2][0] - targetTopLeft[0]) / targetResolution; + const v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution; + context.beginPath(); + context.moveTo(u1, v1); + context.lineTo(u0, v0); + context.lineTo(u2, v2); + context.closePath(); + context.stroke(); + }); + context.restore(); + } + return context.canvas; +} +class ReprojTile extends Tile$1 { + /** + * @param {import("../proj/Projection.js").default} sourceProj Source projection. + * @param {import("../tilegrid/TileGrid.js").default} sourceTileGrid Source tile grid. + * @param {import("../proj/Projection.js").default} targetProj Target projection. + * @param {import("../tilegrid/TileGrid.js").default} targetTileGrid Target tile grid. + * @param {import("../tilecoord.js").TileCoord} tileCoord Coordinate of the tile. + * @param {import("../tilecoord.js").TileCoord} wrappedTileCoord Coordinate of the tile wrapped in X. + * @param {number} pixelRatio Pixel ratio. + * @param {number} gutter Gutter of the source tiles. + * @param {FunctionType} getTileFunction + * Function returning source tiles (z, x, y, pixelRatio). + * @param {number} [errorThreshold] Acceptable reprojection error (in px). + * @param {boolean} [renderEdges] Render reprojection edges. + * @param {boolean} [interpolate] Use linear interpolation when resampling. + */ + constructor(sourceProj, sourceTileGrid, targetProj, targetTileGrid, tileCoord, wrappedTileCoord, pixelRatio, gutter, getTileFunction, errorThreshold, renderEdges, interpolate) { + super(tileCoord, TileState.IDLE, { interpolate: !!interpolate }); + this.renderEdges_ = renderEdges !== void 0 ? renderEdges : false; + this.pixelRatio_ = pixelRatio; + this.gutter_ = gutter; + this.canvas_ = null; + this.sourceTileGrid_ = sourceTileGrid; + this.targetTileGrid_ = targetTileGrid; + this.wrappedTileCoord_ = wrappedTileCoord ? wrappedTileCoord : tileCoord; + this.sourceTiles_ = []; + this.sourcesListenerKeys_ = null; + this.sourceZ_ = 0; + const targetExtent = targetTileGrid.getTileCoordExtent( + this.wrappedTileCoord_ + ); + const maxTargetExtent = this.targetTileGrid_.getExtent(); + let maxSourceExtent = this.sourceTileGrid_.getExtent(); + const limitedTargetExtent = maxTargetExtent ? getIntersection(targetExtent, maxTargetExtent) : targetExtent; + if (getArea(limitedTargetExtent) === 0) { + this.state = TileState.EMPTY; + return; + } + const sourceProjExtent = sourceProj.getExtent(); + if (sourceProjExtent) { + if (!maxSourceExtent) { + maxSourceExtent = sourceProjExtent; + } else { + maxSourceExtent = getIntersection(maxSourceExtent, sourceProjExtent); + } + } + const targetResolution = targetTileGrid.getResolution( + this.wrappedTileCoord_[0] + ); + const sourceResolution = calculateSourceExtentResolution( + sourceProj, + targetProj, + limitedTargetExtent, + targetResolution + ); + if (!isFinite(sourceResolution) || sourceResolution <= 0) { + this.state = TileState.EMPTY; + return; + } + const errorThresholdInPixels = errorThreshold !== void 0 ? errorThreshold : ERROR_THRESHOLD; + this.triangulation_ = new Triangulation$1( + sourceProj, + targetProj, + limitedTargetExtent, + maxSourceExtent, + sourceResolution * errorThresholdInPixels, + targetResolution + ); + if (this.triangulation_.getTriangles().length === 0) { + this.state = TileState.EMPTY; + return; + } + this.sourceZ_ = sourceTileGrid.getZForResolution(sourceResolution); + let sourceExtent = this.triangulation_.calculateSourceExtent(); + if (maxSourceExtent) { + if (sourceProj.canWrapX()) { + sourceExtent[1] = clamp( + sourceExtent[1], + maxSourceExtent[1], + maxSourceExtent[3] + ); + sourceExtent[3] = clamp( + sourceExtent[3], + maxSourceExtent[1], + maxSourceExtent[3] + ); + } else { + sourceExtent = getIntersection(sourceExtent, maxSourceExtent); + } + } + if (!getArea(sourceExtent)) { + this.state = TileState.EMPTY; + } else { + const sourceRange = sourceTileGrid.getTileRangeForExtentAndZ( + sourceExtent, + this.sourceZ_ + ); + for (let srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) { + for (let srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) { + const tile = getTileFunction(this.sourceZ_, srcX, srcY, pixelRatio); + if (tile) { + this.sourceTiles_.push(tile); + } + } + } + if (this.sourceTiles_.length === 0) { + this.state = TileState.EMPTY; + } + } + } + /** + * Get the HTML Canvas element for this tile. + * @return {HTMLCanvasElement} Canvas. + */ + getImage() { + return this.canvas_; + } + /** + * @private + */ + reproject_() { + const sources = []; + this.sourceTiles_.forEach((tile) => { + if (tile && tile.getState() == TileState.LOADED) { + sources.push({ + extent: this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord), + image: tile.getImage() + }); + } + }); + this.sourceTiles_.length = 0; + if (sources.length === 0) { + this.state = TileState.ERROR; + } else { + const z = this.wrappedTileCoord_[0]; + const size = this.targetTileGrid_.getTileSize(z); + const width = typeof size === "number" ? size : size[0]; + const height = typeof size === "number" ? size : size[1]; + const targetResolution = this.targetTileGrid_.getResolution(z); + const sourceResolution = this.sourceTileGrid_.getResolution( + this.sourceZ_ + ); + const targetExtent = this.targetTileGrid_.getTileCoordExtent( + this.wrappedTileCoord_ + ); + this.canvas_ = render( + width, + height, + this.pixelRatio_, + sourceResolution, + this.sourceTileGrid_.getExtent(), + targetResolution, + targetExtent, + this.triangulation_, + sources, + this.gutter_, + this.renderEdges_, + this.interpolate + ); + this.state = TileState.LOADED; + } + this.changed(); + } + /** + * Load not yet loaded URI. + */ + load() { + if (this.state == TileState.IDLE) { + this.state = TileState.LOADING; + this.changed(); + let leftToLoad = 0; + this.sourcesListenerKeys_ = []; + this.sourceTiles_.forEach((tile) => { + const state = tile.getState(); + if (state == TileState.IDLE || state == TileState.LOADING) { + leftToLoad++; + const sourceListenKey = listen( + tile, + EventType.CHANGE, + function(e) { + const state2 = tile.getState(); + if (state2 == TileState.LOADED || state2 == TileState.ERROR || state2 == TileState.EMPTY) { + unlistenByKey(sourceListenKey); + leftToLoad--; + if (leftToLoad === 0) { + this.unlistenSources_(); + this.reproject_(); + } + } + }, + this + ); + this.sourcesListenerKeys_.push(sourceListenKey); + } + }); + if (leftToLoad === 0) { + setTimeout(this.reproject_.bind(this), 0); + } else { + this.sourceTiles_.forEach(function(tile, i, arr) { + const state = tile.getState(); + if (state == TileState.IDLE) { + tile.load(); + } + }); + } + } + } + /** + * @private + */ + unlistenSources_() { + this.sourcesListenerKeys_.forEach(unlistenByKey); + this.sourcesListenerKeys_ = null; + } + /** + * Remove from the cache due to expiry + */ + release() { + if (this.canvas_) { + releaseCanvas(this.canvas_.getContext("2d")); + canvasPool$1.push(this.canvas_); + this.canvas_ = null; + } + super.release(); + } +} +const ReprojTile$1 = ReprojTile; +class LRUCache { + /** + * @param {number} [highWaterMark] High water mark. + */ + constructor(highWaterMark) { + this.highWaterMark = highWaterMark !== void 0 ? highWaterMark : 2048; + this.count_ = 0; + this.entries_ = {}; + this.oldest_ = null; + this.newest_ = null; + } + /** + * @return {boolean} Can expire cache. + */ + canExpireCache() { + return this.highWaterMark > 0 && this.getCount() > this.highWaterMark; + } + /** + * Expire the cache. + * @param {!Object} [keep] Keys to keep. To be implemented by subclasses. + */ + expireCache(keep) { + while (this.canExpireCache()) { + this.pop(); + } + } + /** + * FIXME empty description for jsdoc + */ + clear() { + this.count_ = 0; + this.entries_ = {}; + this.oldest_ = null; + this.newest_ = null; + } + /** + * @param {string} key Key. + * @return {boolean} Contains key. + */ + containsKey(key) { + return this.entries_.hasOwnProperty(key); + } + /** + * @param {function(T, string, LRUCache): ?} f The function + * to call for every entry from the oldest to the newer. This function takes + * 3 arguments (the entry value, the entry key and the LRUCache object). + * The return value is ignored. + */ + forEach(f) { + let entry = this.oldest_; + while (entry) { + f(entry.value_, entry.key_, this); + entry = entry.newer; + } + } + /** + * @param {string} key Key. + * @param {*} [options] Options (reserved for subclasses). + * @return {T} Value. + */ + get(key, options) { + const entry = this.entries_[key]; + assert( + entry !== void 0, + "Tried to get a value for a key that does not exist in the cache" + ); + if (entry === this.newest_) { + return entry.value_; + } + if (entry === this.oldest_) { + this.oldest_ = /** @type {Entry} */ + this.oldest_.newer; + this.oldest_.older = null; + } else { + entry.newer.older = entry.older; + entry.older.newer = entry.newer; + } + entry.newer = null; + entry.older = this.newest_; + this.newest_.newer = entry; + this.newest_ = entry; + return entry.value_; + } + /** + * Remove an entry from the cache. + * @param {string} key The entry key. + * @return {T} The removed entry. + */ + remove(key) { + const entry = this.entries_[key]; + assert( + entry !== void 0, + "Tried to get a value for a key that does not exist in the cache" + ); + if (entry === this.newest_) { + this.newest_ = /** @type {Entry} */ + entry.older; + if (this.newest_) { + this.newest_.newer = null; + } + } else if (entry === this.oldest_) { + this.oldest_ = /** @type {Entry} */ + entry.newer; + if (this.oldest_) { + this.oldest_.older = null; + } + } else { + entry.newer.older = entry.older; + entry.older.newer = entry.newer; + } + delete this.entries_[key]; + --this.count_; + return entry.value_; + } + /** + * @return {number} Count. + */ + getCount() { + return this.count_; + } + /** + * @return {Array} Keys. + */ + getKeys() { + const keys = new Array(this.count_); + let i = 0; + let entry; + for (entry = this.newest_; entry; entry = entry.older) { + keys[i++] = entry.key_; + } + return keys; + } + /** + * @return {Array} Values. + */ + getValues() { + const values = new Array(this.count_); + let i = 0; + let entry; + for (entry = this.newest_; entry; entry = entry.older) { + values[i++] = entry.value_; + } + return values; + } + /** + * @return {T} Last value. + */ + peekLast() { + return this.oldest_.value_; + } + /** + * @return {string} Last key. + */ + peekLastKey() { + return this.oldest_.key_; + } + /** + * Get the key of the newest item in the cache. Throws if the cache is empty. + * @return {string} The newest key. + */ + peekFirstKey() { + return this.newest_.key_; + } + /** + * Return an entry without updating least recently used time. + * @param {string} key Key. + * @return {T} Value. + */ + peek(key) { + if (!this.containsKey(key)) { + return void 0; + } + return this.entries_[key].value_; + } + /** + * @return {T} value Value. + */ + pop() { + const entry = this.oldest_; + delete this.entries_[entry.key_]; + if (entry.newer) { + entry.newer.older = null; + } + this.oldest_ = /** @type {Entry} */ + entry.newer; + if (!this.oldest_) { + this.newest_ = null; + } + --this.count_; + return entry.value_; + } + /** + * @param {string} key Key. + * @param {T} value Value. + */ + replace(key, value) { + this.get(key); + this.entries_[key].value_ = value; + } + /** + * @param {string} key Key. + * @param {T} value Value. + */ + set(key, value) { + assert( + !(key in this.entries_), + "Tried to set a value for a key that is used already" + ); + const entry = { + key_: key, + newer: null, + older: this.newest_, + value_: value + }; + if (!this.newest_) { + this.oldest_ = entry; + } else { + this.newest_.newer = entry; + } + this.newest_ = entry; + this.entries_[key] = entry; + ++this.count_; + } + /** + * Set a maximum number of entries for the cache. + * @param {number} size Cache size. + * @api + */ + setSize(size) { + this.highWaterMark = size; + } +} +const LRUCache$1 = LRUCache; +function createOrUpdate$1(z, x, y, tileCoord) { + if (tileCoord !== void 0) { + tileCoord[0] = z; + tileCoord[1] = x; + tileCoord[2] = y; + return tileCoord; + } + return [z, x, y]; +} +function getKeyZXY(z, x, y) { + return z + "/" + x + "/" + y; +} +function getKey(tileCoord) { + return getKeyZXY(tileCoord[0], tileCoord[1], tileCoord[2]); +} +function fromKey(key) { + return key.split("/").map(Number); +} +function hash(tileCoord) { + return (tileCoord[1] << tileCoord[0]) + tileCoord[2]; +} +function withinExtentAndZ(tileCoord, tileGrid) { + const z = tileCoord[0]; + const x = tileCoord[1]; + const y = tileCoord[2]; + if (tileGrid.getMinZoom() > z || z > tileGrid.getMaxZoom()) { + return false; + } + const tileRange = tileGrid.getFullTileRange(z); + if (!tileRange) { + return true; + } + return tileRange.containsXY(x, y); +} +class TileCache extends LRUCache$1 { + clear() { + while (this.getCount() > 0) { + this.pop().release(); + } + super.clear(); + } + /** + * @param {!Object} usedTiles Used tiles. + */ + expireCache(usedTiles) { + while (this.canExpireCache()) { + const tile = this.peekLast(); + if (tile.getKey() in usedTiles) { + break; + } else { + this.pop().release(); + } + } + } + /** + * Prune all tiles from the cache that don't have the same z as the newest tile. + */ + pruneExceptNewestZ() { + if (this.getCount() === 0) { + return; + } + const key = this.peekFirstKey(); + const tileCoord = fromKey(key); + const z = tileCoord[0]; + this.forEach((tile) => { + if (tile.tileCoord[0] !== z) { + this.remove(getKey(tile.tileCoord)); + tile.release(); + } + }); + } +} +const TileCache$1 = TileCache; +const TileEventType = { + /** + * Triggered when a tile starts loading. + * @event module:ol/source/Tile.TileSourceEvent#tileloadstart + * @api + */ + TILELOADSTART: "tileloadstart", + /** + * Triggered when a tile finishes loading, either when its data is loaded, + * or when loading was aborted because the tile is no longer needed. + * @event module:ol/source/Tile.TileSourceEvent#tileloadend + * @api + */ + TILELOADEND: "tileloadend", + /** + * Triggered if tile loading results in an error. Note that this is not the + * right place to re-fetch tiles. See {@link module:ol/ImageTile~ImageTile#load} + * for details. + * @event module:ol/source/Tile.TileSourceEvent#tileloaderror + * @api + */ + TILELOADERROR: "tileloaderror" +}; +class TileRange { + /** + * @param {number} minX Minimum X. + * @param {number} maxX Maximum X. + * @param {number} minY Minimum Y. + * @param {number} maxY Maximum Y. + */ + constructor(minX, maxX, minY, maxY) { + this.minX = minX; + this.maxX = maxX; + this.minY = minY; + this.maxY = maxY; + } + /** + * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @return {boolean} Contains tile coordinate. + */ + contains(tileCoord) { + return this.containsXY(tileCoord[1], tileCoord[2]); + } + /** + * @param {TileRange} tileRange Tile range. + * @return {boolean} Contains. + */ + containsTileRange(tileRange) { + return this.minX <= tileRange.minX && tileRange.maxX <= this.maxX && this.minY <= tileRange.minY && tileRange.maxY <= this.maxY; + } + /** + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + * @return {boolean} Contains coordinate. + */ + containsXY(x, y) { + return this.minX <= x && x <= this.maxX && this.minY <= y && y <= this.maxY; + } + /** + * @param {TileRange} tileRange Tile range. + * @return {boolean} Equals. + */ + equals(tileRange) { + return this.minX == tileRange.minX && this.minY == tileRange.minY && this.maxX == tileRange.maxX && this.maxY == tileRange.maxY; + } + /** + * @param {TileRange} tileRange Tile range. + */ + extend(tileRange) { + if (tileRange.minX < this.minX) { + this.minX = tileRange.minX; + } + if (tileRange.maxX > this.maxX) { + this.maxX = tileRange.maxX; + } + if (tileRange.minY < this.minY) { + this.minY = tileRange.minY; + } + if (tileRange.maxY > this.maxY) { + this.maxY = tileRange.maxY; + } + } + /** + * @return {number} Height. + */ + getHeight() { + return this.maxY - this.minY + 1; + } + /** + * @return {import("./size.js").Size} Size. + */ + getSize() { + return [this.getWidth(), this.getHeight()]; + } + /** + * @return {number} Width. + */ + getWidth() { + return this.maxX - this.minX + 1; + } + /** + * @param {TileRange} tileRange Tile range. + * @return {boolean} Intersects. + */ + intersects(tileRange) { + return this.minX <= tileRange.maxX && this.maxX >= tileRange.minX && this.minY <= tileRange.maxY && this.maxY >= tileRange.minY; + } +} +function createOrUpdate(minX, maxX, minY, maxY, tileRange) { + if (tileRange !== void 0) { + tileRange.minX = minX; + tileRange.maxX = maxX; + tileRange.minY = minY; + tileRange.maxY = maxY; + return tileRange; + } + return new TileRange(minX, maxX, minY, maxY); +} +const TileRange$1 = TileRange; +const tmpTileCoord = [0, 0, 0]; +const DECIMALS = 5; +class TileGrid { + /** + * @param {Options} options Tile grid options. + */ + constructor(options) { + this.minZoom = options.minZoom !== void 0 ? options.minZoom : 0; + this.resolutions_ = options.resolutions; + assert( + isSorted( + this.resolutions_, + function(a, b) { + return b - a; + }, + true + ), + "`resolutions` must be sorted in descending order" + ); + let zoomFactor; + if (!options.origins) { + for (let i = 0, ii = this.resolutions_.length - 1; i < ii; ++i) { + if (!zoomFactor) { + zoomFactor = this.resolutions_[i] / this.resolutions_[i + 1]; + } else { + if (this.resolutions_[i] / this.resolutions_[i + 1] !== zoomFactor) { + zoomFactor = void 0; + break; + } + } + } + } + this.zoomFactor_ = zoomFactor; + this.maxZoom = this.resolutions_.length - 1; + this.origin_ = options.origin !== void 0 ? options.origin : null; + this.origins_ = null; + if (options.origins !== void 0) { + this.origins_ = options.origins; + assert( + this.origins_.length == this.resolutions_.length, + "Number of `origins` and `resolutions` must be equal" + ); + } + const extent = options.extent; + if (extent !== void 0 && !this.origin_ && !this.origins_) { + this.origin_ = getTopLeft(extent); + } + assert( + !this.origin_ && this.origins_ || this.origin_ && !this.origins_, + "Either `origin` or `origins` must be configured, never both" + ); + this.tileSizes_ = null; + if (options.tileSizes !== void 0) { + this.tileSizes_ = options.tileSizes; + assert( + this.tileSizes_.length == this.resolutions_.length, + "Number of `tileSizes` and `resolutions` must be equal" + ); + } + this.tileSize_ = options.tileSize !== void 0 ? options.tileSize : !this.tileSizes_ ? DEFAULT_TILE_SIZE : null; + assert( + !this.tileSize_ && this.tileSizes_ || this.tileSize_ && !this.tileSizes_, + "Either `tileSize` or `tileSizes` must be configured, never both" + ); + this.extent_ = extent !== void 0 ? extent : null; + this.fullTileRanges_ = null; + this.tmpSize_ = [0, 0]; + this.tmpExtent_ = [0, 0, 0, 0]; + if (options.sizes !== void 0) { + this.fullTileRanges_ = options.sizes.map(function(size, z) { + const tileRange = new TileRange$1( + Math.min(0, size[0]), + Math.max(size[0] - 1, -1), + Math.min(0, size[1]), + Math.max(size[1] - 1, -1) + ); + if (extent) { + const restrictedTileRange = this.getTileRangeForExtentAndZ(extent, z); + tileRange.minX = Math.max(restrictedTileRange.minX, tileRange.minX); + tileRange.maxX = Math.min(restrictedTileRange.maxX, tileRange.maxX); + tileRange.minY = Math.max(restrictedTileRange.minY, tileRange.minY); + tileRange.maxY = Math.min(restrictedTileRange.maxY, tileRange.maxY); + } + return tileRange; + }, this); + } else if (extent) { + this.calculateTileRanges_(extent); + } + } + /** + * Call a function with each tile coordinate for a given extent and zoom level. + * + * @param {import("../extent.js").Extent} extent Extent. + * @param {number} zoom Integer zoom level. + * @param {function(import("../tilecoord.js").TileCoord): void} callback Function called with each tile coordinate. + * @api + */ + forEachTileCoord(extent, zoom, callback) { + const tileRange = this.getTileRangeForExtentAndZ(extent, zoom); + for (let i = tileRange.minX, ii = tileRange.maxX; i <= ii; ++i) { + for (let j = tileRange.minY, jj = tileRange.maxY; j <= jj; ++j) { + callback([zoom, i, j]); + } + } + } + /** + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {function(number, import("../TileRange.js").default): boolean} callback Callback. + * @param {import("../TileRange.js").default} [tempTileRange] Temporary import("../TileRange.js").default object. + * @param {import("../extent.js").Extent} [tempExtent] Temporary import("../extent.js").Extent object. + * @return {boolean} Callback succeeded. + */ + forEachTileCoordParentTileRange(tileCoord, callback, tempTileRange, tempExtent) { + let tileRange, x, y; + let tileCoordExtent = null; + let z = tileCoord[0] - 1; + if (this.zoomFactor_ === 2) { + x = tileCoord[1]; + y = tileCoord[2]; + } else { + tileCoordExtent = this.getTileCoordExtent(tileCoord, tempExtent); + } + while (z >= this.minZoom) { + if (this.zoomFactor_ === 2) { + x = Math.floor(x / 2); + y = Math.floor(y / 2); + tileRange = createOrUpdate(x, x, y, y, tempTileRange); + } else { + tileRange = this.getTileRangeForExtentAndZ( + tileCoordExtent, + z, + tempTileRange + ); + } + if (callback(z, tileRange)) { + return true; + } + --z; + } + return false; + } + /** + * Get the extent for this tile grid, if it was configured. + * @return {import("../extent.js").Extent} Extent. + * @api + */ + getExtent() { + return this.extent_; + } + /** + * Get the maximum zoom level for the grid. + * @return {number} Max zoom. + * @api + */ + getMaxZoom() { + return this.maxZoom; + } + /** + * Get the minimum zoom level for the grid. + * @return {number} Min zoom. + * @api + */ + getMinZoom() { + return this.minZoom; + } + /** + * Get the origin for the grid at the given zoom level. + * @param {number} z Integer zoom level. + * @return {import("../coordinate.js").Coordinate} Origin. + * @api + */ + getOrigin(z) { + if (this.origin_) { + return this.origin_; + } + return this.origins_[z]; + } + /** + * Get the resolution for the given zoom level. + * @param {number} z Integer zoom level. + * @return {number} Resolution. + * @api + */ + getResolution(z) { + return this.resolutions_[z]; + } + /** + * Get the list of resolutions for the tile grid. + * @return {Array} Resolutions. + * @api + */ + getResolutions() { + return this.resolutions_; + } + /** + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {import("../TileRange.js").default} [tempTileRange] Temporary import("../TileRange.js").default object. + * @param {import("../extent.js").Extent} [tempExtent] Temporary import("../extent.js").Extent object. + * @return {import("../TileRange.js").default|null} Tile range. + */ + getTileCoordChildTileRange(tileCoord, tempTileRange, tempExtent) { + if (tileCoord[0] < this.maxZoom) { + if (this.zoomFactor_ === 2) { + const minX = tileCoord[1] * 2; + const minY = tileCoord[2] * 2; + return createOrUpdate( + minX, + minX + 1, + minY, + minY + 1, + tempTileRange + ); + } + const tileCoordExtent = this.getTileCoordExtent( + tileCoord, + tempExtent || this.tmpExtent_ + ); + return this.getTileRangeForExtentAndZ( + tileCoordExtent, + tileCoord[0] + 1, + tempTileRange + ); + } + return null; + } + /** + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {number} z Integer zoom level. + * @param {import("../TileRange.js").default} [tempTileRange] Temporary import("../TileRange.js").default object. + * @return {import("../TileRange.js").default|null} Tile range. + */ + getTileRangeForTileCoordAndZ(tileCoord, z, tempTileRange) { + if (z > this.maxZoom || z < this.minZoom) { + return null; + } + const tileCoordZ = tileCoord[0]; + const tileCoordX = tileCoord[1]; + const tileCoordY = tileCoord[2]; + if (z === tileCoordZ) { + return createOrUpdate( + tileCoordX, + tileCoordY, + tileCoordX, + tileCoordY, + tempTileRange + ); + } + if (this.zoomFactor_) { + const factor = Math.pow(this.zoomFactor_, z - tileCoordZ); + const minX = Math.floor(tileCoordX * factor); + const minY = Math.floor(tileCoordY * factor); + if (z < tileCoordZ) { + return createOrUpdate(minX, minX, minY, minY, tempTileRange); + } + const maxX = Math.floor(factor * (tileCoordX + 1)) - 1; + const maxY = Math.floor(factor * (tileCoordY + 1)) - 1; + return createOrUpdate(minX, maxX, minY, maxY, tempTileRange); + } + const tileCoordExtent = this.getTileCoordExtent(tileCoord, this.tmpExtent_); + return this.getTileRangeForExtentAndZ(tileCoordExtent, z, tempTileRange); + } + /** + * Get a tile range for the given extent and integer zoom level. + * @param {import("../extent.js").Extent} extent Extent. + * @param {number} z Integer zoom level. + * @param {import("../TileRange.js").default} [tempTileRange] Temporary tile range object. + * @return {import("../TileRange.js").default} Tile range. + */ + getTileRangeForExtentAndZ(extent, z, tempTileRange) { + this.getTileCoordForXYAndZ_(extent[0], extent[3], z, false, tmpTileCoord); + const minX = tmpTileCoord[1]; + const minY = tmpTileCoord[2]; + this.getTileCoordForXYAndZ_(extent[2], extent[1], z, true, tmpTileCoord); + const maxX = tmpTileCoord[1]; + const maxY = tmpTileCoord[2]; + return createOrUpdate(minX, maxX, minY, maxY, tempTileRange); + } + /** + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @return {import("../coordinate.js").Coordinate} Tile center. + */ + getTileCoordCenter(tileCoord) { + const origin = this.getOrigin(tileCoord[0]); + const resolution = this.getResolution(tileCoord[0]); + const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_); + return [ + origin[0] + (tileCoord[1] + 0.5) * tileSize[0] * resolution, + origin[1] - (tileCoord[2] + 0.5) * tileSize[1] * resolution + ]; + } + /** + * Get the extent of a tile coordinate. + * + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {import("../extent.js").Extent} [tempExtent] Temporary extent object. + * @return {import("../extent.js").Extent} Extent. + * @api + */ + getTileCoordExtent(tileCoord, tempExtent) { + const origin = this.getOrigin(tileCoord[0]); + const resolution = this.getResolution(tileCoord[0]); + const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_); + const minX = origin[0] + tileCoord[1] * tileSize[0] * resolution; + const minY = origin[1] - (tileCoord[2] + 1) * tileSize[1] * resolution; + const maxX = minX + tileSize[0] * resolution; + const maxY = minY + tileSize[1] * resolution; + return createOrUpdate$2(minX, minY, maxX, maxY, tempExtent); + } + /** + * Get the tile coordinate for the given map coordinate and resolution. This + * method considers that coordinates that intersect tile boundaries should be + * assigned the higher tile coordinate. + * + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @param {number} resolution Resolution. + * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Destination import("../tilecoord.js").TileCoord object. + * @return {import("../tilecoord.js").TileCoord} Tile coordinate. + * @api + */ + getTileCoordForCoordAndResolution(coordinate, resolution, opt_tileCoord) { + return this.getTileCoordForXYAndResolution_( + coordinate[0], + coordinate[1], + resolution, + false, + opt_tileCoord + ); + } + /** + * Note that this method should not be called for resolutions that correspond + * to an integer zoom level. Instead call the `getTileCoordForXYAndZ_` method. + * @param {number} x X. + * @param {number} y Y. + * @param {number} resolution Resolution (for a non-integer zoom level). + * @param {boolean} reverseIntersectionPolicy Instead of letting edge + * intersections go to the higher tile coordinate, let edge intersections + * go to the lower tile coordinate. + * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Temporary import("../tilecoord.js").TileCoord object. + * @return {import("../tilecoord.js").TileCoord} Tile coordinate. + * @private + */ + getTileCoordForXYAndResolution_(x, y, resolution, reverseIntersectionPolicy, opt_tileCoord) { + const z = this.getZForResolution(resolution); + const scale2 = resolution / this.getResolution(z); + const origin = this.getOrigin(z); + const tileSize = toSize(this.getTileSize(z), this.tmpSize_); + let tileCoordX = scale2 * (x - origin[0]) / resolution / tileSize[0]; + let tileCoordY = scale2 * (origin[1] - y) / resolution / tileSize[1]; + if (reverseIntersectionPolicy) { + tileCoordX = ceil(tileCoordX, DECIMALS) - 1; + tileCoordY = ceil(tileCoordY, DECIMALS) - 1; + } else { + tileCoordX = floor(tileCoordX, DECIMALS); + tileCoordY = floor(tileCoordY, DECIMALS); + } + return createOrUpdate$1(z, tileCoordX, tileCoordY, opt_tileCoord); + } + /** + * Although there is repetition between this method and `getTileCoordForXYAndResolution_`, + * they should have separate implementations. This method is for integer zoom + * levels. The other method should only be called for resolutions corresponding + * to non-integer zoom levels. + * @param {number} x Map x coordinate. + * @param {number} y Map y coordinate. + * @param {number} z Integer zoom level. + * @param {boolean} reverseIntersectionPolicy Instead of letting edge + * intersections go to the higher tile coordinate, let edge intersections + * go to the lower tile coordinate. + * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Temporary import("../tilecoord.js").TileCoord object. + * @return {import("../tilecoord.js").TileCoord} Tile coordinate. + * @private + */ + getTileCoordForXYAndZ_(x, y, z, reverseIntersectionPolicy, opt_tileCoord) { + const origin = this.getOrigin(z); + const resolution = this.getResolution(z); + const tileSize = toSize(this.getTileSize(z), this.tmpSize_); + let tileCoordX = (x - origin[0]) / resolution / tileSize[0]; + let tileCoordY = (origin[1] - y) / resolution / tileSize[1]; + if (reverseIntersectionPolicy) { + tileCoordX = ceil(tileCoordX, DECIMALS) - 1; + tileCoordY = ceil(tileCoordY, DECIMALS) - 1; + } else { + tileCoordX = floor(tileCoordX, DECIMALS); + tileCoordY = floor(tileCoordY, DECIMALS); + } + return createOrUpdate$1(z, tileCoordX, tileCoordY, opt_tileCoord); + } + /** + * Get a tile coordinate given a map coordinate and zoom level. + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @param {number} z Zoom level. + * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Destination import("../tilecoord.js").TileCoord object. + * @return {import("../tilecoord.js").TileCoord} Tile coordinate. + * @api + */ + getTileCoordForCoordAndZ(coordinate, z, opt_tileCoord) { + return this.getTileCoordForXYAndZ_( + coordinate[0], + coordinate[1], + z, + false, + opt_tileCoord + ); + } + /** + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @return {number} Tile resolution. + */ + getTileCoordResolution(tileCoord) { + return this.resolutions_[tileCoord[0]]; + } + /** + * Get the tile size for a zoom level. The type of the return value matches the + * `tileSize` or `tileSizes` that the tile grid was configured with. To always + * get an {@link import("../size.js").Size}, run the result through {@link module:ol/size.toSize}. + * @param {number} z Z. + * @return {number|import("../size.js").Size} Tile size. + * @api + */ + getTileSize(z) { + if (this.tileSize_) { + return this.tileSize_; + } + return this.tileSizes_[z]; + } + /** + * @param {number} z Zoom level. + * @return {import("../TileRange.js").default} Extent tile range for the specified zoom level. + */ + getFullTileRange(z) { + if (!this.fullTileRanges_) { + return this.extent_ ? this.getTileRangeForExtentAndZ(this.extent_, z) : null; + } + return this.fullTileRanges_[z]; + } + /** + * @param {number} resolution Resolution. + * @param {number|import("../array.js").NearestDirectionFunction} [opt_direction] + * If 0, the nearest resolution will be used. + * If 1, the nearest higher resolution (lower Z) will be used. If -1, the + * nearest lower resolution (higher Z) will be used. Default is 0. + * Use a {@link module:ol/array~NearestDirectionFunction} for more precise control. + * + * For example to change tile Z at the midpoint of zoom levels + * ```js + * function(value, high, low) { + * return value - low * Math.sqrt(high / low); + * } + * ``` + * @return {number} Z. + * @api + */ + getZForResolution(resolution, opt_direction) { + const z = linearFindNearest( + this.resolutions_, + resolution, + opt_direction || 0 + ); + return clamp(z, this.minZoom, this.maxZoom); + } + /** + * The tile with the provided tile coordinate intersects the given viewport. + * @param {import('../tilecoord.js').TileCoord} tileCoord Tile coordinate. + * @param {Array} viewport Viewport as returned from {@link module:ol/extent.getRotatedViewport}. + * @return {boolean} The tile with the provided tile coordinate intersects the given viewport. + */ + tileCoordIntersectsViewport(tileCoord, viewport) { + return intersectsLinearRing( + viewport, + 0, + viewport.length, + 2, + this.getTileCoordExtent(tileCoord) + ); + } + /** + * @param {!import("../extent.js").Extent} extent Extent for this tile grid. + * @private + */ + calculateTileRanges_(extent) { + const length = this.resolutions_.length; + const fullTileRanges = new Array(length); + for (let z = this.minZoom; z < length; ++z) { + fullTileRanges[z] = this.getTileRangeForExtentAndZ(extent, z); + } + this.fullTileRanges_ = fullTileRanges; + } +} +const TileGrid$1 = TileGrid; +function getForProjection(projection) { + let tileGrid = projection.getDefaultTileGrid(); + if (!tileGrid) { + tileGrid = createForProjection(projection); + projection.setDefaultTileGrid(tileGrid); + } + return tileGrid; +} +function wrapX(tileGrid, tileCoord, projection) { + const z = tileCoord[0]; + const center = tileGrid.getTileCoordCenter(tileCoord); + const projectionExtent = extentFromProjection(projection); + if (!containsCoordinate(projectionExtent, center)) { + const worldWidth = getWidth(projectionExtent); + const worldsAway = Math.ceil( + (projectionExtent[0] - center[0]) / worldWidth + ); + center[0] += worldWidth * worldsAway; + return tileGrid.getTileCoordForCoordAndZ(center, z); + } + return tileCoord; +} +function createForExtent(extent, maxZoom, tileSize, corner) { + corner = corner !== void 0 ? corner : "top-left"; + const resolutions = resolutionsFromExtent(extent, maxZoom, tileSize); + return new TileGrid$1({ + extent, + origin: getCorner(extent, corner), + resolutions, + tileSize + }); +} +function resolutionsFromExtent(extent, maxZoom, tileSize, maxResolution) { + maxZoom = maxZoom !== void 0 ? maxZoom : DEFAULT_MAX_ZOOM; + tileSize = toSize(tileSize !== void 0 ? tileSize : DEFAULT_TILE_SIZE); + const height = getHeight(extent); + const width = getWidth(extent); + maxResolution = maxResolution > 0 ? maxResolution : Math.max(width / tileSize[0], height / tileSize[1]); + const length = maxZoom + 1; + const resolutions = new Array(length); + for (let z = 0; z < length; ++z) { + resolutions[z] = maxResolution / Math.pow(2, z); + } + return resolutions; +} +function createForProjection(projection, maxZoom, tileSize, corner) { + const extent = extentFromProjection(projection); + return createForExtent(extent, maxZoom, tileSize, corner); +} +function extentFromProjection(projection) { + projection = get$1(projection); + let extent = projection.getExtent(); + if (!extent) { + const half = 180 * METERS_PER_UNIT$1.degrees / projection.getMetersPerUnit(); + extent = createOrUpdate$2(-half, -half, half, half); + } + return extent; +} +class TileSource extends Source$1 { + /** + * @param {Options} options SourceTile source options. + */ + constructor(options) { + super({ + attributions: options.attributions, + attributionsCollapsible: options.attributionsCollapsible, + projection: options.projection, + state: options.state, + wrapX: options.wrapX, + interpolate: options.interpolate + }); + this.on; + this.once; + this.un; + this.opaque_ = options.opaque !== void 0 ? options.opaque : false; + this.tilePixelRatio_ = options.tilePixelRatio !== void 0 ? options.tilePixelRatio : 1; + this.tileGrid = options.tileGrid !== void 0 ? options.tileGrid : null; + const tileSize = [256, 256]; + if (this.tileGrid) { + toSize(this.tileGrid.getTileSize(this.tileGrid.getMinZoom()), tileSize); + } + this.tileCache = new TileCache$1(options.cacheSize || 0); + this.tmpSize = [0, 0]; + this.key_ = options.key || ""; + this.tileOptions = { + transition: options.transition, + interpolate: options.interpolate + }; + this.zDirection = options.zDirection ? options.zDirection : 0; + } + /** + * @return {boolean} Can expire cache. + */ + canExpireCache() { + return this.tileCache.canExpireCache(); + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @param {!Object} usedTiles Used tiles. + */ + expireCache(projection, usedTiles) { + const tileCache = this.getTileCacheForProjection(projection); + if (tileCache) { + tileCache.expireCache(usedTiles); + } + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @param {number} z Zoom level. + * @param {import("../TileRange.js").default} tileRange Tile range. + * @param {function(import("../Tile.js").default):(boolean|void)} callback Called with each + * loaded tile. If the callback returns `false`, the tile will not be + * considered loaded. + * @return {boolean} The tile range is fully covered with loaded tiles. + */ + forEachLoadedTile(projection, z, tileRange, callback) { + const tileCache = this.getTileCacheForProjection(projection); + if (!tileCache) { + return false; + } + let covered = true; + let tile, tileCoordKey, loaded; + for (let x = tileRange.minX; x <= tileRange.maxX; ++x) { + for (let y = tileRange.minY; y <= tileRange.maxY; ++y) { + tileCoordKey = getKeyZXY(z, x, y); + loaded = false; + if (tileCache.containsKey(tileCoordKey)) { + tile = /** @type {!import("../Tile.js").default} */ + tileCache.get(tileCoordKey); + loaded = tile.getState() === TileState.LOADED; + if (loaded) { + loaded = callback(tile) !== false; + } + } + if (!loaded) { + covered = false; + } + } + } + return covered; + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {number} Gutter. + */ + getGutterForProjection(projection) { + return 0; + } + /** + * Return the key to be used for all tiles in the source. + * @return {string} The key for all tiles. + */ + getKey() { + return this.key_; + } + /** + * Set the value to be used as the key for all tiles in the source. + * @param {string} key The key for tiles. + * @protected + */ + setKey(key) { + if (this.key_ !== key) { + this.key_ = key; + this.changed(); + } + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {boolean} Opaque. + */ + getOpaque(projection) { + return this.opaque_; + } + /** + * @param {import("../proj/Projection").default} [projection] Projection. + * @return {Array|null} Resolutions. + */ + getResolutions(projection) { + const tileGrid = projection ? this.getTileGridForProjection(projection) : this.tileGrid; + if (!tileGrid) { + return null; + } + return tileGrid.getResolutions(); + } + /** + * @abstract + * @param {number} z Tile coordinate z. + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {!import("../Tile.js").default} Tile. + */ + getTile(z, x, y, pixelRatio, projection) { + return abstract(); + } + /** + * Return the tile grid of the tile source. + * @return {import("../tilegrid/TileGrid.js").default|null} Tile grid. + * @api + */ + getTileGrid() { + return this.tileGrid; + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {!import("../tilegrid/TileGrid.js").default} Tile grid. + */ + getTileGridForProjection(projection) { + if (!this.tileGrid) { + return getForProjection(projection); + } + return this.tileGrid; + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {import("../TileCache.js").default} Tile cache. + * @protected + */ + getTileCacheForProjection(projection) { + const sourceProjection = this.getProjection(); + assert( + sourceProjection === null || equivalent(sourceProjection, projection), + "A VectorTile source can only be rendered if it has a projection compatible with the view projection." + ); + return this.tileCache; + } + /** + * Get the tile pixel ratio for this source. Subclasses may override this + * method, which is meant to return a supported pixel ratio that matches the + * provided `pixelRatio` as close as possible. + * @param {number} pixelRatio Pixel ratio. + * @return {number} Tile pixel ratio. + */ + getTilePixelRatio(pixelRatio) { + return this.tilePixelRatio_; + } + /** + * @param {number} z Z. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {import("../size.js").Size} Tile size. + */ + getTilePixelSize(z, pixelRatio, projection) { + const tileGrid = this.getTileGridForProjection(projection); + const tilePixelRatio = this.getTilePixelRatio(pixelRatio); + const tileSize = toSize(tileGrid.getTileSize(z), this.tmpSize); + if (tilePixelRatio == 1) { + return tileSize; + } + return scale(tileSize, tilePixelRatio, this.tmpSize); + } + /** + * Returns a tile coordinate wrapped around the x-axis. When the tile coordinate + * is outside the resolution and extent range of the tile grid, `null` will be + * returned. + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {import("../proj/Projection.js").default} [projection] Projection. + * @return {import("../tilecoord.js").TileCoord} Tile coordinate to be passed to the tileUrlFunction or + * null if no tile URL should be created for the passed `tileCoord`. + */ + getTileCoordForTileUrlFunction(tileCoord, projection) { + projection = projection !== void 0 ? projection : this.getProjection(); + const tileGrid = this.getTileGridForProjection(projection); + if (this.getWrapX() && projection.isGlobal()) { + tileCoord = wrapX(tileGrid, tileCoord, projection); + } + return withinExtentAndZ(tileCoord, tileGrid) ? tileCoord : null; + } + /** + * Remove all cached tiles from the source. The next render cycle will fetch new tiles. + * @api + */ + clear() { + this.tileCache.clear(); + } + refresh() { + this.clear(); + super.refresh(); + } + /** + * Increases the cache size if needed + * @param {number} tileCount Minimum number of tiles needed. + * @param {import("../proj/Projection.js").default} projection Projection. + */ + updateCacheSize(tileCount, projection) { + const tileCache = this.getTileCacheForProjection(projection); + if (tileCount > tileCache.highWaterMark) { + tileCache.highWaterMark = tileCount; + } + } + /** + * Marks a tile coord as being used, without triggering a load. + * @abstract + * @param {number} z Tile coordinate z. + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + * @param {import("../proj/Projection.js").default} projection Projection. + */ + useTile(z, x, y, projection) { + } +} +class TileSourceEvent extends Event { + /** + * @param {string} type Type. + * @param {import("../Tile.js").default} tile The tile. + */ + constructor(type, tile) { + super(type); + this.tile = tile; + } +} +const TileSource$1 = TileSource; +function createFromTemplate(template, tileGrid) { + const zRegEx = /\{z\}/g; + const xRegEx = /\{x\}/g; + const yRegEx = /\{y\}/g; + const dashYRegEx = /\{-y\}/g; + return ( + /** + * @param {import("./tilecoord.js").TileCoord} tileCoord Tile Coordinate. + * @param {number} pixelRatio Pixel ratio. + * @param {import("./proj/Projection.js").default} projection Projection. + * @return {string|undefined} Tile URL. + */ + function(tileCoord, pixelRatio, projection) { + if (!tileCoord) { + return void 0; + } + return template.replace(zRegEx, tileCoord[0].toString()).replace(xRegEx, tileCoord[1].toString()).replace(yRegEx, tileCoord[2].toString()).replace(dashYRegEx, function() { + const z = tileCoord[0]; + const range = tileGrid.getFullTileRange(z); + assert( + range, + "The {-y} placeholder requires a tile grid with extent" + ); + const y = range.getHeight() - tileCoord[2] - 1; + return y.toString(); + }); + } + ); +} +function createFromTemplates(templates, tileGrid) { + const len = templates.length; + const tileUrlFunctions = new Array(len); + for (let i = 0; i < len; ++i) { + tileUrlFunctions[i] = createFromTemplate(templates[i], tileGrid); + } + return createFromTileUrlFunctions(tileUrlFunctions); +} +function createFromTileUrlFunctions(tileUrlFunctions) { + if (tileUrlFunctions.length === 1) { + return tileUrlFunctions[0]; + } + return ( + /** + * @param {import("./tilecoord.js").TileCoord} tileCoord Tile Coordinate. + * @param {number} pixelRatio Pixel ratio. + * @param {import("./proj/Projection.js").default} projection Projection. + * @return {string|undefined} Tile URL. + */ + function(tileCoord, pixelRatio, projection) { + if (!tileCoord) { + return void 0; + } + const h = hash(tileCoord); + const index = modulo(h, tileUrlFunctions.length); + return tileUrlFunctions[index](tileCoord, pixelRatio, projection); + } + ); +} +function expandUrl(url) { + const urls = []; + let match = /\{([a-z])-([a-z])\}/.exec(url); + if (match) { + const startCharCode = match[1].charCodeAt(0); + const stopCharCode = match[2].charCodeAt(0); + let charCode; + for (charCode = startCharCode; charCode <= stopCharCode; ++charCode) { + urls.push(url.replace(match[0], String.fromCharCode(charCode))); + } + return urls; + } + match = /\{(\d+)-(\d+)\}/.exec(url); + if (match) { + const stop = parseInt(match[2], 10); + for (let i = parseInt(match[1], 10); i <= stop; i++) { + urls.push(url.replace(match[0], i.toString())); + } + return urls; + } + urls.push(url); + return urls; +} +class UrlTile extends TileSource$1 { + /** + * @param {Options} options Image tile options. + */ + constructor(options) { + super({ + attributions: options.attributions, + cacheSize: options.cacheSize, + opaque: options.opaque, + projection: options.projection, + state: options.state, + tileGrid: options.tileGrid, + tilePixelRatio: options.tilePixelRatio, + wrapX: options.wrapX, + transition: options.transition, + interpolate: options.interpolate, + key: options.key, + attributionsCollapsible: options.attributionsCollapsible, + zDirection: options.zDirection + }); + this.generateTileUrlFunction_ = this.tileUrlFunction === UrlTile.prototype.tileUrlFunction; + this.tileLoadFunction = options.tileLoadFunction; + if (options.tileUrlFunction) { + this.tileUrlFunction = options.tileUrlFunction; + } + this.urls = null; + if (options.urls) { + this.setUrls(options.urls); + } else if (options.url) { + this.setUrl(options.url); + } + this.tileLoadingKeys_ = {}; + } + /** + * Return the tile load function of the source. + * @return {import("../Tile.js").LoadFunction} TileLoadFunction + * @api + */ + getTileLoadFunction() { + return this.tileLoadFunction; + } + /** + * Return the tile URL function of the source. + * @return {import("../Tile.js").UrlFunction} TileUrlFunction + * @api + */ + getTileUrlFunction() { + return Object.getPrototypeOf(this).tileUrlFunction === this.tileUrlFunction ? this.tileUrlFunction.bind(this) : this.tileUrlFunction; + } + /** + * Return the URLs used for this source. + * When a tileUrlFunction is used instead of url or urls, + * null will be returned. + * @return {!Array|null} URLs. + * @api + */ + getUrls() { + return this.urls; + } + /** + * Handle tile change events. + * @param {import("../events/Event.js").default} event Event. + * @protected + */ + handleTileChange(event) { + const tile = ( + /** @type {import("../Tile.js").default} */ + event.target + ); + const uid = getUid(tile); + const tileState = tile.getState(); + let type; + if (tileState == TileState.LOADING) { + this.tileLoadingKeys_[uid] = true; + type = TileEventType.TILELOADSTART; + } else if (uid in this.tileLoadingKeys_) { + delete this.tileLoadingKeys_[uid]; + type = tileState == TileState.ERROR ? TileEventType.TILELOADERROR : tileState == TileState.LOADED ? TileEventType.TILELOADEND : void 0; + } + if (type != void 0) { + this.dispatchEvent(new TileSourceEvent(type, tile)); + } + } + /** + * Set the tile load function of the source. + * @param {import("../Tile.js").LoadFunction} tileLoadFunction Tile load function. + * @api + */ + setTileLoadFunction(tileLoadFunction) { + this.tileCache.clear(); + this.tileLoadFunction = tileLoadFunction; + this.changed(); + } + /** + * Set the tile URL function of the source. + * @param {import("../Tile.js").UrlFunction} tileUrlFunction Tile URL function. + * @param {string} [key] Optional new tile key for the source. + * @api + */ + setTileUrlFunction(tileUrlFunction, key) { + this.tileUrlFunction = tileUrlFunction; + this.tileCache.pruneExceptNewestZ(); + if (typeof key !== "undefined") { + this.setKey(key); + } else { + this.changed(); + } + } + /** + * Set the URL to use for requests. + * @param {string} url URL. + * @api + */ + setUrl(url) { + const urls = expandUrl(url); + this.urls = urls; + this.setUrls(urls); + } + /** + * Set the URLs to use for requests. + * @param {Array} urls URLs. + * @api + */ + setUrls(urls) { + this.urls = urls; + const key = urls.join("\n"); + if (this.generateTileUrlFunction_) { + this.setTileUrlFunction(createFromTemplates(urls, this.tileGrid), key); + } else { + this.setKey(key); + } + } + /** + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {string|undefined} Tile URL. + */ + tileUrlFunction(tileCoord, pixelRatio, projection) { + return void 0; + } + /** + * Marks a tile coord as being used, without triggering a load. + * @param {number} z Tile coordinate z. + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + */ + useTile(z, x, y) { + const tileCoordKey = getKeyZXY(z, x, y); + if (this.tileCache.containsKey(tileCoordKey)) { + this.tileCache.get(tileCoordKey); + } + } +} +const UrlTile$1 = UrlTile; +class TileImage extends UrlTile$1 { + /** + * @param {!Options} options Image tile options. + */ + constructor(options) { + super({ + attributions: options.attributions, + cacheSize: options.cacheSize, + opaque: options.opaque, + projection: options.projection, + state: options.state, + tileGrid: options.tileGrid, + tileLoadFunction: options.tileLoadFunction ? options.tileLoadFunction : defaultTileLoadFunction, + tilePixelRatio: options.tilePixelRatio, + tileUrlFunction: options.tileUrlFunction, + url: options.url, + urls: options.urls, + wrapX: options.wrapX, + transition: options.transition, + interpolate: options.interpolate !== void 0 ? options.interpolate : true, + key: options.key, + attributionsCollapsible: options.attributionsCollapsible, + zDirection: options.zDirection + }); + this.crossOrigin = options.crossOrigin !== void 0 ? options.crossOrigin : null; + this.tileClass = options.tileClass !== void 0 ? options.tileClass : ImageTile$1; + this.tileCacheForProjection = {}; + this.tileGridForProjection = {}; + this.reprojectionErrorThreshold_ = options.reprojectionErrorThreshold; + this.renderReprojectionEdges_ = false; + } + /** + * @return {boolean} Can expire cache. + */ + canExpireCache() { + if (this.tileCache.canExpireCache()) { + return true; + } + for (const key in this.tileCacheForProjection) { + if (this.tileCacheForProjection[key].canExpireCache()) { + return true; + } + } + return false; + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @param {!Object} usedTiles Used tiles. + */ + expireCache(projection, usedTiles) { + const usedTileCache = this.getTileCacheForProjection(projection); + this.tileCache.expireCache( + this.tileCache == usedTileCache ? usedTiles : {} + ); + for (const id in this.tileCacheForProjection) { + const tileCache = this.tileCacheForProjection[id]; + tileCache.expireCache(tileCache == usedTileCache ? usedTiles : {}); + } + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {number} Gutter. + */ + getGutterForProjection(projection) { + if (this.getProjection() && projection && !equivalent(this.getProjection(), projection)) { + return 0; + } + return this.getGutter(); + } + /** + * @return {number} Gutter. + */ + getGutter() { + return 0; + } + /** + * Return the key to be used for all tiles in the source. + * @return {string} The key for all tiles. + */ + getKey() { + let key = super.getKey(); + if (!this.getInterpolate()) { + key += ":disable-interpolation"; + } + return key; + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {boolean} Opaque. + */ + getOpaque(projection) { + if (this.getProjection() && projection && !equivalent(this.getProjection(), projection)) { + return false; + } + return super.getOpaque(projection); + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {!import("../tilegrid/TileGrid.js").default} Tile grid. + */ + getTileGridForProjection(projection) { + const thisProj = this.getProjection(); + if (this.tileGrid && (!thisProj || equivalent(thisProj, projection))) { + return this.tileGrid; + } + const projKey = getUid(projection); + if (!(projKey in this.tileGridForProjection)) { + this.tileGridForProjection[projKey] = getForProjection(projection); + } + return this.tileGridForProjection[projKey]; + } + /** + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {import("../TileCache.js").default} Tile cache. + */ + getTileCacheForProjection(projection) { + const thisProj = this.getProjection(); + if (!thisProj || equivalent(thisProj, projection)) { + return this.tileCache; + } + const projKey = getUid(projection); + if (!(projKey in this.tileCacheForProjection)) { + this.tileCacheForProjection[projKey] = new TileCache$1( + this.tileCache.highWaterMark + ); + } + return this.tileCacheForProjection[projKey]; + } + /** + * @param {number} z Tile coordinate z. + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../proj/Projection.js").default} projection Projection. + * @param {string} key The key set on the tile. + * @return {!ImageTile} Tile. + * @private + */ + createTile_(z, x, y, pixelRatio, projection, key) { + const tileCoord = [z, x, y]; + const urlTileCoord = this.getTileCoordForTileUrlFunction( + tileCoord, + projection + ); + const tileUrl = urlTileCoord ? this.tileUrlFunction(urlTileCoord, pixelRatio, projection) : void 0; + const tile = new this.tileClass( + tileCoord, + tileUrl !== void 0 ? TileState.IDLE : TileState.EMPTY, + tileUrl !== void 0 ? tileUrl : "", + this.crossOrigin, + this.tileLoadFunction, + this.tileOptions + ); + tile.key = key; + tile.addEventListener(EventType.CHANGE, this.handleTileChange.bind(this)); + return tile; + } + /** + * @param {number} z Tile coordinate z. + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {!(ImageTile|ReprojTile)} Tile. + */ + getTile(z, x, y, pixelRatio, projection) { + const sourceProjection = this.getProjection(); + if (!sourceProjection || !projection || equivalent(sourceProjection, projection)) { + return this.getTileInternal( + z, + x, + y, + pixelRatio, + sourceProjection || projection + ); + } + const cache2 = this.getTileCacheForProjection(projection); + const tileCoord = [z, x, y]; + let tile; + const tileCoordKey = getKey(tileCoord); + if (cache2.containsKey(tileCoordKey)) { + tile = cache2.get(tileCoordKey); + } + const key = this.getKey(); + if (tile && tile.key == key) { + return tile; + } + const sourceTileGrid = this.getTileGridForProjection(sourceProjection); + const targetTileGrid = this.getTileGridForProjection(projection); + const wrappedTileCoord = this.getTileCoordForTileUrlFunction( + tileCoord, + projection + ); + const newTile = new ReprojTile$1( + sourceProjection, + sourceTileGrid, + projection, + targetTileGrid, + tileCoord, + wrappedTileCoord, + this.getTilePixelRatio(pixelRatio), + this.getGutter(), + (z2, x2, y2, pixelRatio2) => this.getTileInternal(z2, x2, y2, pixelRatio2, sourceProjection), + this.reprojectionErrorThreshold_, + this.renderReprojectionEdges_, + this.getInterpolate() + ); + newTile.key = key; + if (tile) { + newTile.interimTile = tile; + newTile.refreshInterimChain(); + cache2.replace(tileCoordKey, newTile); + } else { + cache2.set(tileCoordKey, newTile); + } + return newTile; + } + /** + * @param {number} z Tile coordinate z. + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + * @param {number} pixelRatio Pixel ratio. + * @param {!import("../proj/Projection.js").default} projection Projection. + * @return {!ImageTile} Tile. + * @protected + */ + getTileInternal(z, x, y, pixelRatio, projection) { + let tile = null; + const tileCoordKey = getKeyZXY(z, x, y); + const key = this.getKey(); + if (!this.tileCache.containsKey(tileCoordKey)) { + tile = this.createTile_(z, x, y, pixelRatio, projection, key); + this.tileCache.set(tileCoordKey, tile); + } else { + tile = this.tileCache.get(tileCoordKey); + if (tile.key != key) { + const interimTile = tile; + tile = this.createTile_(z, x, y, pixelRatio, projection, key); + if (interimTile.getState() == TileState.IDLE) { + tile.interimTile = interimTile.interimTile; + } else { + tile.interimTile = interimTile; + } + tile.refreshInterimChain(); + this.tileCache.replace(tileCoordKey, tile); + } + } + return tile; + } + /** + * Sets whether to render reprojection edges or not (usually for debugging). + * @param {boolean} render Render the edges. + * @api + */ + setRenderReprojectionEdges(render2) { + if (this.renderReprojectionEdges_ == render2) { + return; + } + this.renderReprojectionEdges_ = render2; + for (const id in this.tileCacheForProjection) { + this.tileCacheForProjection[id].clear(); + } + this.changed(); + } + /** + * Sets the tile grid to use when reprojecting the tiles to the given + * projection instead of the default tile grid for the projection. + * + * This can be useful when the default tile grid cannot be created + * (e.g. projection has no extent defined) or + * for optimization reasons (custom tile size, resolutions, ...). + * + * @param {import("../proj.js").ProjectionLike} projection Projection. + * @param {import("../tilegrid/TileGrid.js").default} tilegrid Tile grid to use for the projection. + * @api + */ + setTileGridForProjection(projection, tilegrid) { + const proj = get$1(projection); + if (proj) { + const projKey = getUid(proj); + if (!(projKey in this.tileGridForProjection)) { + this.tileGridForProjection[projKey] = tilegrid; + } + } + } + clear() { + super.clear(); + for (const id in this.tileCacheForProjection) { + this.tileCacheForProjection[id].clear(); + } + } +} +function defaultTileLoadFunction(imageTile, src) { + imageTile.getImage().src = src; +} +const TileImage$1 = TileImage; +function appendParams(uri, params) { + const keyParams = []; + Object.keys(params).forEach(function(k) { + if (params[k] !== null && params[k] !== void 0) { + keyParams.push(k + "=" + encodeURIComponent(params[k])); + } + }); + const qs = keyParams.join("&"); + uri = uri.replace(/[?&]$/, ""); + uri += uri.includes("?") ? "&" : "?"; + return uri + qs; +} +class WMTSTileGrid extends TileGrid$1 { + /** + * @param {Options} options WMTS options. + */ + constructor(options) { + super({ + extent: options.extent, + origin: options.origin, + origins: options.origins, + resolutions: options.resolutions, + tileSize: options.tileSize, + tileSizes: options.tileSizes, + sizes: options.sizes + }); + this.matrixIds_ = options.matrixIds; + } + /** + * @param {number} z Z. + * @return {string} MatrixId.. + */ + getMatrixId(z) { + return this.matrixIds_[z]; + } + /** + * Get the list of matrix identifiers. + * @return {Array} MatrixIds. + * @api + */ + getMatrixIds() { + return this.matrixIds_; + } +} +function createFromCapabilitiesMatrixSet(matrixSet, extent, matrixLimits) { + const resolutions = []; + const matrixIds = []; + const origins = []; + const tileSizes = []; + const sizes = []; + matrixLimits = matrixLimits !== void 0 ? matrixLimits : []; + const supportedCRSPropName = "SupportedCRS"; + const matrixIdsPropName = "TileMatrix"; + const identifierPropName = "Identifier"; + const scaleDenominatorPropName = "ScaleDenominator"; + const topLeftCornerPropName = "TopLeftCorner"; + const tileWidthPropName = "TileWidth"; + const tileHeightPropName = "TileHeight"; + const code = matrixSet[supportedCRSPropName]; + const projection = get$1(code); + const metersPerUnit = projection.getMetersPerUnit(); + const switchOriginXY = projection.getAxisOrientation().substr(0, 2) == "ne"; + matrixSet[matrixIdsPropName].sort(function(a, b) { + return b[scaleDenominatorPropName] - a[scaleDenominatorPropName]; + }); + matrixSet[matrixIdsPropName].forEach(function(elt) { + let matrixAvailable; + if (matrixLimits.length > 0) { + matrixAvailable = matrixLimits.find(function(elt_ml) { + if (elt[identifierPropName] == elt_ml[matrixIdsPropName]) { + return true; + } + if (!elt[identifierPropName].includes(":")) { + return matrixSet[identifierPropName] + ":" + elt[identifierPropName] === elt_ml[matrixIdsPropName]; + } + return false; + }); + } else { + matrixAvailable = true; + } + if (matrixAvailable) { + matrixIds.push(elt[identifierPropName]); + const resolution = elt[scaleDenominatorPropName] * 28e-5 / metersPerUnit; + const tileWidth = elt[tileWidthPropName]; + const tileHeight = elt[tileHeightPropName]; + if (switchOriginXY) { + origins.push([ + elt[topLeftCornerPropName][1], + elt[topLeftCornerPropName][0] + ]); + } else { + origins.push(elt[topLeftCornerPropName]); + } + resolutions.push(resolution); + tileSizes.push( + tileWidth == tileHeight ? tileWidth : [tileWidth, tileHeight] + ); + sizes.push([elt["MatrixWidth"], elt["MatrixHeight"]]); + } + }); + return new WMTSTileGrid({ + extent, + origins, + resolutions, + matrixIds, + tileSizes, + sizes + }); +} +class WMTS extends TileImage$1 { + /** + * @param {Options} options WMTS options. + */ + constructor(options) { + const requestEncoding = options.requestEncoding !== void 0 ? options.requestEncoding : "KVP"; + const tileGrid = options.tileGrid; + let urls = options.urls; + if (urls === void 0 && options.url !== void 0) { + urls = expandUrl(options.url); + } + super({ + attributions: options.attributions, + attributionsCollapsible: options.attributionsCollapsible, + cacheSize: options.cacheSize, + crossOrigin: options.crossOrigin, + interpolate: options.interpolate, + projection: options.projection, + reprojectionErrorThreshold: options.reprojectionErrorThreshold, + tileClass: options.tileClass, + tileGrid, + tileLoadFunction: options.tileLoadFunction, + tilePixelRatio: options.tilePixelRatio, + urls, + wrapX: options.wrapX !== void 0 ? options.wrapX : false, + transition: options.transition, + zDirection: options.zDirection + }); + this.version_ = options.version !== void 0 ? options.version : "1.0.0"; + this.format_ = options.format !== void 0 ? options.format : "image/jpeg"; + this.dimensions_ = options.dimensions !== void 0 ? options.dimensions : {}; + this.layer_ = options.layer; + this.matrixSet_ = options.matrixSet; + this.style_ = options.style; + this.requestEncoding_ = requestEncoding; + this.setKey(this.getKeyForDimensions_()); + if (urls && urls.length > 0) { + this.tileUrlFunction = createFromTileUrlFunctions( + urls.map(this.createFromWMTSTemplate.bind(this)) + ); + } + } + /** + * Set the URLs to use for requests. + * URLs may contain OGC conform URL Template Variables: {TileMatrix}, {TileRow}, {TileCol}. + * @param {Array} urls URLs. + */ + setUrls(urls) { + this.urls = urls; + const key = urls.join("\n"); + this.setTileUrlFunction( + createFromTileUrlFunctions( + urls.map(this.createFromWMTSTemplate.bind(this)) + ), + key + ); + } + /** + * Get the dimensions, i.e. those passed to the constructor through the + * "dimensions" option, and possibly updated using the updateDimensions + * method. + * @return {!Object} Dimensions. + * @api + */ + getDimensions() { + return this.dimensions_; + } + /** + * Return the image format of the WMTS source. + * @return {string} Format. + * @api + */ + getFormat() { + return this.format_; + } + /** + * Return the layer of the WMTS source. + * @return {string} Layer. + * @api + */ + getLayer() { + return this.layer_; + } + /** + * Return the matrix set of the WMTS source. + * @return {string} MatrixSet. + * @api + */ + getMatrixSet() { + return this.matrixSet_; + } + /** + * Return the request encoding, either "KVP" or "REST". + * @return {RequestEncoding} Request encoding. + * @api + */ + getRequestEncoding() { + return this.requestEncoding_; + } + /** + * Return the style of the WMTS source. + * @return {string} Style. + * @api + */ + getStyle() { + return this.style_; + } + /** + * Return the version of the WMTS source. + * @return {string} Version. + * @api + */ + getVersion() { + return this.version_; + } + /** + * @private + * @return {string} The key for the current dimensions. + */ + getKeyForDimensions_() { + const res = this.urls ? this.urls.slice(0) : []; + for (const key in this.dimensions_) { + res.push(key + "-" + this.dimensions_[key]); + } + return res.join("/"); + } + /** + * Update the dimensions. + * @param {Object} dimensions Dimensions. + * @api + */ + updateDimensions(dimensions) { + Object.assign(this.dimensions_, dimensions); + this.setKey(this.getKeyForDimensions_()); + } + /** + * @param {string} template Template. + * @return {import("../Tile.js").UrlFunction} Tile URL function. + */ + createFromWMTSTemplate(template) { + const requestEncoding = this.requestEncoding_; + const context = { + "layer": this.layer_, + "style": this.style_, + "tilematrixset": this.matrixSet_ + }; + if (requestEncoding == "KVP") { + Object.assign(context, { + "Service": "WMTS", + "Request": "GetTile", + "Version": this.version_, + "Format": this.format_ + }); + } + template = requestEncoding == "KVP" ? appendParams(template, context) : template.replace(/\{(\w+?)\}/g, function(m, p) { + return p.toLowerCase() in context ? context[p.toLowerCase()] : m; + }); + const tileGrid = ( + /** @type {import("../tilegrid/WMTS.js").default} */ + this.tileGrid + ); + const dimensions = this.dimensions_; + return ( + /** + * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../proj/Projection.js").default} projection Projection. + * @return {string|undefined} Tile URL. + */ + function(tileCoord, pixelRatio, projection) { + if (!tileCoord) { + return void 0; + } + const localContext = { + "TileMatrix": tileGrid.getMatrixId(tileCoord[0]), + "TileCol": tileCoord[1], + "TileRow": tileCoord[2] + }; + Object.assign(localContext, dimensions); + let url = template; + if (requestEncoding == "KVP") { + url = appendParams(url, localContext); + } else { + url = url.replace(/\{(\w+?)\}/g, function(m, p) { + return localContext[p]; + }); + } + return url; + } + ); + } +} +const OlSourceWmts = WMTS; +function optionsFromCapabilities(wmtsCap, config) { + const layers = wmtsCap["Contents"]["Layer"]; + const l = layers.find(function(elt) { + return elt["Identifier"] == config["layer"]; + }); + if (!l) { + return null; + } + const tileMatrixSets = wmtsCap["Contents"]["TileMatrixSet"]; + let idx; + if (l["TileMatrixSetLink"].length > 1) { + if ("projection" in config) { + idx = l["TileMatrixSetLink"].findIndex(function(elt) { + const tileMatrixSet = tileMatrixSets.find(function(el) { + return el["Identifier"] == elt["TileMatrixSet"]; + }); + const supportedCRS = tileMatrixSet["SupportedCRS"]; + const proj1 = get$1(supportedCRS); + const proj2 = get$1(config["projection"]); + if (proj1 && proj2) { + return equivalent(proj1, proj2); + } + return supportedCRS == config["projection"]; + }); + } else { + idx = l["TileMatrixSetLink"].findIndex(function(elt) { + return elt["TileMatrixSet"] == config["matrixSet"]; + }); + } + } else { + idx = 0; + } + if (idx < 0) { + idx = 0; + } + const matrixSet = ( + /** @type {string} */ + l["TileMatrixSetLink"][idx]["TileMatrixSet"] + ); + const matrixLimits = ( + /** @type {Array} */ + l["TileMatrixSetLink"][idx]["TileMatrixSetLimits"] + ); + let format = ( + /** @type {string} */ + l["Format"][0] + ); + if ("format" in config) { + format = config["format"]; + } + idx = l["Style"].findIndex(function(elt) { + if ("style" in config) { + return elt["Title"] == config["style"]; + } + return elt["isDefault"]; + }); + if (idx < 0) { + idx = 0; + } + const style = ( + /** @type {string} */ + l["Style"][idx]["Identifier"] + ); + const dimensions = {}; + if ("Dimension" in l) { + l["Dimension"].forEach(function(elt, index, array) { + const key = elt["Identifier"]; + let value = elt["Default"]; + if (value === void 0) { + value = elt["Value"][0]; + } + dimensions[key] = value; + }); + } + const matrixSets = wmtsCap["Contents"]["TileMatrixSet"]; + const matrixSetObj = matrixSets.find(function(elt) { + return elt["Identifier"] == matrixSet; + }); + let projection; + const code = matrixSetObj["SupportedCRS"]; + if (code) { + projection = get$1(code); + } + if ("projection" in config) { + const projConfig = get$1(config["projection"]); + if (projConfig) { + if (!projection || equivalent(projConfig, projection)) { + projection = projConfig; + } + } + } + let wrapX2 = false; + const switchXY = projection.getAxisOrientation().substr(0, 2) == "ne"; + let matrix = matrixSetObj.TileMatrix[0]; + let selectedMatrixLimit = { + MinTileCol: 0, + MinTileRow: 0, + // subtract one to end up at tile top left + MaxTileCol: matrix.MatrixWidth - 1, + MaxTileRow: matrix.MatrixHeight - 1 + }; + if (matrixLimits) { + selectedMatrixLimit = matrixLimits[matrixLimits.length - 1]; + const m = matrixSetObj.TileMatrix.find( + (tileMatrixValue) => tileMatrixValue.Identifier === selectedMatrixLimit.TileMatrix || matrixSetObj.Identifier + ":" + tileMatrixValue.Identifier === selectedMatrixLimit.TileMatrix + ); + if (m) { + matrix = m; + } + } + const resolution = matrix.ScaleDenominator * 28e-5 / projection.getMetersPerUnit(); + const origin = switchXY ? [matrix.TopLeftCorner[1], matrix.TopLeftCorner[0]] : matrix.TopLeftCorner; + const tileSpanX = matrix.TileWidth * resolution; + const tileSpanY = matrix.TileHeight * resolution; + let matrixSetExtent = matrixSetObj["BoundingBox"]; + if (matrixSetExtent && switchXY) { + matrixSetExtent = [ + matrixSetExtent[1], + matrixSetExtent[0], + matrixSetExtent[3], + matrixSetExtent[2] + ]; + } + let extent = [ + origin[0] + tileSpanX * selectedMatrixLimit.MinTileCol, + // add one to get proper bottom/right coordinate + origin[1] - tileSpanY * (1 + selectedMatrixLimit.MaxTileRow), + origin[0] + tileSpanX * (1 + selectedMatrixLimit.MaxTileCol), + origin[1] - tileSpanY * selectedMatrixLimit.MinTileRow + ]; + if (matrixSetExtent !== void 0 && !containsExtent(matrixSetExtent, extent)) { + const wgs84BoundingBox = l["WGS84BoundingBox"]; + const wgs84ProjectionExtent = get$1("EPSG:4326").getExtent(); + extent = matrixSetExtent; + if (wgs84BoundingBox) { + wrapX2 = wgs84BoundingBox[0] === wgs84ProjectionExtent[0] && wgs84BoundingBox[2] === wgs84ProjectionExtent[2]; + } else { + const wgs84MatrixSetExtent = transformExtent( + matrixSetExtent, + matrixSetObj["SupportedCRS"], + "EPSG:4326" + ); + wrapX2 = wgs84MatrixSetExtent[0] - 1e-10 <= wgs84ProjectionExtent[0] && wgs84MatrixSetExtent[2] + 1e-10 >= wgs84ProjectionExtent[2]; + } + } + const tileGrid = createFromCapabilitiesMatrixSet( + matrixSetObj, + extent, + matrixLimits + ); + const urls = []; + let requestEncoding = config["requestEncoding"]; + requestEncoding = requestEncoding !== void 0 ? requestEncoding : ""; + if ("OperationsMetadata" in wmtsCap && "GetTile" in wmtsCap["OperationsMetadata"]) { + const gets = wmtsCap["OperationsMetadata"]["GetTile"]["DCP"]["HTTP"]["Get"]; + for (let i = 0, ii = gets.length; i < ii; ++i) { + if (gets[i]["Constraint"]) { + const constraint = gets[i]["Constraint"].find(function(element) { + return element["name"] == "GetEncoding"; + }); + const encodings = constraint["AllowedValues"]["Value"]; + if (requestEncoding === "") { + requestEncoding = encodings[0]; + } + if (requestEncoding === "KVP") { + if (encodings.includes("KVP")) { + urls.push( + /** @type {string} */ + gets[i]["href"] + ); + } + } else { + break; + } + } else if (gets[i]["href"]) { + requestEncoding = "KVP"; + urls.push( + /** @type {string} */ + gets[i]["href"] + ); + } + } + } + if (urls.length === 0) { + requestEncoding = "REST"; + l["ResourceURL"].forEach(function(element) { + if (element["resourceType"] === "tile") { + format = element["format"]; + urls.push( + /** @type {string} */ + element["template"] + ); + } + }); + } + return { + urls, + layer: config["layer"], + matrixSet, + format, + projection, + requestEncoding, + tileGrid, + style, + dimensions, + wrapX: wrapX2, + crossOrigin: config["crossOrigin"] + }; +} +function getAllTextContent(node, normalizeWhitespace) { + return getAllTextContent_(node, normalizeWhitespace, []).join(""); +} +function getAllTextContent_(node, normalizeWhitespace, accumulator) { + if (node.nodeType == Node.CDATA_SECTION_NODE || node.nodeType == Node.TEXT_NODE) { + if (normalizeWhitespace) { + accumulator.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, "")); + } else { + accumulator.push(node.nodeValue); + } + } else { + let n; + for (n = node.firstChild; n; n = n.nextSibling) { + getAllTextContent_(n, normalizeWhitespace, accumulator); + } + } + return accumulator; +} +function isDocument(object) { + return "documentElement" in object; +} +function parse$1(xml) { + return new DOMParser().parseFromString(xml, "application/xml"); +} +function makeArrayPusher(valueReader, thisArg) { + return ( + /** + * @param {Element} node Node. + * @param {Array<*>} objectStack Object stack. + */ + function(node, objectStack) { + const value = valueReader.call( + thisArg !== void 0 ? thisArg : this, + node, + objectStack + ); + if (value !== void 0) { + const array = ( + /** @type {Array<*>} */ + objectStack[objectStack.length - 1] + ); + array.push(value); + } + } + ); +} +function makeObjectPropertyPusher(valueReader, property, thisArg) { + return ( + /** + * @param {Element} node Node. + * @param {Array<*>} objectStack Object stack. + */ + function(node, objectStack) { + const value = valueReader.call( + thisArg !== void 0 ? thisArg : this, + node, + objectStack + ); + if (value !== void 0) { + const object = ( + /** @type {!Object} */ + objectStack[objectStack.length - 1] + ); + const name = property !== void 0 ? property : node.localName; + let array; + if (name in object) { + array = object[name]; + } else { + array = []; + object[name] = array; + } + array.push(value); + } + } + ); +} +function makeObjectPropertySetter(valueReader, property, thisArg) { + return ( + /** + * @param {Element} node Node. + * @param {Array<*>} objectStack Object stack. + */ + function(node, objectStack) { + const value = valueReader.call( + thisArg !== void 0 ? thisArg : this, + node, + objectStack + ); + if (value !== void 0) { + const object = ( + /** @type {!Object} */ + objectStack[objectStack.length - 1] + ); + const name = property !== void 0 ? property : node.localName; + object[name] = value; + } + } + ); +} +function makeStructureNS(namespaceURIs, structure, structureNS) { + structureNS = structureNS !== void 0 ? structureNS : {}; + let i, ii; + for (i = 0, ii = namespaceURIs.length; i < ii; ++i) { + structureNS[namespaceURIs[i]] = structure; + } + return structureNS; +} +function parseNode(parsersNS, node, objectStack, thisArg) { + let n; + for (n = node.firstElementChild; n; n = n.nextElementSibling) { + const parsers2 = parsersNS[n.namespaceURI]; + if (parsers2 !== void 0) { + const parser = parsers2[n.localName]; + if (parser !== void 0) { + parser.call(thisArg, n, objectStack); + } + } + } +} +function pushParseAndPop(object, parsersNS, node, objectStack, thisArg) { + objectStack.push(object); + parseNode(parsersNS, node, objectStack, thisArg); + return ( + /** @type {T} */ + objectStack.pop() + ); +} +class XML { + /** + * Read the source document. + * + * @param {Document|Element|string} source The XML source. + * @return {Object} An object representing the source. + * @api + */ + read(source) { + if (!source) { + return null; + } + if (typeof source === "string") { + const doc = parse$1(source); + return this.readFromDocument(doc); + } + if (isDocument(source)) { + return this.readFromDocument( + /** @type {Document} */ + source + ); + } + return this.readFromNode( + /** @type {Element} */ + source + ); + } + /** + * @param {Document} doc Document. + * @return {Object} Object + */ + readFromDocument(doc) { + for (let n = doc.firstChild; n; n = n.nextSibling) { + if (n.nodeType == Node.ELEMENT_NODE) { + return this.readFromNode( + /** @type {Element} */ + n + ); + } + } + return null; + } + /** + * @abstract + * @param {Element} node Node. + * @return {Object} Object + */ + readFromNode(node) { + } +} +const XML$1 = XML; +const NAMESPACE_URI = "http://www.w3.org/1999/xlink"; +function readHref(node) { + return node.getAttributeNS(NAMESPACE_URI, "href"); +} +function readDecimal(node) { + const s = getAllTextContent(node, false); + return readDecimalString(s); +} +function readDecimalString(string) { + const m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(string); + if (m) { + return parseFloat(m[1]); + } + return void 0; +} +function readPositiveInteger(node) { + const s = getAllTextContent(node, false); + return readNonNegativeIntegerString(s); +} +function readNonNegativeIntegerString(string) { + const m = /^\s*(\d+)\s*$/.exec(string); + if (m) { + return parseInt(m[1], 10); + } + return void 0; +} +function readString(node) { + return getAllTextContent(node, false).trim(); +} +const NAMESPACE_URIS$1 = [null, "http://www.opengis.net/ows/1.1"]; +const PARSERS$1 = makeStructureNS(NAMESPACE_URIS$1, { + "ServiceIdentification": makeObjectPropertySetter(readServiceIdentification), + "ServiceProvider": makeObjectPropertySetter(readServiceProvider), + "OperationsMetadata": makeObjectPropertySetter(readOperationsMetadata) +}); +class OWS extends XML$1 { + constructor() { + super(); + } + /** + * @param {Element} node Node. + * @return {Object} Object + */ + readFromNode(node) { + const owsObject = pushParseAndPop({}, PARSERS$1, node, []); + return owsObject ? owsObject : null; + } +} +const ADDRESS_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "DeliveryPoint": makeObjectPropertySetter(readString), + "City": makeObjectPropertySetter(readString), + "AdministrativeArea": makeObjectPropertySetter(readString), + "PostalCode": makeObjectPropertySetter(readString), + "Country": makeObjectPropertySetter(readString), + "ElectronicMailAddress": makeObjectPropertySetter(readString) +}); +const ALLOWED_VALUES_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "Value": makeObjectPropertyPusher(readValue) +}); +const CONSTRAINT_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "AllowedValues": makeObjectPropertySetter(readAllowedValues) +}); +const CONTACT_INFO_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "Phone": makeObjectPropertySetter(readPhone), + "Address": makeObjectPropertySetter(readAddress) +}); +const DCP_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "HTTP": makeObjectPropertySetter(readHttp) +}); +const HTTP_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "Get": makeObjectPropertyPusher(readGet), + "Post": void 0 + // TODO +}); +const OPERATION_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "DCP": makeObjectPropertySetter(readDcp) +}); +const OPERATIONS_METADATA_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "Operation": readOperation +}); +const PHONE_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "Voice": makeObjectPropertySetter(readString), + "Facsimile": makeObjectPropertySetter(readString) +}); +const REQUEST_METHOD_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "Constraint": makeObjectPropertyPusher(readConstraint) +}); +const SERVICE_CONTACT_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "IndividualName": makeObjectPropertySetter(readString), + "PositionName": makeObjectPropertySetter(readString), + "ContactInfo": makeObjectPropertySetter(readContactInfo) +}); +const SERVICE_IDENTIFICATION_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "Abstract": makeObjectPropertySetter(readString), + "AccessConstraints": makeObjectPropertySetter(readString), + "Fees": makeObjectPropertySetter(readString), + "Title": makeObjectPropertySetter(readString), + "ServiceTypeVersion": makeObjectPropertySetter(readString), + "ServiceType": makeObjectPropertySetter(readString) +}); +const SERVICE_PROVIDER_PARSERS = makeStructureNS(NAMESPACE_URIS$1, { + "ProviderName": makeObjectPropertySetter(readString), + "ProviderSite": makeObjectPropertySetter(readHref), + "ServiceContact": makeObjectPropertySetter(readServiceContact) +}); +function readAddress(node, objectStack) { + return pushParseAndPop({}, ADDRESS_PARSERS, node, objectStack); +} +function readAllowedValues(node, objectStack) { + return pushParseAndPop({}, ALLOWED_VALUES_PARSERS, node, objectStack); +} +function readConstraint(node, objectStack) { + const name = node.getAttribute("name"); + if (!name) { + return void 0; + } + return pushParseAndPop({ "name": name }, CONSTRAINT_PARSERS, node, objectStack); +} +function readContactInfo(node, objectStack) { + return pushParseAndPop({}, CONTACT_INFO_PARSERS, node, objectStack); +} +function readDcp(node, objectStack) { + return pushParseAndPop({}, DCP_PARSERS, node, objectStack); +} +function readGet(node, objectStack) { + const href = readHref(node); + if (!href) { + return void 0; + } + return pushParseAndPop( + { "href": href }, + REQUEST_METHOD_PARSERS, + node, + objectStack + ); +} +function readHttp(node, objectStack) { + return pushParseAndPop({}, HTTP_PARSERS, node, objectStack); +} +function readOperation(node, objectStack) { + const name = node.getAttribute("name"); + const value = pushParseAndPop({}, OPERATION_PARSERS, node, objectStack); + if (!value) { + return void 0; + } + const object = ( + /** @type {Object} */ + objectStack[objectStack.length - 1] + ); + object[name] = value; +} +function readOperationsMetadata(node, objectStack) { + return pushParseAndPop({}, OPERATIONS_METADATA_PARSERS, node, objectStack); +} +function readPhone(node, objectStack) { + return pushParseAndPop({}, PHONE_PARSERS, node, objectStack); +} +function readServiceIdentification(node, objectStack) { + return pushParseAndPop({}, SERVICE_IDENTIFICATION_PARSERS, node, objectStack); +} +function readServiceContact(node, objectStack) { + return pushParseAndPop({}, SERVICE_CONTACT_PARSERS, node, objectStack); +} +function readServiceProvider(node, objectStack) { + return pushParseAndPop({}, SERVICE_PROVIDER_PARSERS, node, objectStack); +} +function readValue(node, objectStack) { + return readString(node); +} +const OWS$1 = OWS; +const NAMESPACE_URIS = [null, "http://www.opengis.net/wmts/1.0"]; +const OWS_NAMESPACE_URIS = [null, "http://www.opengis.net/ows/1.1"]; +const PARSERS = makeStructureNS(NAMESPACE_URIS, { + "Contents": makeObjectPropertySetter(readContents) +}); +class WMTSCapabilities extends XML$1 { + constructor() { + super(); + this.owsParser_ = new OWS$1(); + } + /** + * @param {Element} node Node. + * @return {Object} Object + */ + readFromNode(node) { + let version = node.getAttribute("version"); + if (version) { + version = version.trim(); + } + let WMTSCapabilityObject = this.owsParser_.readFromNode(node); + if (!WMTSCapabilityObject) { + return null; + } + WMTSCapabilityObject["version"] = version; + WMTSCapabilityObject = pushParseAndPop( + WMTSCapabilityObject, + PARSERS, + node, + [] + ); + return WMTSCapabilityObject ? WMTSCapabilityObject : null; + } +} +const CONTENTS_PARSERS = makeStructureNS(NAMESPACE_URIS, { + "Layer": makeObjectPropertyPusher(readLayer), + "TileMatrixSet": makeObjectPropertyPusher(readTileMatrixSet) +}); +const LAYER_PARSERS = makeStructureNS( + NAMESPACE_URIS, + { + "Style": makeObjectPropertyPusher(readStyle), + "Format": makeObjectPropertyPusher(readString), + "TileMatrixSetLink": makeObjectPropertyPusher(readTileMatrixSetLink), + "Dimension": makeObjectPropertyPusher(readDimensions), + "ResourceURL": makeObjectPropertyPusher(readResourceUrl) + }, + makeStructureNS(OWS_NAMESPACE_URIS, { + "Title": makeObjectPropertySetter(readString), + "Abstract": makeObjectPropertySetter(readString), + "WGS84BoundingBox": makeObjectPropertySetter(readBoundingBox), + "Identifier": makeObjectPropertySetter(readString) + }) +); +const STYLE_PARSERS = makeStructureNS( + NAMESPACE_URIS, + { + "LegendURL": makeObjectPropertyPusher(readLegendUrl) + }, + makeStructureNS(OWS_NAMESPACE_URIS, { + "Title": makeObjectPropertySetter(readString), + "Identifier": makeObjectPropertySetter(readString) + }) +); +const TMS_LINKS_PARSERS = makeStructureNS(NAMESPACE_URIS, { + "TileMatrixSet": makeObjectPropertySetter(readString), + "TileMatrixSetLimits": makeObjectPropertySetter(readTileMatrixLimitsList) +}); +const TMS_LIMITS_LIST_PARSERS = makeStructureNS(NAMESPACE_URIS, { + "TileMatrixLimits": makeArrayPusher(readTileMatrixLimits) +}); +const TMS_LIMITS_PARSERS = makeStructureNS(NAMESPACE_URIS, { + "TileMatrix": makeObjectPropertySetter(readString), + "MinTileRow": makeObjectPropertySetter(readPositiveInteger), + "MaxTileRow": makeObjectPropertySetter(readPositiveInteger), + "MinTileCol": makeObjectPropertySetter(readPositiveInteger), + "MaxTileCol": makeObjectPropertySetter(readPositiveInteger) +}); +const DIMENSION_PARSERS = makeStructureNS( + NAMESPACE_URIS, + { + "Default": makeObjectPropertySetter(readString), + "Value": makeObjectPropertyPusher(readString) + }, + makeStructureNS(OWS_NAMESPACE_URIS, { + "Identifier": makeObjectPropertySetter(readString) + }) +); +const WGS84_BBOX_READERS = makeStructureNS(OWS_NAMESPACE_URIS, { + "LowerCorner": makeArrayPusher(readCoordinates), + "UpperCorner": makeArrayPusher(readCoordinates) +}); +const TMS_PARSERS = makeStructureNS( + NAMESPACE_URIS, + { + "WellKnownScaleSet": makeObjectPropertySetter(readString), + "TileMatrix": makeObjectPropertyPusher(readTileMatrix) + }, + makeStructureNS(OWS_NAMESPACE_URIS, { + "SupportedCRS": makeObjectPropertySetter(readString), + "Identifier": makeObjectPropertySetter(readString), + "BoundingBox": makeObjectPropertySetter(readBoundingBox) + }) +); +const TM_PARSERS = makeStructureNS( + NAMESPACE_URIS, + { + "TopLeftCorner": makeObjectPropertySetter(readCoordinates), + "ScaleDenominator": makeObjectPropertySetter(readDecimal), + "TileWidth": makeObjectPropertySetter(readPositiveInteger), + "TileHeight": makeObjectPropertySetter(readPositiveInteger), + "MatrixWidth": makeObjectPropertySetter(readPositiveInteger), + "MatrixHeight": makeObjectPropertySetter(readPositiveInteger) + }, + makeStructureNS(OWS_NAMESPACE_URIS, { + "Identifier": makeObjectPropertySetter(readString) + }) +); +function readContents(node, objectStack) { + return pushParseAndPop({}, CONTENTS_PARSERS, node, objectStack); +} +function readLayer(node, objectStack) { + return pushParseAndPop({}, LAYER_PARSERS, node, objectStack); +} +function readTileMatrixSet(node, objectStack) { + return pushParseAndPop({}, TMS_PARSERS, node, objectStack); +} +function readStyle(node, objectStack) { + const style = pushParseAndPop({}, STYLE_PARSERS, node, objectStack); + if (!style) { + return void 0; + } + const isDefault = node.getAttribute("isDefault") === "true"; + style["isDefault"] = isDefault; + return style; +} +function readTileMatrixSetLink(node, objectStack) { + return pushParseAndPop({}, TMS_LINKS_PARSERS, node, objectStack); +} +function readDimensions(node, objectStack) { + return pushParseAndPop({}, DIMENSION_PARSERS, node, objectStack); +} +function readResourceUrl(node, objectStack) { + const format = node.getAttribute("format"); + const template = node.getAttribute("template"); + const resourceType = node.getAttribute("resourceType"); + const resource = {}; + if (format) { + resource["format"] = format; + } + if (template) { + resource["template"] = template; + } + if (resourceType) { + resource["resourceType"] = resourceType; + } + return resource; +} +function readBoundingBox(node, objectStack) { + const coordinates2 = pushParseAndPop( + [], + WGS84_BBOX_READERS, + node, + objectStack + ); + if (coordinates2.length != 2) { + return void 0; + } + return boundingExtent(coordinates2); +} +function readLegendUrl(node, objectStack) { + const legend = {}; + legend["format"] = node.getAttribute("format"); + legend["href"] = readHref(node); + return legend; +} +function readCoordinates(node, objectStack) { + const coordinates2 = readString(node).split(/\s+/); + if (!coordinates2 || coordinates2.length != 2) { + return void 0; + } + const x = +coordinates2[0]; + const y = +coordinates2[1]; + if (isNaN(x) || isNaN(y)) { + return void 0; + } + return [x, y]; +} +function readTileMatrix(node, objectStack) { + return pushParseAndPop({}, TM_PARSERS, node, objectStack); +} +function readTileMatrixLimitsList(node, objectStack) { + return pushParseAndPop([], TMS_LIMITS_LIST_PARSERS, node, objectStack); +} +function readTileMatrixLimits(node, objectStack) { + return pushParseAndPop({}, TMS_LIMITS_PARSERS, node, objectStack); +} +const OlFormatWmtsCapabilities = WMTSCapabilities; +let numTypes = 0; +const BooleanType = 1 << numTypes++; +const NumberType = 1 << numTypes++; +const StringType = 1 << numTypes++; +const ColorType = 1 << numTypes++; +const NumberArrayType = 1 << numTypes++; +const AnyType = Math.pow(2, numTypes) - 1; +const typeNames = { + [BooleanType]: "boolean", + [NumberType]: "number", + [StringType]: "string", + [ColorType]: "color", + [NumberArrayType]: "number[]" +}; +const namedTypes = Object.keys(typeNames).map(Number).sort(ascending); +function typeName(type) { + const names = []; + for (const namedType of namedTypes) { + if (includesType(type, namedType)) { + names.push(typeNames[namedType]); + } + } + if (names.length === 0) { + return "untyped"; + } + if (names.length < 3) { + return names.join(" or "); + } + return names.slice(0, -1).join(", ") + ", or " + names[names.length - 1]; +} +function includesType(broad, specific) { + return (broad & specific) === specific; +} +function overlapsType(oneType, otherType) { + return !!(oneType & otherType); +} +class LiteralExpression { + /** + * @param {number} type The value type. + * @param {LiteralValue} value The literal value. + */ + constructor(type, value) { + this.type = type; + this.value = value; + } +} +class CallExpression { + /** + * @param {number} type The return type. + * @param {string} operator The operator. + * @param {...Expression} args The arguments. + */ + constructor(type, operator, ...args) { + this.type = type; + this.operator = operator; + this.args = args; + } +} +function newParsingContext() { + return { + variables: /* @__PURE__ */ new Set(), + properties: /* @__PURE__ */ new Set() + }; +} +function parse(encoded, context) { + switch (typeof encoded) { + case "boolean": { + return new LiteralExpression(BooleanType, encoded); + } + case "number": { + return new LiteralExpression(NumberType, encoded); + } + case "string": { + return new LiteralExpression(StringType, encoded); + } + } + if (!Array.isArray(encoded)) { + throw new Error("Expression must be an array or a primitive value"); + } + if (encoded.length === 0) { + throw new Error("Empty expression"); + } + if (typeof encoded[0] === "string") { + return parseCallExpression(encoded, context); + } + for (const item of encoded) { + if (typeof item !== "number") { + throw new Error("Expected an array of numbers"); + } + } + let type = NumberArrayType; + if (encoded.length === 3 || encoded.length === 4) { + type |= ColorType; + } + return new LiteralExpression(type, encoded); +} +const Ops = { + Number: "number", + String: "string", + Get: "get", + Var: "var", + Any: "any", + All: "all", + Not: "!", + Resolution: "resolution", + Equal: "==", + NotEqual: "!=", + GreaterThan: ">", + GreaterThanOrEqualTo: ">=", + LessThan: "<", + LessThanOrEqualTo: "<=", + Multiply: "*", + Divide: "/", + Add: "+", + Subtract: "-", + Clamp: "clamp", + Mod: "%", + Pow: "^", + Abs: "abs", + Floor: "floor", + Ceil: "ceil", + Round: "round", + Sin: "sin", + Cos: "cos", + Atan: "atan", + Sqrt: "sqrt", + Match: "match" +}; +const parsers = { + [Ops.Number]: createParser(withArgs(1, Infinity, AnyType), NumberType), + [Ops.String]: createParser(withArgs(1, Infinity, AnyType), StringType), + [Ops.Get]: createParser(withGetArgs, AnyType), + [Ops.Var]: createParser(withVarArgs, AnyType), + [Ops.Resolution]: createParser(withNoArgs, NumberType), + [Ops.Any]: createParser(withArgs(2, Infinity, BooleanType), BooleanType), + [Ops.All]: createParser(withArgs(2, Infinity, BooleanType), BooleanType), + [Ops.Not]: createParser(withArgs(1, 1, BooleanType), BooleanType), + [Ops.Equal]: createParser(withArgs(2, 2, AnyType), BooleanType), + [Ops.NotEqual]: createParser(withArgs(2, 2, AnyType), BooleanType), + [Ops.GreaterThan]: createParser(withArgs(2, 2, AnyType), BooleanType), + [Ops.GreaterThanOrEqualTo]: createParser( + withArgs(2, 2, AnyType), + BooleanType + ), + [Ops.LessThan]: createParser(withArgs(2, 2, AnyType), BooleanType), + [Ops.LessThanOrEqualTo]: createParser(withArgs(2, 2, AnyType), BooleanType), + [Ops.Multiply]: createParser(withArgs(2, Infinity, NumberType), NumberType), + [Ops.Divide]: createParser(withArgs(2, 2, NumberType), NumberType), + [Ops.Add]: createParser(withArgs(2, Infinity, NumberType), NumberType), + [Ops.Subtract]: createParser(withArgs(2, 2, NumberType), NumberType), + [Ops.Clamp]: createParser(withArgs(3, 3, NumberType), NumberType), + [Ops.Mod]: createParser(withArgs(2, 2, NumberType), NumberType), + [Ops.Pow]: createParser(withArgs(2, 2, NumberType), NumberType), + [Ops.Abs]: createParser(withArgs(1, 1, NumberType), NumberType), + [Ops.Floor]: createParser(withArgs(1, 1, NumberType), NumberType), + [Ops.Ceil]: createParser(withArgs(1, 1, NumberType), NumberType), + [Ops.Round]: createParser(withArgs(1, 1, NumberType), NumberType), + [Ops.Sin]: createParser(withArgs(1, 1, NumberType), NumberType), + [Ops.Cos]: createParser(withArgs(1, 1, NumberType), NumberType), + [Ops.Atan]: createParser(withArgs(1, 2, NumberType), NumberType), + [Ops.Sqrt]: createParser(withArgs(1, 1, NumberType), NumberType), + [Ops.Match]: createParser( + withArgs(4, Infinity, StringType | NumberType), + AnyType + ) +}; +function withGetArgs(encoded, context) { + if (encoded.length !== 2) { + throw new Error("Expected 1 argument for get operation"); + } + const arg = parse(encoded[1], context); + if (!(arg instanceof LiteralExpression)) { + throw new Error("Expected a literal argument for get operation"); + } + if (typeof arg.value !== "string") { + throw new Error("Expected a string argument for get operation"); + } + context.properties.add(arg.value); + return [arg]; +} +function withVarArgs(encoded, context) { + if (encoded.length !== 2) { + throw new Error("Expected 1 argument for var operation"); + } + const arg = parse(encoded[1], context); + if (!(arg instanceof LiteralExpression)) { + throw new Error("Expected a literal argument for var operation"); + } + if (typeof arg.value !== "string") { + throw new Error("Expected a string argument for get operation"); + } + context.variables.add(arg.value); + return [arg]; +} +function withNoArgs(encoded, context) { + const operation = encoded[0]; + if (encoded.length !== 1) { + throw new Error(`Expected no arguments for ${operation} operation`); + } + return []; +} +function withArgs(minArgs, maxArgs, argType) { + return function(encoded, context) { + const operation = encoded[0]; + const argCount = encoded.length - 1; + if (minArgs === maxArgs) { + if (argCount !== minArgs) { + const plural = minArgs === 1 ? "" : "s"; + throw new Error( + `Expected ${minArgs} argument${plural} for operation ${operation}, got ${argCount}` + ); + } + } else if (argCount < minArgs || argCount > maxArgs) { + throw new Error( + `Expected ${minArgs} to ${maxArgs} arguments for operation ${operation}, got ${argCount}` + ); + } + const args = new Array(argCount); + for (let i = 0; i < argCount; ++i) { + const expression = parse(encoded[i + 1], context); + if (!overlapsType(argType, expression.type)) { + const gotType = typeName(argType); + const expectedType = typeName(expression.type); + throw new Error( + `Unexpected type for argument ${i} of ${operation} operation : got ${gotType} but expected ${expectedType}` + ); + } + args[i] = expression; + } + return args; + }; +} +function createParser(argValidator, returnType) { + return function(encoded, context) { + const operator = encoded[0]; + const args = argValidator(encoded, context); + return new CallExpression(returnType, operator, ...args); + }; +} +function parseCallExpression(encoded, context) { + const operator = encoded[0]; + const parser = parsers[operator]; + if (!parser) { + throw new Error(`Unknown operator: ${operator}`); + } + return parser(encoded, context); +} +function newEvaluationContext() { + return { + variables: {}, + properties: {}, + resolution: NaN + }; +} +function buildExpression(encoded, type, context) { + const expression = parse(encoded, context); + if (!overlapsType(type, expression.type)) { + const expected = typeName(type); + const actual = typeName(expression.type); + throw new Error( + `Expected expression to be of type ${expected}, got ${actual}` + ); + } + return compileExpression(expression); +} +function compileExpression(expression, context) { + if (expression instanceof LiteralExpression) { + return function() { + return expression.value; + }; + } + const operator = expression.operator; + switch (operator) { + case Ops.Number: + case Ops.String: { + return compileAssertionExpression(expression); + } + case Ops.Get: + case Ops.Var: { + return compileAccessorExpression(expression); + } + case Ops.Resolution: { + return (context2) => context2.resolution; + } + case Ops.Any: + case Ops.All: + case Ops.Not: { + return compileLogicalExpression(expression); + } + case Ops.Equal: + case Ops.NotEqual: + case Ops.LessThan: + case Ops.LessThanOrEqualTo: + case Ops.GreaterThan: + case Ops.GreaterThanOrEqualTo: { + return compileComparisonExpression(expression); + } + case Ops.Multiply: + case Ops.Divide: + case Ops.Add: + case Ops.Subtract: + case Ops.Clamp: + case Ops.Mod: + case Ops.Pow: + case Ops.Abs: + case Ops.Floor: + case Ops.Ceil: + case Ops.Round: + case Ops.Sin: + case Ops.Cos: + case Ops.Atan: + case Ops.Sqrt: { + return compileNumericExpression(expression); + } + case Ops.Match: { + return compileMatchExpression(expression); + } + default: { + throw new Error(`Unsupported operator ${operator}`); + } + } +} +function compileAssertionExpression(expression, context) { + const type = expression.operator; + const length = expression.args.length; + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i]); + } + switch (type) { + case Ops.Number: + case Ops.String: { + return (context2) => { + for (let i = 0; i < length; ++i) { + const value = args[i](context2); + if (typeof value === type) { + return value; + } + } + throw new Error(`Expected one of the values to be a ${type}`); + }; + } + default: { + throw new Error(`Unsupported assertion operator ${type}`); + } + } +} +function compileAccessorExpression(expression, context) { + const nameExpression = expression.args[0]; + if (!(nameExpression instanceof LiteralExpression)) { + throw new Error("Expected literal name"); + } + const name = nameExpression.value; + if (typeof name !== "string") { + throw new Error("Expected string name"); + } + switch (expression.operator) { + case Ops.Get: { + return (context2) => context2.properties[name]; + } + case Ops.Var: { + return (context2) => context2.variables[name]; + } + default: { + throw new Error(`Unsupported accessor operator ${expression.operator}`); + } + } +} +function compileComparisonExpression(expression, context) { + const op = expression.operator; + const left = compileExpression(expression.args[0]); + const right = compileExpression(expression.args[1]); + switch (op) { + case Ops.Equal: { + return (context2) => left(context2) === right(context2); + } + case Ops.NotEqual: { + return (context2) => left(context2) !== right(context2); + } + case Ops.LessThan: { + return (context2) => left(context2) < right(context2); + } + case Ops.LessThanOrEqualTo: { + return (context2) => left(context2) <= right(context2); + } + case Ops.GreaterThan: { + return (context2) => left(context2) > right(context2); + } + case Ops.GreaterThanOrEqualTo: { + return (context2) => left(context2) >= right(context2); + } + default: { + throw new Error(`Unsupported comparison operator ${op}`); + } + } +} +function compileLogicalExpression(expression, context) { + const op = expression.operator; + const length = expression.args.length; + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i]); + } + switch (op) { + case Ops.Any: { + return (context2) => { + for (let i = 0; i < length; ++i) { + if (args[i](context2)) { + return true; + } + } + return false; + }; + } + case Ops.All: { + return (context2) => { + for (let i = 0; i < length; ++i) { + if (!args[i](context2)) { + return false; + } + } + return true; + }; + } + case Ops.Not: { + return (context2) => !args[0](context2); + } + default: { + throw new Error(`Unsupported logical operator ${op}`); + } + } +} +function compileNumericExpression(expression, context) { + const op = expression.operator; + const length = expression.args.length; + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i]); + } + switch (op) { + case Ops.Multiply: { + return (context2) => { + let value = 1; + for (let i = 0; i < length; ++i) { + value *= args[i](context2); + } + return value; + }; + } + case Ops.Divide: { + return (context2) => args[0](context2) / args[1](context2); + } + case Ops.Add: { + return (context2) => { + let value = 0; + for (let i = 0; i < length; ++i) { + value += args[i](context2); + } + return value; + }; + } + case Ops.Subtract: { + return (context2) => args[0](context2) - args[1](context2); + } + case Ops.Clamp: { + return (context2) => { + const value = args[0](context2); + const min = args[1](context2); + if (value < min) { + return min; + } + const max = args[2](context2); + if (value > max) { + return max; + } + return value; + }; + } + case Ops.Mod: { + return (context2) => args[0](context2) % args[1](context2); + } + case Ops.Pow: { + return (context2) => Math.pow(args[0](context2), args[1](context2)); + } + case Ops.Abs: { + return (context2) => Math.abs(args[0](context2)); + } + case Ops.Floor: { + return (context2) => Math.floor(args[0](context2)); + } + case Ops.Ceil: { + return (context2) => Math.ceil(args[0](context2)); + } + case Ops.Round: { + return (context2) => Math.round(args[0](context2)); + } + case Ops.Sin: { + return (context2) => Math.sin(args[0](context2)); + } + case Ops.Cos: { + return (context2) => Math.cos(args[0](context2)); + } + case Ops.Atan: { + if (length === 2) { + return (context2) => Math.atan2(args[0](context2), args[1](context2)); + } + return (context2) => Math.atan(args[0](context2)); + } + case Ops.Sqrt: { + return (context2) => Math.sqrt(args[0](context2)); + } + default: { + throw new Error(`Unsupported numeric operator ${op}`); + } + } +} +function compileMatchExpression(expression, context) { + const length = expression.args.length; + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i]); + } + return (context2) => { + const value = args[0](context2); + for (let i = 1; i < length; i += 2) { + if (value === args[i](context2)) { + return args[i + 1](context2); + } + } + return args[length - 1](context2); + }; +} +function always(context) { + return true; +} +function rulesToStyleFunction(rules) { + const parsingContext = newParsingContext(); + const evaluator = buildRuleSet(rules, parsingContext); + const evaluationContext = newEvaluationContext(); + return function(feature, resolution) { + evaluationContext.properties = feature.getPropertiesInternal(); + evaluationContext.resolution = resolution; + return evaluator(evaluationContext); + }; +} +function flatStylesToStyleFunction(flatStyles) { + const parsingContext = newParsingContext(); + const length = flatStyles.length; + const evaluators = new Array(length); + for (let i = 0; i < length; ++i) { + evaluators[i] = buildStyle(flatStyles[i], parsingContext); + } + const evaluationContext = newEvaluationContext(); + const styles = new Array(length); + return function(feature, resolution) { + evaluationContext.properties = feature.getPropertiesInternal(); + evaluationContext.resolution = resolution; + for (let i = 0; i < length; ++i) { + styles[i] = evaluators[i](evaluationContext); + } + return styles; + }; +} +function buildRuleSet(rules, context) { + const length = rules.length; + const compiledRules = new Array(length); + for (let i = 0; i < length; ++i) { + const rule = rules[i]; + const filter = "filter" in rule ? buildExpression(rule.filter, BooleanType, context) : always; + let styles; + if (Array.isArray(rule.style)) { + const styleLength = rule.style.length; + styles = new Array(styleLength); + for (let j = 0; j < styleLength; ++j) { + styles[j] = buildStyle(rule.style[j], context); + } + } else { + styles = [buildStyle(rule.style, context)]; + } + compiledRules[i] = { filter, styles }; + } + return function(context2) { + const styles = []; + let someMatched = false; + for (let i = 0; i < length; ++i) { + const filterEvaluator = compiledRules[i].filter; + if (!filterEvaluator(context2)) { + continue; + } + if (rules[i].else && someMatched) { + continue; + } + someMatched = true; + for (const styleEvaluator of compiledRules[i].styles) { + const style = styleEvaluator(context2); + if (!style) { + continue; + } + styles.push(style); + } + } + return styles; + }; +} +function buildStyle(flatStyle, context) { + const evaluateFill = buildFill(flatStyle, "", context); + const evaluateStroke = buildStroke(flatStyle, "", context); + const evaluateText = buildText(flatStyle, context); + const evaluateImage = buildImage(flatStyle, context); + const evaluateZIndex = numberEvaluator(flatStyle, "z-index", context); + const style = new Style(); + return function(context2) { + let empty = true; + if (evaluateFill) { + const fill = evaluateFill(context2); + if (fill) { + empty = false; + } + style.setFill(fill); + } + if (evaluateStroke) { + const stroke = evaluateStroke(context2); + if (stroke) { + empty = false; + } + style.setStroke(stroke); + } + if (evaluateText) { + const text = evaluateText(context2); + if (text) { + empty = false; + } + style.setText(text); + } + if (evaluateImage) { + const image = evaluateImage(context2); + if (image) { + empty = false; + } + style.setImage(image); + } + if (evaluateZIndex) { + style.setZIndex(evaluateZIndex(context2)); + } + if (empty) { + return null; + } + return style; + }; +} +function buildFill(flatStyle, prefix, context) { + const evaluateColor = colorLikeEvaluator( + flatStyle, + prefix + "fill-color", + context + ); + if (!evaluateColor) { + return null; + } + const fill = new Fill$1(); + return function(context2) { + const color = evaluateColor(context2); + if (color === "none") { + return null; + } + fill.setColor(color); + return fill; + }; +} +function buildStroke(flatStyle, prefix, context) { + const evaluateWidth = numberEvaluator( + flatStyle, + prefix + "stroke-width", + context + ); + const evaluateColor = colorLikeEvaluator( + flatStyle, + prefix + "stroke-color", + context + ); + if (!evaluateWidth && !evaluateColor) { + return null; + } + const evaluateLineCap = stringEvaluator( + flatStyle, + prefix + "stroke-line-cap", + context + ); + const evaluateLineJoin = stringEvaluator( + flatStyle, + prefix + "stroke-line-join", + context + ); + const evaluateLineDash = numberArrayEvaluator( + flatStyle, + prefix + "stroke-line-dash", + context + ); + const evaluateLineDashOffset = numberEvaluator( + flatStyle, + prefix + "stroke-line-dash-offset", + context + ); + const evaluateMiterLimit = numberEvaluator( + flatStyle, + prefix + "stroke-miter-limit", + context + ); + const stroke = new OlStroke(); + return function(context2) { + if (evaluateColor) { + const color = evaluateColor(context2); + if (color === "none") { + return null; + } + stroke.setColor(color); + } + if (evaluateWidth) { + stroke.setWidth(evaluateWidth(context2)); + } + if (evaluateLineCap) { + const lineCap = evaluateLineCap(context2); + if (lineCap !== "butt" && lineCap !== "round" && lineCap !== "square") { + throw new Error("Expected butt, round, or square line cap"); + } + stroke.setLineCap(lineCap); + } + if (evaluateLineJoin) { + const lineJoin = evaluateLineJoin(context2); + if (lineJoin !== "bevel" && lineJoin !== "round" && lineJoin !== "miter") { + throw new Error("Expected bevel, round, or miter line join"); + } + stroke.setLineJoin(lineJoin); + } + if (evaluateLineDash) { + stroke.setLineDash(evaluateLineDash(context2)); + } + if (evaluateLineDashOffset) { + stroke.setLineDashOffset(evaluateLineDashOffset(context2)); + } + if (evaluateMiterLimit) { + stroke.setMiterLimit(evaluateMiterLimit(context2)); + } + return stroke; + }; +} +function buildText(flatStyle, context) { + const prefix = "text-"; + const evaluateValue = stringEvaluator(flatStyle, prefix + "value", context); + if (!evaluateValue) { + return null; + } + const evaluateFill = buildFill(flatStyle, prefix, context); + const evaluateBackgroundFill = buildFill( + flatStyle, + prefix + "background-", + context + ); + const evaluateStroke = buildStroke(flatStyle, prefix, context); + const evaluateBackgroundStroke = buildStroke( + flatStyle, + prefix + "background-", + context + ); + const evaluateFont = stringEvaluator(flatStyle, prefix + "font", context); + const evaluateMaxAngle = numberEvaluator( + flatStyle, + prefix + "max-angle", + context + ); + const evaluateOffsetX = numberEvaluator( + flatStyle, + prefix + "offset-x", + context + ); + const evaluateOffsetY = numberEvaluator( + flatStyle, + prefix + "offset-y", + context + ); + const evaluateOverflow = booleanEvaluator( + flatStyle, + prefix + "overflow", + context + ); + const evaluatePlacement = stringEvaluator( + flatStyle, + prefix + "placement", + context + ); + const evaluateRepeat = numberEvaluator(flatStyle, prefix + "repeat", context); + const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + "scale", context); + const evaluateRotateWithView = booleanEvaluator( + flatStyle, + prefix + "rotate-with-view", + context + ); + const evaluateRotation = numberEvaluator( + flatStyle, + prefix + "rotation", + context + ); + const evaluateAlign = stringEvaluator(flatStyle, prefix + "align", context); + const evaluateJustify = stringEvaluator( + flatStyle, + prefix + "justify", + context + ); + const evaluateBaseline = stringEvaluator( + flatStyle, + prefix + "baseline", + context + ); + const evaluatePadding = numberArrayEvaluator( + flatStyle, + prefix + "padding", + context + ); + const text = new OlText({}); + return function(context2) { + text.setText(evaluateValue(context2)); + if (evaluateFill) { + text.setFill(evaluateFill(context2)); + } + if (evaluateBackgroundFill) { + text.setBackgroundFill(evaluateBackgroundFill(context2)); + } + if (evaluateStroke) { + text.setStroke(evaluateStroke(context2)); + } + if (evaluateBackgroundStroke) { + text.setBackgroundStroke(evaluateBackgroundStroke(context2)); + } + if (evaluateFont) { + text.setFont(evaluateFont(context2)); + } + if (evaluateMaxAngle) { + text.setMaxAngle(evaluateMaxAngle(context2)); + } + if (evaluateOffsetX) { + text.setOffsetX(evaluateOffsetX(context2)); + } + if (evaluateOffsetY) { + text.setOffsetY(evaluateOffsetY(context2)); + } + if (evaluateOverflow) { + text.setOverflow(evaluateOverflow(context2)); + } + if (evaluatePlacement) { + const placement = evaluatePlacement(context2); + if (placement !== "point" && placement !== "line") { + throw new Error("Expected point or line for text-placement"); + } + text.setPlacement(placement); + } + if (evaluateRepeat) { + text.setRepeat(evaluateRepeat(context2)); + } + if (evaluateScale) { + text.setScale(evaluateScale(context2)); + } + if (evaluateRotateWithView) { + text.setRotateWithView(evaluateRotateWithView(context2)); + } + if (evaluateRotation) { + text.setRotation(evaluateRotation(context2)); + } + if (evaluateAlign) { + const textAlign = evaluateAlign(context2); + if (textAlign !== "left" && textAlign !== "center" && textAlign !== "right" && textAlign !== "end" && textAlign !== "start") { + throw new Error( + "Expected left, right, center, start, or end for text-align" + ); + } + text.setTextAlign(textAlign); + } + if (evaluateJustify) { + const justify = evaluateJustify(context2); + if (justify !== "left" && justify !== "right" && justify !== "center") { + throw new Error("Expected left, right, or center for text-justify"); + } + text.setJustify(justify); + } + if (evaluateBaseline) { + const textBaseline = evaluateBaseline(context2); + if (textBaseline !== "bottom" && textBaseline !== "top" && textBaseline !== "middle" && textBaseline !== "alphabetic" && textBaseline !== "hanging") { + throw new Error( + "Expected bottom, top, middle, alphabetic, or hanging for text-baseline" + ); + } + text.setTextBaseline(textBaseline); + } + if (evaluatePadding) { + text.setPadding(evaluatePadding(context2)); + } + return text; + }; +} +function buildImage(flatStyle, context) { + if ("icon-src" in flatStyle) { + return buildIcon(flatStyle, context); + } + if ("shape-points" in flatStyle) { + return buildShape(flatStyle, context); + } + if ("circle-radius" in flatStyle) { + return buildCircle(flatStyle, context); + } + return null; +} +function buildIcon(flatStyle, context) { + const prefix = "icon-"; + const srcName = prefix + "src"; + const src = requireString(flatStyle[srcName], srcName); + const evaluateAnchor = coordinateEvaluator( + flatStyle, + prefix + "anchor", + context + ); + const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + "scale", context); + const evaluateOpacity = numberEvaluator( + flatStyle, + prefix + "opacity", + context + ); + const evaluateDisplacement = coordinateEvaluator( + flatStyle, + prefix + "displacement", + context + ); + const evaluateRotation = numberEvaluator( + flatStyle, + prefix + "rotation", + context + ); + const evaluateRotateWithView = booleanEvaluator( + flatStyle, + prefix + "rotate-with-view", + context + ); + const anchorOrigin = optionalIconOrigin(flatStyle, prefix + "anchor-origin"); + const anchorXUnits = optionalIconAnchorUnits( + flatStyle, + prefix + "anchor-x-units" + ); + const anchorYUnits = optionalIconAnchorUnits( + flatStyle, + prefix + "anchor-y-units" + ); + const color = optionalColorLike(flatStyle, prefix + "color"); + const crossOrigin = optionalString(flatStyle, prefix + "cross-origin"); + const offset = optionalNumberArray(flatStyle, prefix + "offset"); + const offsetOrigin = optionalIconOrigin(flatStyle, prefix + "offset-origin"); + const width = optionalNumber(flatStyle, prefix + "width"); + const height = optionalNumber(flatStyle, prefix + "height"); + const size = optionalSize(flatStyle, prefix + "size"); + const declutterMode = optionalDeclutterMode(flatStyle, prefix + "declutter"); + const icon = new OlIcon({ + src, + anchorOrigin, + anchorXUnits, + anchorYUnits, + color, + crossOrigin, + offset, + offsetOrigin, + height, + width, + size, + declutterMode + }); + return function(context2) { + if (evaluateOpacity) { + icon.setOpacity(evaluateOpacity(context2)); + } + if (evaluateDisplacement) { + icon.setDisplacement(evaluateDisplacement(context2)); + } + if (evaluateRotation) { + icon.setRotation(evaluateRotation(context2)); + } + if (evaluateRotateWithView) { + icon.setRotateWithView(evaluateRotateWithView(context2)); + } + if (evaluateScale) { + icon.setScale(evaluateScale(context2)); + } + if (evaluateAnchor) { + icon.setAnchor(evaluateAnchor(context2)); + } + return icon; + }; +} +function buildShape(flatStyle, context) { + const prefix = "shape-"; + const pointsName = prefix + "points"; + const points = requireNumber(flatStyle[pointsName], pointsName); + const evaluateFill = buildFill(flatStyle, prefix, context); + const evaluateStroke = buildStroke(flatStyle, prefix, context); + const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + "scale", context); + const evaluateDisplacement = coordinateEvaluator( + flatStyle, + prefix + "displacement", + context + ); + const evaluateRotation = numberEvaluator( + flatStyle, + prefix + "rotation", + context + ); + const evaluateRotateWithView = booleanEvaluator( + flatStyle, + prefix + "rotate-with-view", + context + ); + const radius = optionalNumber(flatStyle, prefix + "radius"); + const radius1 = optionalNumber(flatStyle, prefix + "radius1"); + const radius2 = optionalNumber(flatStyle, prefix + "radius2"); + const angle = optionalNumber(flatStyle, prefix + "angle"); + const declutterMode = optionalDeclutterMode( + flatStyle, + prefix + "declutter-mode" + ); + const shape = new RegularShape$1({ + points, + radius, + radius1, + radius2, + angle, + declutterMode + }); + return function(context2) { + if (evaluateFill) { + shape.setFill(evaluateFill(context2)); + } + if (evaluateStroke) { + shape.setStroke(evaluateStroke(context2)); + } + if (evaluateDisplacement) { + shape.setDisplacement(evaluateDisplacement(context2)); + } + if (evaluateRotation) { + shape.setRotation(evaluateRotation(context2)); + } + if (evaluateRotateWithView) { + shape.setRotateWithView(evaluateRotateWithView(context2)); + } + if (evaluateScale) { + shape.setScale(evaluateScale(context2)); + } + return shape; + }; +} +function buildCircle(flatStyle, context) { + const prefix = "circle-"; + const evaluateFill = buildFill(flatStyle, prefix, context); + const evaluateStroke = buildStroke(flatStyle, prefix, context); + const evaluateRadius = numberEvaluator(flatStyle, prefix + "radius", context); + const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + "scale", context); + const evaluateDisplacement = coordinateEvaluator( + flatStyle, + prefix + "displacement", + context + ); + const evaluateRotation = numberEvaluator( + flatStyle, + prefix + "rotation", + context + ); + const evaluateRotateWithView = booleanEvaluator( + flatStyle, + prefix + "rotate-with-view", + context + ); + const declutterMode = optionalDeclutterMode( + flatStyle, + prefix + "declutter-mode" + ); + const circle = new Circle({ + radius: 5, + // this is arbitrary, but required - the evaluated radius is used below + declutterMode + }); + return function(context2) { + if (evaluateRadius) { + circle.setRadius(evaluateRadius(context2)); + } + if (evaluateFill) { + circle.setFill(evaluateFill(context2)); + } + if (evaluateStroke) { + circle.setStroke(evaluateStroke(context2)); + } + if (evaluateDisplacement) { + circle.setDisplacement(evaluateDisplacement(context2)); + } + if (evaluateRotation) { + circle.setRotation(evaluateRotation(context2)); + } + if (evaluateRotateWithView) { + circle.setRotateWithView(evaluateRotateWithView(context2)); + } + if (evaluateScale) { + circle.setScale(evaluateScale(context2)); + } + return circle; + }; +} +function numberEvaluator(flatStyle, name, context) { + if (!(name in flatStyle)) { + return void 0; + } + const evaluator = buildExpression(flatStyle[name], NumberType, context); + return function(context2) { + return requireNumber(evaluator(context2), name); + }; +} +function stringEvaluator(flatStyle, name, context) { + if (!(name in flatStyle)) { + return null; + } + const evaluator = buildExpression(flatStyle[name], StringType, context); + return function(context2) { + return requireString(evaluator(context2), name); + }; +} +function booleanEvaluator(flatStyle, name, context) { + if (!(name in flatStyle)) { + return null; + } + const evaluator = buildExpression(flatStyle[name], BooleanType, context); + return function(context2) { + const value = evaluator(context2); + if (typeof value !== "boolean") { + throw new Error(`Expected a boolean for ${name}`); + } + return value; + }; +} +function colorLikeEvaluator(flatStyle, name, context) { + if (!(name in flatStyle)) { + return null; + } + const evaluator = buildExpression( + flatStyle[name], + ColorType | StringType, + context + ); + return function(context2) { + return requireColorLike(evaluator(context2), name); + }; +} +function numberArrayEvaluator(flatStyle, name, context) { + if (!(name in flatStyle)) { + return null; + } + const evaluator = buildExpression(flatStyle[name], NumberArrayType, context); + return function(context2) { + return requireNumberArray(evaluator(context2), name); + }; +} +function coordinateEvaluator(flatStyle, name, context) { + if (!(name in flatStyle)) { + return null; + } + const evaluator = buildExpression(flatStyle[name], NumberArrayType, context); + return function(context2) { + const array = requireNumberArray(evaluator(context2), name); + if (array.length !== 2) { + throw new Error(`Expected two numbers for ${name}`); + } + return array; + }; +} +function sizeLikeEvaluator(flatStyle, name, context) { + if (!(name in flatStyle)) { + return null; + } + const evaluator = buildExpression( + flatStyle[name], + NumberArrayType | NumberType, + context + ); + return function(context2) { + return requireSizeLike(evaluator(context2), name); + }; +} +function optionalNumber(flatStyle, property) { + const value = flatStyle[property]; + if (value === void 0) { + return void 0; + } + if (typeof value !== "number") { + throw new Error(`Expected a number for ${property}`); + } + return value; +} +function optionalSize(flatStyle, property) { + const encoded = flatStyle[property]; + if (encoded === void 0) { + return void 0; + } + if (typeof encoded === "number") { + return toSize(encoded); + } + if (!Array.isArray(encoded)) { + throw new Error(`Expected a number or size array for ${property}`); + } + if (encoded.length !== 2 || typeof encoded[0] !== "number" || typeof encoded[1] !== "number") { + throw new Error(`Expected a number or size array for ${property}`); + } + return encoded; +} +function optionalString(flatStyle, property) { + const encoded = flatStyle[property]; + if (encoded === void 0) { + return void 0; + } + if (typeof encoded !== "string") { + throw new Error(`Expected a string for ${property}`); + } + return encoded; +} +function optionalIconOrigin(flatStyle, property) { + const encoded = flatStyle[property]; + if (encoded === void 0) { + return void 0; + } + if (encoded !== "bottom-left" && encoded !== "bottom-right" && encoded !== "top-left" && encoded !== "top-right") { + throw new Error( + `Expected bottom-left, bottom-right, top-left, or top-right for ${property}` + ); + } + return encoded; +} +function optionalIconAnchorUnits(flatStyle, property) { + const encoded = flatStyle[property]; + if (encoded === void 0) { + return void 0; + } + if (encoded !== "pixels" && encoded !== "fraction") { + throw new Error(`Expected pixels or fraction for ${property}`); + } + return encoded; +} +function optionalNumberArray(flatStyle, property) { + const encoded = flatStyle[property]; + if (encoded === void 0) { + return void 0; + } + return requireNumberArray(encoded, property); +} +function optionalDeclutterMode(flatStyle, property) { + const encoded = flatStyle[property]; + if (encoded === void 0) { + return void 0; + } + if (typeof encoded !== "string") { + throw new Error(`Expected a string for ${property}`); + } + if (encoded !== "declutter" && encoded !== "obstacle" && encoded !== "none") { + throw new Error(`Expected declutter, obstacle, or none for ${property}`); + } + return encoded; +} +function optionalColorLike(flatStyle, property) { + const encoded = flatStyle[property]; + if (encoded === void 0) { + return void 0; + } + return requireColorLike(encoded, property); +} +function requireNumberArray(value, property) { + if (!Array.isArray(value)) { + throw new Error(`Expected an array for ${property}`); + } + const length = value.length; + for (let i = 0; i < length; ++i) { + if (typeof value[i] !== "number") { + throw new Error(`Expected an array of numbers for ${property}`); + } + } + return value; +} +function requireString(value, property) { + if (typeof value !== "string") { + throw new Error(`Expected a string for ${property}`); + } + return value; +} +function requireNumber(value, property) { + if (typeof value !== "number") { + throw new Error(`Expected a number for ${property}`); + } + return value; +} +function requireColorLike(value, property) { + if (typeof value === "string") { + return value; + } + const array = requireNumberArray(value, property); + const length = array.length; + if (length < 3 || length > 4) { + throw new Error(`Expected a color with 3 or 4 values for ${property}`); + } + return array; +} +function requireSizeLike(value, property) { + if (typeof value === "number") { + return value; + } + const size = requireNumberArray(value, property); + if (size.length !== 2) { + throw new Error(`Expected an array of two numbers for ${property}`); + } + return size; +} +const Property = { + RENDER_ORDER: "renderOrder" +}; +class BaseVectorLayer extends Layer$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + const baseOptions = Object.assign({}, options); + delete baseOptions.style; + delete baseOptions.renderBuffer; + delete baseOptions.updateWhileAnimating; + delete baseOptions.updateWhileInteracting; + super(baseOptions); + this.declutter_ = options.declutter !== void 0 ? options.declutter : false; + this.renderBuffer_ = options.renderBuffer !== void 0 ? options.renderBuffer : 100; + this.style_ = null; + this.styleFunction_ = void 0; + this.setStyle(options.style); + this.updateWhileAnimating_ = options.updateWhileAnimating !== void 0 ? options.updateWhileAnimating : false; + this.updateWhileInteracting_ = options.updateWhileInteracting !== void 0 ? options.updateWhileInteracting : false; + } + /** + * @return {boolean} Declutter. + */ + getDeclutter() { + return this.declutter_; + } + /** + * Get the topmost feature that intersects the given pixel on the viewport. Returns a promise + * that resolves with an array of features. The array will either contain the topmost feature + * when a hit was detected, or it will be empty. + * + * The hit detection algorithm used for this method is optimized for performance, but is less + * accurate than the one used in [map.getFeaturesAtPixel()]{@link import("../Map.js").default#getFeaturesAtPixel}. + * Text is not considered, and icons are only represented by their bounding box instead of the exact + * image. + * + * @param {import("../pixel.js").Pixel} pixel Pixel. + * @return {Promise>} Promise that resolves with an array of features. + * @api + */ + getFeatures(pixel) { + return super.getFeatures(pixel); + } + /** + * @return {number|undefined} Render buffer. + */ + getRenderBuffer() { + return this.renderBuffer_; + } + /** + * @return {function(import("../Feature.js").default, import("../Feature.js").default): number|null|undefined} Render + * order. + */ + getRenderOrder() { + return ( + /** @type {import("../render.js").OrderFunction|null|undefined} */ + this.get(Property.RENDER_ORDER) + ); + } + /** + * Get the style for features. This returns whatever was passed to the `style` + * option at construction or to the `setStyle` method. + * @return {import("../style/Style.js").StyleLike|null|undefined} Layer style. + * @api + */ + getStyle() { + return this.style_; + } + /** + * Get the style function. + * @return {import("../style/Style.js").StyleFunction|undefined} Layer style function. + * @api + */ + getStyleFunction() { + return this.styleFunction_; + } + /** + * @return {boolean} Whether the rendered layer should be updated while + * animating. + */ + getUpdateWhileAnimating() { + return this.updateWhileAnimating_; + } + /** + * @return {boolean} Whether the rendered layer should be updated while + * interacting. + */ + getUpdateWhileInteracting() { + return this.updateWhileInteracting_; + } + /** + * Render declutter items for this layer + * @param {import("../Map.js").FrameState} frameState Frame state. + */ + renderDeclutter(frameState) { + if (!frameState.declutterTree) { + frameState.declutterTree = new RBush$2(9); + } + this.getRenderer().renderDeclutter(frameState); + } + /** + * @param {import("../render.js").OrderFunction|null|undefined} renderOrder + * Render order. + */ + setRenderOrder(renderOrder) { + this.set(Property.RENDER_ORDER, renderOrder); + } + /** + * Set the style for features. This can be a single style object, an array + * of styles, or a function that takes a feature and resolution and returns + * an array of styles. If set to `null`, the layer has no style (a `null` style), + * so only features that have their own styles will be rendered in the layer. Call + * `setStyle()` without arguments to reset to the default style. See + * [the ol/style/Style module]{@link module:ol/style/Style~Style} for information on the default style. + * + * If your layer has a static style, you can use [flat style]{@link module:ol/style/flat~FlatStyle} object + * literals instead of using the `Style` and symbolizer constructors (`Fill`, `Stroke`, etc.): + * ```js + * vectorLayer.setStyle({ + * "fill-color": "yellow", + * "stroke-color": "black", + * "stroke-width": 4 + * }) + * ``` + * + * @param {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style. + * @api + */ + setStyle(style) { + this.style_ = toStyleLike(style); + this.styleFunction_ = style === null ? void 0 : toFunction(this.style_); + this.changed(); + } +} +function toStyleLike(style) { + if (style === void 0) { + return createDefaultStyle; + } + if (!style) { + return null; + } + if (typeof style === "function") { + return style; + } + if (style instanceof Style) { + return style; + } + if (!Array.isArray(style)) { + return flatStylesToStyleFunction([style]); + } + if (style.length === 0) { + return []; + } + const length = style.length; + const first = style[0]; + if (first instanceof Style) { + const styles = new Array(length); + for (let i = 0; i < length; ++i) { + const candidate = style[i]; + if (!(candidate instanceof Style)) { + throw new Error("Expected a list of style instances"); + } + styles[i] = candidate; + } + return styles; + } + if ("style" in first) { + const rules = new Array(length); + for (let i = 0; i < length; ++i) { + const candidate = style[i]; + if (!("style" in candidate)) { + throw new Error("Expected a list of rules with a style property"); + } + rules[i] = candidate; + } + return rulesToStyleFunction(rules); + } + const flatStyles = ( + /** @type {Array} */ + style + ); + return flatStylesToStyleFunction(flatStyles); +} +const BaseVectorLayer$1 = BaseVectorLayer; +const Instruction = { + BEGIN_GEOMETRY: 0, + BEGIN_PATH: 1, + CIRCLE: 2, + CLOSE_PATH: 3, + CUSTOM: 4, + DRAW_CHARS: 5, + DRAW_IMAGE: 6, + END_GEOMETRY: 7, + FILL: 8, + MOVE_TO_LINE_TO: 9, + SET_FILL_STYLE: 10, + SET_STROKE_STYLE: 11, + STROKE: 12 +}; +const fillInstruction = [Instruction.FILL]; +const strokeInstruction = [Instruction.STROKE]; +const beginPathInstruction = [Instruction.BEGIN_PATH]; +const closePathInstruction = [Instruction.CLOSE_PATH]; +const CanvasInstruction = Instruction; +class VectorContext { + /** + * Render a geometry with a custom renderer. + * + * @param {import("../geom/SimpleGeometry.js").default} geometry Geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + * @param {Function} renderer Renderer. + * @param {Function} hitDetectionRenderer Renderer. + */ + drawCustom(geometry, feature, renderer, hitDetectionRenderer) { + } + /** + * Render a geometry. + * + * @param {import("../geom/Geometry.js").default} geometry The geometry to render. + */ + drawGeometry(geometry) { + } + /** + * Set the rendering style. + * + * @param {import("../style/Style.js").default} style The rendering style. + */ + setStyle(style) { + } + /** + * @param {import("../geom/Circle.js").default} circleGeometry Circle geometry. + * @param {import("../Feature.js").default} feature Feature. + */ + drawCircle(circleGeometry, feature) { + } + /** + * @param {import("../Feature.js").default} feature Feature. + * @param {import("../style/Style.js").default} style Style. + */ + drawFeature(feature, style) { + } + /** + * @param {import("../geom/GeometryCollection.js").default} geometryCollectionGeometry Geometry collection. + * @param {import("../Feature.js").default} feature Feature. + */ + drawGeometryCollection(geometryCollectionGeometry, feature) { + } + /** + * @param {import("../geom/LineString.js").default|import("./Feature.js").default} lineStringGeometry Line string geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + */ + drawLineString(lineStringGeometry, feature) { + } + /** + * @param {import("../geom/MultiLineString.js").default|import("./Feature.js").default} multiLineStringGeometry MultiLineString geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + */ + drawMultiLineString(multiLineStringGeometry, feature) { + } + /** + * @param {import("../geom/MultiPoint.js").default|import("./Feature.js").default} multiPointGeometry MultiPoint geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + */ + drawMultiPoint(multiPointGeometry, feature) { + } + /** + * @param {import("../geom/MultiPolygon.js").default} multiPolygonGeometry MultiPolygon geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + */ + drawMultiPolygon(multiPolygonGeometry, feature) { + } + /** + * @param {import("../geom/Point.js").default|import("./Feature.js").default} pointGeometry Point geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + */ + drawPoint(pointGeometry, feature) { + } + /** + * @param {import("../geom/Polygon.js").default|import("./Feature.js").default} polygonGeometry Polygon geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + */ + drawPolygon(polygonGeometry, feature) { + } + /** + * @param {import("../geom/SimpleGeometry.js").default|import("./Feature.js").default} geometry Geometry. + * @param {import("../Feature.js").FeatureLike} feature Feature. + */ + drawText(geometry, feature) { + } + /** + * @param {import("../style/Fill.js").default} fillStyle Fill style. + * @param {import("../style/Stroke.js").default} strokeStyle Stroke style. + */ + setFillStrokeStyle(fillStyle, strokeStyle) { + } + /** + * @param {import("../style/Image.js").default} imageStyle Image style. + * @param {import("../render/canvas.js").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with a text style. + */ + setImageStyle(imageStyle, declutterImageWithText) { + } + /** + * @param {import("../style/Text.js").default} textStyle Text style. + * @param {import("../render/canvas.js").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with an image style. + */ + setTextStyle(textStyle, declutterImageWithText) { + } +} +const VectorContext$1 = VectorContext; +class CanvasBuilder extends VectorContext$1 { + /** + * @param {number} tolerance Tolerance. + * @param {import("../../extent.js").Extent} maxExtent Maximum extent. + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + */ + constructor(tolerance, maxExtent, resolution, pixelRatio) { + super(); + this.tolerance = tolerance; + this.maxExtent = maxExtent; + this.pixelRatio = pixelRatio; + this.maxLineWidth = 0; + this.resolution = resolution; + this.beginGeometryInstruction1_ = null; + this.beginGeometryInstruction2_ = null; + this.bufferedMaxExtent_ = null; + this.instructions = []; + this.coordinates = []; + this.tmpCoordinate_ = []; + this.hitDetectionInstructions = []; + this.state = /** @type {import("../canvas.js").FillStrokeState} */ + {}; + } + /** + * @protected + * @param {Array} dashArray Dash array. + * @return {Array} Dash array with pixel ratio applied + */ + applyPixelRatio(dashArray) { + const pixelRatio = this.pixelRatio; + return pixelRatio == 1 ? dashArray : dashArray.map(function(dash) { + return dash * pixelRatio; + }); + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} stride Stride. + * @protected + * @return {number} My end + */ + appendFlatPointCoordinates(flatCoordinates, stride) { + const extent = this.getBufferedMaxExtent(); + const tmpCoord = this.tmpCoordinate_; + const coordinates2 = this.coordinates; + let myEnd = coordinates2.length; + for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) { + tmpCoord[0] = flatCoordinates[i]; + tmpCoord[1] = flatCoordinates[i + 1]; + if (containsCoordinate(extent, tmpCoord)) { + coordinates2[myEnd++] = tmpCoord[0]; + coordinates2[myEnd++] = tmpCoord[1]; + } + } + return myEnd; + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {boolean} closed Last input coordinate equals first. + * @param {boolean} skipFirst Skip first coordinate. + * @protected + * @return {number} My end. + */ + appendFlatLineCoordinates(flatCoordinates, offset, end, stride, closed, skipFirst) { + const coordinates2 = this.coordinates; + let myEnd = coordinates2.length; + const extent = this.getBufferedMaxExtent(); + if (skipFirst) { + offset += stride; + } + let lastXCoord = flatCoordinates[offset]; + let lastYCoord = flatCoordinates[offset + 1]; + const nextCoord = this.tmpCoordinate_; + let skipped = true; + let i, lastRel, nextRel; + for (i = offset + stride; i < end; i += stride) { + nextCoord[0] = flatCoordinates[i]; + nextCoord[1] = flatCoordinates[i + 1]; + nextRel = coordinateRelationship(extent, nextCoord); + if (nextRel !== lastRel) { + if (skipped) { + coordinates2[myEnd++] = lastXCoord; + coordinates2[myEnd++] = lastYCoord; + skipped = false; + } + coordinates2[myEnd++] = nextCoord[0]; + coordinates2[myEnd++] = nextCoord[1]; + } else if (nextRel === Relationship.INTERSECTING) { + coordinates2[myEnd++] = nextCoord[0]; + coordinates2[myEnd++] = nextCoord[1]; + skipped = false; + } else { + skipped = true; + } + lastXCoord = nextCoord[0]; + lastYCoord = nextCoord[1]; + lastRel = nextRel; + } + if (closed && skipped || i === offset + stride) { + coordinates2[myEnd++] = lastXCoord; + coordinates2[myEnd++] = lastYCoord; + } + return myEnd; + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {Array} builderEnds Builder ends. + * @return {number} Offset. + */ + drawCustomCoordinates_(flatCoordinates, offset, ends, stride, builderEnds) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const builderEnd = this.appendFlatLineCoordinates( + flatCoordinates, + offset, + end, + stride, + false, + false + ); + builderEnds.push(builderEnd); + offset = end; + } + return offset; + } + /** + * @param {import("../../geom/SimpleGeometry.js").default} geometry Geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + * @param {Function} renderer Renderer. + * @param {Function} hitDetectionRenderer Renderer. + */ + drawCustom(geometry, feature, renderer, hitDetectionRenderer) { + this.beginGeometry(geometry, feature); + const type = geometry.getType(); + const stride = geometry.getStride(); + const builderBegin = this.coordinates.length; + let flatCoordinates, builderEnd, builderEnds, builderEndss; + let offset; + switch (type) { + case "MultiPolygon": + flatCoordinates = /** @type {import("../../geom/MultiPolygon.js").default} */ + geometry.getOrientedFlatCoordinates(); + builderEndss = []; + const endss = ( + /** @type {import("../../geom/MultiPolygon.js").default} */ + geometry.getEndss() + ); + offset = 0; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const myEnds = []; + offset = this.drawCustomCoordinates_( + flatCoordinates, + offset, + endss[i], + stride, + myEnds + ); + builderEndss.push(myEnds); + } + this.instructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEndss, + geometry, + renderer, + inflateMultiCoordinatesArray + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEndss, + geometry, + hitDetectionRenderer || renderer, + inflateMultiCoordinatesArray + ]); + break; + case "Polygon": + case "MultiLineString": + builderEnds = []; + flatCoordinates = type == "Polygon" ? ( + /** @type {import("../../geom/Polygon.js").default} */ + geometry.getOrientedFlatCoordinates() + ) : geometry.getFlatCoordinates(); + offset = this.drawCustomCoordinates_( + flatCoordinates, + 0, + /** @type {import("../../geom/Polygon.js").default|import("../../geom/MultiLineString.js").default} */ + geometry.getEnds(), + stride, + builderEnds + ); + this.instructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnds, + geometry, + renderer, + inflateCoordinatesArray + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnds, + geometry, + hitDetectionRenderer || renderer, + inflateCoordinatesArray + ]); + break; + case "LineString": + case "Circle": + flatCoordinates = geometry.getFlatCoordinates(); + builderEnd = this.appendFlatLineCoordinates( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + false, + false + ); + this.instructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnd, + geometry, + renderer, + inflateCoordinates + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnd, + geometry, + hitDetectionRenderer || renderer, + inflateCoordinates + ]); + break; + case "MultiPoint": + flatCoordinates = geometry.getFlatCoordinates(); + builderEnd = this.appendFlatPointCoordinates(flatCoordinates, stride); + if (builderEnd > builderBegin) { + this.instructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnd, + geometry, + renderer, + inflateCoordinates + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnd, + geometry, + hitDetectionRenderer || renderer, + inflateCoordinates + ]); + } + break; + case "Point": + flatCoordinates = geometry.getFlatCoordinates(); + this.coordinates.push(flatCoordinates[0], flatCoordinates[1]); + builderEnd = this.coordinates.length; + this.instructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnd, + geometry, + renderer + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.CUSTOM, + builderBegin, + builderEnd, + geometry, + hitDetectionRenderer || renderer + ]); + break; + } + this.endGeometry(feature); + } + /** + * @protected + * @param {import("../../geom/Geometry").default|import("../Feature.js").default} geometry The geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + beginGeometry(geometry, feature) { + this.beginGeometryInstruction1_ = [ + CanvasInstruction.BEGIN_GEOMETRY, + feature, + 0, + geometry + ]; + this.instructions.push(this.beginGeometryInstruction1_); + this.beginGeometryInstruction2_ = [ + CanvasInstruction.BEGIN_GEOMETRY, + feature, + 0, + geometry + ]; + this.hitDetectionInstructions.push(this.beginGeometryInstruction2_); + } + /** + * @return {import("../canvas.js").SerializableInstructions} the serializable instructions. + */ + finish() { + return { + instructions: this.instructions, + hitDetectionInstructions: this.hitDetectionInstructions, + coordinates: this.coordinates + }; + } + /** + * Reverse the hit detection instructions. + */ + reverseHitDetectionInstructions() { + const hitDetectionInstructions = this.hitDetectionInstructions; + hitDetectionInstructions.reverse(); + let i; + const n = hitDetectionInstructions.length; + let instruction; + let type; + let begin = -1; + for (i = 0; i < n; ++i) { + instruction = hitDetectionInstructions[i]; + type = /** @type {import("./Instruction.js").default} */ + instruction[0]; + if (type == CanvasInstruction.END_GEOMETRY) { + begin = i; + } else if (type == CanvasInstruction.BEGIN_GEOMETRY) { + instruction[2] = i; + reverseSubArray(this.hitDetectionInstructions, begin, i); + begin = -1; + } + } + } + /** + * @param {import("../../style/Fill.js").default} fillStyle Fill style. + * @param {import("../../style/Stroke.js").default} strokeStyle Stroke style. + */ + setFillStrokeStyle(fillStyle, strokeStyle) { + const state = this.state; + if (fillStyle) { + const fillStyleColor = fillStyle.getColor(); + state.fillStyle = asColorLike( + fillStyleColor ? fillStyleColor : defaultFillStyle + ); + } else { + state.fillStyle = void 0; + } + if (strokeStyle) { + const strokeStyleColor = strokeStyle.getColor(); + state.strokeStyle = asColorLike( + strokeStyleColor ? strokeStyleColor : defaultStrokeStyle + ); + const strokeStyleLineCap = strokeStyle.getLineCap(); + state.lineCap = strokeStyleLineCap !== void 0 ? strokeStyleLineCap : defaultLineCap; + const strokeStyleLineDash = strokeStyle.getLineDash(); + state.lineDash = strokeStyleLineDash ? strokeStyleLineDash.slice() : defaultLineDash; + const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); + state.lineDashOffset = strokeStyleLineDashOffset ? strokeStyleLineDashOffset : defaultLineDashOffset; + const strokeStyleLineJoin = strokeStyle.getLineJoin(); + state.lineJoin = strokeStyleLineJoin !== void 0 ? strokeStyleLineJoin : defaultLineJoin; + const strokeStyleWidth = strokeStyle.getWidth(); + state.lineWidth = strokeStyleWidth !== void 0 ? strokeStyleWidth : defaultLineWidth; + const strokeStyleMiterLimit = strokeStyle.getMiterLimit(); + state.miterLimit = strokeStyleMiterLimit !== void 0 ? strokeStyleMiterLimit : defaultMiterLimit; + if (state.lineWidth > this.maxLineWidth) { + this.maxLineWidth = state.lineWidth; + this.bufferedMaxExtent_ = null; + } + } else { + state.strokeStyle = void 0; + state.lineCap = void 0; + state.lineDash = null; + state.lineDashOffset = void 0; + state.lineJoin = void 0; + state.lineWidth = void 0; + state.miterLimit = void 0; + } + } + /** + * @param {import("../canvas.js").FillStrokeState} state State. + * @return {Array<*>} Fill instruction. + */ + createFill(state) { + const fillStyle = state.fillStyle; + const fillInstruction2 = [CanvasInstruction.SET_FILL_STYLE, fillStyle]; + if (typeof fillStyle !== "string") { + fillInstruction2.push(true); + } + return fillInstruction2; + } + /** + * @param {import("../canvas.js").FillStrokeState} state State. + */ + applyStroke(state) { + this.instructions.push(this.createStroke(state)); + } + /** + * @param {import("../canvas.js").FillStrokeState} state State. + * @return {Array<*>} Stroke instruction. + */ + createStroke(state) { + return [ + CanvasInstruction.SET_STROKE_STYLE, + state.strokeStyle, + state.lineWidth * this.pixelRatio, + state.lineCap, + state.lineJoin, + state.miterLimit, + this.applyPixelRatio(state.lineDash), + state.lineDashOffset * this.pixelRatio + ]; + } + /** + * @param {import("../canvas.js").FillStrokeState} state State. + * @param {function(this:CanvasBuilder, import("../canvas.js").FillStrokeState):Array<*>} createFill Create fill. + */ + updateFillStyle(state, createFill) { + const fillStyle = state.fillStyle; + if (typeof fillStyle !== "string" || state.currentFillStyle != fillStyle) { + if (fillStyle !== void 0) { + this.instructions.push(createFill.call(this, state)); + } + state.currentFillStyle = fillStyle; + } + } + /** + * @param {import("../canvas.js").FillStrokeState} state State. + * @param {function(this:CanvasBuilder, import("../canvas.js").FillStrokeState): void} applyStroke Apply stroke. + */ + updateStrokeStyle(state, applyStroke) { + const strokeStyle = state.strokeStyle; + const lineCap = state.lineCap; + const lineDash = state.lineDash; + const lineDashOffset = state.lineDashOffset; + const lineJoin = state.lineJoin; + const lineWidth = state.lineWidth; + const miterLimit = state.miterLimit; + if (state.currentStrokeStyle != strokeStyle || state.currentLineCap != lineCap || lineDash != state.currentLineDash && !equals$2(state.currentLineDash, lineDash) || state.currentLineDashOffset != lineDashOffset || state.currentLineJoin != lineJoin || state.currentLineWidth != lineWidth || state.currentMiterLimit != miterLimit) { + if (strokeStyle !== void 0) { + applyStroke.call(this, state); + } + state.currentStrokeStyle = strokeStyle; + state.currentLineCap = lineCap; + state.currentLineDash = lineDash; + state.currentLineDashOffset = lineDashOffset; + state.currentLineJoin = lineJoin; + state.currentLineWidth = lineWidth; + state.currentMiterLimit = miterLimit; + } + } + /** + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + endGeometry(feature) { + this.beginGeometryInstruction1_[2] = this.instructions.length; + this.beginGeometryInstruction1_ = null; + this.beginGeometryInstruction2_[2] = this.hitDetectionInstructions.length; + this.beginGeometryInstruction2_ = null; + const endGeometryInstruction = [CanvasInstruction.END_GEOMETRY, feature]; + this.instructions.push(endGeometryInstruction); + this.hitDetectionInstructions.push(endGeometryInstruction); + } + /** + * Get the buffered rendering extent. Rendering will be clipped to the extent + * provided to the constructor. To account for symbolizers that may intersect + * this extent, we calculate a buffered extent (e.g. based on stroke width). + * @return {import("../../extent.js").Extent} The buffered rendering extent. + * @protected + */ + getBufferedMaxExtent() { + if (!this.bufferedMaxExtent_) { + this.bufferedMaxExtent_ = clone(this.maxExtent); + if (this.maxLineWidth > 0) { + const width = this.resolution * (this.maxLineWidth + 1) / 2; + buffer(this.bufferedMaxExtent_, width, this.bufferedMaxExtent_); + } + } + return this.bufferedMaxExtent_; + } +} +const Builder = CanvasBuilder; +class CanvasImageBuilder extends Builder { + /** + * @param {number} tolerance Tolerance. + * @param {import("../../extent.js").Extent} maxExtent Maximum extent. + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + */ + constructor(tolerance, maxExtent, resolution, pixelRatio) { + super(tolerance, maxExtent, resolution, pixelRatio); + this.hitDetectionImage_ = null; + this.image_ = null; + this.imagePixelRatio_ = void 0; + this.anchorX_ = void 0; + this.anchorY_ = void 0; + this.height_ = void 0; + this.opacity_ = void 0; + this.originX_ = void 0; + this.originY_ = void 0; + this.rotateWithView_ = void 0; + this.rotation_ = void 0; + this.scale_ = void 0; + this.width_ = void 0; + this.declutterMode_ = void 0; + this.declutterImageWithText_ = void 0; + } + /** + * @param {import("../../geom/Point.js").default|import("../Feature.js").default} pointGeometry Point geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + drawPoint(pointGeometry, feature) { + if (!this.image_) { + return; + } + this.beginGeometry(pointGeometry, feature); + const flatCoordinates = pointGeometry.getFlatCoordinates(); + const stride = pointGeometry.getStride(); + const myBegin = this.coordinates.length; + const myEnd = this.appendFlatPointCoordinates(flatCoordinates, stride); + this.instructions.push([ + CanvasInstruction.DRAW_IMAGE, + myBegin, + myEnd, + this.image_, + // Remaining arguments to DRAW_IMAGE are in alphabetical order + this.anchorX_ * this.imagePixelRatio_, + this.anchorY_ * this.imagePixelRatio_, + Math.ceil(this.height_ * this.imagePixelRatio_), + this.opacity_, + this.originX_ * this.imagePixelRatio_, + this.originY_ * this.imagePixelRatio_, + this.rotateWithView_, + this.rotation_, + [ + this.scale_[0] * this.pixelRatio / this.imagePixelRatio_, + this.scale_[1] * this.pixelRatio / this.imagePixelRatio_ + ], + Math.ceil(this.width_ * this.imagePixelRatio_), + this.declutterMode_, + this.declutterImageWithText_ + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.DRAW_IMAGE, + myBegin, + myEnd, + this.hitDetectionImage_, + // Remaining arguments to DRAW_IMAGE are in alphabetical order + this.anchorX_, + this.anchorY_, + this.height_, + 1, + this.originX_, + this.originY_, + this.rotateWithView_, + this.rotation_, + this.scale_, + this.width_, + this.declutterMode_, + this.declutterImageWithText_ + ]); + this.endGeometry(feature); + } + /** + * @param {import("../../geom/MultiPoint.js").default|import("../Feature.js").default} multiPointGeometry MultiPoint geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + drawMultiPoint(multiPointGeometry, feature) { + if (!this.image_) { + return; + } + this.beginGeometry(multiPointGeometry, feature); + const flatCoordinates = multiPointGeometry.getFlatCoordinates(); + const stride = multiPointGeometry.getStride(); + const myBegin = this.coordinates.length; + const myEnd = this.appendFlatPointCoordinates(flatCoordinates, stride); + this.instructions.push([ + CanvasInstruction.DRAW_IMAGE, + myBegin, + myEnd, + this.image_, + // Remaining arguments to DRAW_IMAGE are in alphabetical order + this.anchorX_ * this.imagePixelRatio_, + this.anchorY_ * this.imagePixelRatio_, + Math.ceil(this.height_ * this.imagePixelRatio_), + this.opacity_, + this.originX_ * this.imagePixelRatio_, + this.originY_ * this.imagePixelRatio_, + this.rotateWithView_, + this.rotation_, + [ + this.scale_[0] * this.pixelRatio / this.imagePixelRatio_, + this.scale_[1] * this.pixelRatio / this.imagePixelRatio_ + ], + Math.ceil(this.width_ * this.imagePixelRatio_), + this.declutterMode_, + this.declutterImageWithText_ + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.DRAW_IMAGE, + myBegin, + myEnd, + this.hitDetectionImage_, + // Remaining arguments to DRAW_IMAGE are in alphabetical order + this.anchorX_, + this.anchorY_, + this.height_, + 1, + this.originX_, + this.originY_, + this.rotateWithView_, + this.rotation_, + this.scale_, + this.width_, + this.declutterMode_, + this.declutterImageWithText_ + ]); + this.endGeometry(feature); + } + /** + * @return {import("../canvas.js").SerializableInstructions} the serializable instructions. + */ + finish() { + this.reverseHitDetectionInstructions(); + this.anchorX_ = void 0; + this.anchorY_ = void 0; + this.hitDetectionImage_ = null; + this.image_ = null; + this.imagePixelRatio_ = void 0; + this.height_ = void 0; + this.scale_ = void 0; + this.opacity_ = void 0; + this.originX_ = void 0; + this.originY_ = void 0; + this.rotateWithView_ = void 0; + this.rotation_ = void 0; + this.width_ = void 0; + return super.finish(); + } + /** + * @param {import("../../style/Image.js").default} imageStyle Image style. + * @param {Object} [sharedData] Shared data. + */ + setImageStyle(imageStyle, sharedData) { + const anchor = imageStyle.getAnchor(); + const size = imageStyle.getSize(); + const origin = imageStyle.getOrigin(); + this.imagePixelRatio_ = imageStyle.getPixelRatio(this.pixelRatio); + this.anchorX_ = anchor[0]; + this.anchorY_ = anchor[1]; + this.hitDetectionImage_ = imageStyle.getHitDetectionImage(); + this.image_ = imageStyle.getImage(this.pixelRatio); + this.height_ = size[1]; + this.opacity_ = imageStyle.getOpacity(); + this.originX_ = origin[0]; + this.originY_ = origin[1]; + this.rotateWithView_ = imageStyle.getRotateWithView(); + this.rotation_ = imageStyle.getRotation(); + this.scale_ = imageStyle.getScaleArray(); + this.width_ = size[0]; + this.declutterMode_ = imageStyle.getDeclutterMode(); + this.declutterImageWithText_ = sharedData; + } +} +const ImageBuilder = CanvasImageBuilder; +class CanvasLineStringBuilder extends Builder { + /** + * @param {number} tolerance Tolerance. + * @param {import("../../extent.js").Extent} maxExtent Maximum extent. + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + */ + constructor(tolerance, maxExtent, resolution, pixelRatio) { + super(tolerance, maxExtent, resolution, pixelRatio); + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @private + * @return {number} end. + */ + drawFlatCoordinates_(flatCoordinates, offset, end, stride) { + const myBegin = this.coordinates.length; + const myEnd = this.appendFlatLineCoordinates( + flatCoordinates, + offset, + end, + stride, + false, + false + ); + const moveToLineToInstruction = [ + CanvasInstruction.MOVE_TO_LINE_TO, + myBegin, + myEnd + ]; + this.instructions.push(moveToLineToInstruction); + this.hitDetectionInstructions.push(moveToLineToInstruction); + return end; + } + /** + * @param {import("../../geom/LineString.js").default|import("../Feature.js").default} lineStringGeometry Line string geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + drawLineString(lineStringGeometry, feature) { + const state = this.state; + const strokeStyle = state.strokeStyle; + const lineWidth = state.lineWidth; + if (strokeStyle === void 0 || lineWidth === void 0) { + return; + } + this.updateStrokeStyle(state, this.applyStroke); + this.beginGeometry(lineStringGeometry, feature); + this.hitDetectionInstructions.push( + [ + CanvasInstruction.SET_STROKE_STYLE, + state.strokeStyle, + state.lineWidth, + state.lineCap, + state.lineJoin, + state.miterLimit, + defaultLineDash, + defaultLineDashOffset + ], + beginPathInstruction + ); + const flatCoordinates = lineStringGeometry.getFlatCoordinates(); + const stride = lineStringGeometry.getStride(); + this.drawFlatCoordinates_( + flatCoordinates, + 0, + flatCoordinates.length, + stride + ); + this.hitDetectionInstructions.push(strokeInstruction); + this.endGeometry(feature); + } + /** + * @param {import("../../geom/MultiLineString.js").default|import("../Feature.js").default} multiLineStringGeometry MultiLineString geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + drawMultiLineString(multiLineStringGeometry, feature) { + const state = this.state; + const strokeStyle = state.strokeStyle; + const lineWidth = state.lineWidth; + if (strokeStyle === void 0 || lineWidth === void 0) { + return; + } + this.updateStrokeStyle(state, this.applyStroke); + this.beginGeometry(multiLineStringGeometry, feature); + this.hitDetectionInstructions.push( + [ + CanvasInstruction.SET_STROKE_STYLE, + state.strokeStyle, + state.lineWidth, + state.lineCap, + state.lineJoin, + state.miterLimit, + defaultLineDash, + defaultLineDashOffset + ], + beginPathInstruction + ); + const ends = multiLineStringGeometry.getEnds(); + const flatCoordinates = multiLineStringGeometry.getFlatCoordinates(); + const stride = multiLineStringGeometry.getStride(); + let offset = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + offset = this.drawFlatCoordinates_( + flatCoordinates, + offset, + /** @type {number} */ + ends[i], + stride + ); + } + this.hitDetectionInstructions.push(strokeInstruction); + this.endGeometry(feature); + } + /** + * @return {import("../canvas.js").SerializableInstructions} the serializable instructions. + */ + finish() { + const state = this.state; + if (state.lastStroke != void 0 && state.lastStroke != this.coordinates.length) { + this.instructions.push(strokeInstruction); + } + this.reverseHitDetectionInstructions(); + this.state = null; + return super.finish(); + } + /** + * @param {import("../canvas.js").FillStrokeState} state State. + */ + applyStroke(state) { + if (state.lastStroke != void 0 && state.lastStroke != this.coordinates.length) { + this.instructions.push(strokeInstruction); + state.lastStroke = this.coordinates.length; + } + state.lastStroke = 0; + super.applyStroke(state); + this.instructions.push(beginPathInstruction); + } +} +const LineStringBuilder = CanvasLineStringBuilder; +class CanvasPolygonBuilder extends Builder { + /** + * @param {number} tolerance Tolerance. + * @param {import("../../extent.js").Extent} maxExtent Maximum extent. + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + */ + constructor(tolerance, maxExtent, resolution, pixelRatio) { + super(tolerance, maxExtent, resolution, pixelRatio); + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @private + * @return {number} End. + */ + drawFlatCoordinatess_(flatCoordinates, offset, ends, stride) { + const state = this.state; + const fill = state.fillStyle !== void 0; + const stroke = state.strokeStyle !== void 0; + const numEnds = ends.length; + this.instructions.push(beginPathInstruction); + this.hitDetectionInstructions.push(beginPathInstruction); + for (let i = 0; i < numEnds; ++i) { + const end = ends[i]; + const myBegin = this.coordinates.length; + const myEnd = this.appendFlatLineCoordinates( + flatCoordinates, + offset, + end, + stride, + true, + !stroke + ); + const moveToLineToInstruction = [ + CanvasInstruction.MOVE_TO_LINE_TO, + myBegin, + myEnd + ]; + this.instructions.push(moveToLineToInstruction); + this.hitDetectionInstructions.push(moveToLineToInstruction); + if (stroke) { + this.instructions.push(closePathInstruction); + this.hitDetectionInstructions.push(closePathInstruction); + } + offset = end; + } + if (fill) { + this.instructions.push(fillInstruction); + this.hitDetectionInstructions.push(fillInstruction); + } + if (stroke) { + this.instructions.push(strokeInstruction); + this.hitDetectionInstructions.push(strokeInstruction); + } + return offset; + } + /** + * @param {import("../../geom/Circle.js").default} circleGeometry Circle geometry. + * @param {import("../../Feature.js").default} feature Feature. + */ + drawCircle(circleGeometry, feature) { + const state = this.state; + const fillStyle = state.fillStyle; + const strokeStyle = state.strokeStyle; + if (fillStyle === void 0 && strokeStyle === void 0) { + return; + } + this.setFillStrokeStyles_(); + this.beginGeometry(circleGeometry, feature); + if (state.fillStyle !== void 0) { + this.hitDetectionInstructions.push([ + CanvasInstruction.SET_FILL_STYLE, + defaultFillStyle + ]); + } + if (state.strokeStyle !== void 0) { + this.hitDetectionInstructions.push([ + CanvasInstruction.SET_STROKE_STYLE, + state.strokeStyle, + state.lineWidth, + state.lineCap, + state.lineJoin, + state.miterLimit, + defaultLineDash, + defaultLineDashOffset + ]); + } + const flatCoordinates = circleGeometry.getFlatCoordinates(); + const stride = circleGeometry.getStride(); + const myBegin = this.coordinates.length; + this.appendFlatLineCoordinates( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + false, + false + ); + const circleInstruction = [CanvasInstruction.CIRCLE, myBegin]; + this.instructions.push(beginPathInstruction, circleInstruction); + this.hitDetectionInstructions.push(beginPathInstruction, circleInstruction); + if (state.fillStyle !== void 0) { + this.instructions.push(fillInstruction); + this.hitDetectionInstructions.push(fillInstruction); + } + if (state.strokeStyle !== void 0) { + this.instructions.push(strokeInstruction); + this.hitDetectionInstructions.push(strokeInstruction); + } + this.endGeometry(feature); + } + /** + * @param {import("../../geom/Polygon.js").default|import("../Feature.js").default} polygonGeometry Polygon geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + drawPolygon(polygonGeometry, feature) { + const state = this.state; + const fillStyle = state.fillStyle; + const strokeStyle = state.strokeStyle; + if (fillStyle === void 0 && strokeStyle === void 0) { + return; + } + this.setFillStrokeStyles_(); + this.beginGeometry(polygonGeometry, feature); + if (state.fillStyle !== void 0) { + this.hitDetectionInstructions.push([ + CanvasInstruction.SET_FILL_STYLE, + defaultFillStyle + ]); + } + if (state.strokeStyle !== void 0) { + this.hitDetectionInstructions.push([ + CanvasInstruction.SET_STROKE_STYLE, + state.strokeStyle, + state.lineWidth, + state.lineCap, + state.lineJoin, + state.miterLimit, + defaultLineDash, + defaultLineDashOffset + ]); + } + const ends = polygonGeometry.getEnds(); + const flatCoordinates = polygonGeometry.getOrientedFlatCoordinates(); + const stride = polygonGeometry.getStride(); + this.drawFlatCoordinatess_( + flatCoordinates, + 0, + /** @type {Array} */ + ends, + stride + ); + this.endGeometry(feature); + } + /** + * @param {import("../../geom/MultiPolygon.js").default} multiPolygonGeometry MultiPolygon geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + drawMultiPolygon(multiPolygonGeometry, feature) { + const state = this.state; + const fillStyle = state.fillStyle; + const strokeStyle = state.strokeStyle; + if (fillStyle === void 0 && strokeStyle === void 0) { + return; + } + this.setFillStrokeStyles_(); + this.beginGeometry(multiPolygonGeometry, feature); + if (state.fillStyle !== void 0) { + this.hitDetectionInstructions.push([ + CanvasInstruction.SET_FILL_STYLE, + defaultFillStyle + ]); + } + if (state.strokeStyle !== void 0) { + this.hitDetectionInstructions.push([ + CanvasInstruction.SET_STROKE_STYLE, + state.strokeStyle, + state.lineWidth, + state.lineCap, + state.lineJoin, + state.miterLimit, + defaultLineDash, + defaultLineDashOffset + ]); + } + const endss = multiPolygonGeometry.getEndss(); + const flatCoordinates = multiPolygonGeometry.getOrientedFlatCoordinates(); + const stride = multiPolygonGeometry.getStride(); + let offset = 0; + for (let i = 0, ii = endss.length; i < ii; ++i) { + offset = this.drawFlatCoordinatess_( + flatCoordinates, + offset, + endss[i], + stride + ); + } + this.endGeometry(feature); + } + /** + * @return {import("../canvas.js").SerializableInstructions} the serializable instructions. + */ + finish() { + this.reverseHitDetectionInstructions(); + this.state = null; + const tolerance = this.tolerance; + if (tolerance !== 0) { + const coordinates2 = this.coordinates; + for (let i = 0, ii = coordinates2.length; i < ii; ++i) { + coordinates2[i] = snap(coordinates2[i], tolerance); + } + } + return super.finish(); + } + /** + * @private + */ + setFillStrokeStyles_() { + const state = this.state; + const fillStyle = state.fillStyle; + if (fillStyle !== void 0) { + this.updateFillStyle(state, this.createFill); + } + if (state.strokeStyle !== void 0) { + this.updateStrokeStyle(state, this.applyStroke); + } + } +} +const PolygonBuilder = CanvasPolygonBuilder; +function lineChunk(chunkLength, flatCoordinates, offset, end, stride) { + const chunks = []; + let cursor = offset; + let chunkM = 0; + let currentChunk = flatCoordinates.slice(offset, 2); + while (chunkM < chunkLength && cursor + stride < end) { + const [x1, y1] = currentChunk.slice(-2); + const x2 = flatCoordinates[cursor + stride]; + const y2 = flatCoordinates[cursor + stride + 1]; + const segmentLength = Math.sqrt( + (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + ); + chunkM += segmentLength; + if (chunkM >= chunkLength) { + const m = (chunkLength - chunkM + segmentLength) / segmentLength; + const x = lerp(x1, x2, m); + const y = lerp(y1, y2, m); + currentChunk.push(x, y); + chunks.push(currentChunk); + currentChunk = [x, y]; + if (chunkM == chunkLength) { + cursor += stride; + } + chunkM = 0; + } else if (chunkM < chunkLength) { + currentChunk.push( + flatCoordinates[cursor + stride], + flatCoordinates[cursor + stride + 1] + ); + cursor += stride; + } else { + const missing = segmentLength - chunkM; + const x = lerp(x1, x2, missing / segmentLength); + const y = lerp(y1, y2, missing / segmentLength); + currentChunk.push(x, y); + chunks.push(currentChunk); + currentChunk = [x, y]; + chunkM = 0; + cursor += stride; + } + } + if (chunkM > 0) { + chunks.push(currentChunk); + } + return chunks; +} +function matchingChunk(maxAngle, flatCoordinates, offset, end, stride) { + let chunkStart = offset; + let chunkEnd = offset; + let chunkM = 0; + let m = 0; + let start = offset; + let acos, i, m12, m23, x1, y1, x12, y12, x23, y23; + for (i = offset; i < end; i += stride) { + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; + if (x1 !== void 0) { + x23 = x2 - x1; + y23 = y2 - y1; + m23 = Math.sqrt(x23 * x23 + y23 * y23); + if (x12 !== void 0) { + m += m12; + acos = Math.acos((x12 * x23 + y12 * y23) / (m12 * m23)); + if (acos > maxAngle) { + if (m > chunkM) { + chunkM = m; + chunkStart = start; + chunkEnd = i; + } + m = 0; + start = i - stride; + } + } + m12 = m23; + x12 = x23; + y12 = y23; + } + x1 = x2; + y1 = y2; + } + m += m23; + return m > chunkM ? [start, i] : [chunkStart, chunkEnd]; +} +const TEXT_ALIGN = { + "left": 0, + "center": 0.5, + "right": 1, + "top": 0, + "middle": 0.5, + "hanging": 0.2, + "alphabetic": 0.8, + "ideographic": 0.8, + "bottom": 1 +}; +class CanvasTextBuilder extends Builder { + /** + * @param {number} tolerance Tolerance. + * @param {import("../../extent.js").Extent} maxExtent Maximum extent. + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + */ + constructor(tolerance, maxExtent, resolution, pixelRatio) { + super(tolerance, maxExtent, resolution, pixelRatio); + this.labels_ = null; + this.text_ = ""; + this.textOffsetX_ = 0; + this.textOffsetY_ = 0; + this.textRotateWithView_ = void 0; + this.textRotation_ = 0; + this.textFillState_ = null; + this.fillStates = {}; + this.fillStates[defaultFillStyle] = { fillStyle: defaultFillStyle }; + this.textStrokeState_ = null; + this.strokeStates = {}; + this.textState_ = /** @type {import("../canvas.js").TextState} */ + {}; + this.textStates = {}; + this.textKey_ = ""; + this.fillKey_ = ""; + this.strokeKey_ = ""; + this.declutterImageWithText_ = void 0; + } + /** + * @return {import("../canvas.js").SerializableInstructions} the serializable instructions. + */ + finish() { + const instructions = super.finish(); + instructions.textStates = this.textStates; + instructions.fillStates = this.fillStates; + instructions.strokeStates = this.strokeStates; + return instructions; + } + /** + * @param {import("../../geom/SimpleGeometry.js").default|import("../Feature.js").default} geometry Geometry. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + */ + drawText(geometry, feature) { + const fillState = this.textFillState_; + const strokeState = this.textStrokeState_; + const textState = this.textState_; + if (this.text_ === "" || !textState || !fillState && !strokeState) { + return; + } + const coordinates2 = this.coordinates; + let begin = coordinates2.length; + const geometryType = geometry.getType(); + let flatCoordinates = null; + let stride = geometry.getStride(); + if (textState.placement === "line" && (geometryType == "LineString" || geometryType == "MultiLineString" || geometryType == "Polygon" || geometryType == "MultiPolygon")) { + if (!intersects$1(this.getBufferedMaxExtent(), geometry.getExtent())) { + return; + } + let ends; + flatCoordinates = geometry.getFlatCoordinates(); + if (geometryType == "LineString") { + ends = [flatCoordinates.length]; + } else if (geometryType == "MultiLineString") { + ends = /** @type {import("../../geom/MultiLineString.js").default} */ + geometry.getEnds(); + } else if (geometryType == "Polygon") { + ends = /** @type {import("../../geom/Polygon.js").default} */ + geometry.getEnds().slice(0, 1); + } else if (geometryType == "MultiPolygon") { + const endss = ( + /** @type {import("../../geom/MultiPolygon.js").default} */ + geometry.getEndss() + ); + ends = []; + for (let i = 0, ii = endss.length; i < ii; ++i) { + ends.push(endss[i][0]); + } + } + this.beginGeometry(geometry, feature); + const repeat = textState.repeat; + const textAlign = repeat ? void 0 : textState.textAlign; + let flatOffset = 0; + for (let o = 0, oo = ends.length; o < oo; ++o) { + let chunks; + if (repeat) { + chunks = lineChunk( + repeat * this.resolution, + flatCoordinates, + flatOffset, + ends[o], + stride + ); + } else { + chunks = [flatCoordinates.slice(flatOffset, ends[o])]; + } + for (let c = 0, cc = chunks.length; c < cc; ++c) { + const chunk = chunks[c]; + let chunkBegin = 0; + let chunkEnd = chunk.length; + if (textAlign == void 0) { + const range = matchingChunk( + textState.maxAngle, + chunk, + 0, + chunk.length, + 2 + ); + chunkBegin = range[0]; + chunkEnd = range[1]; + } + for (let i = chunkBegin; i < chunkEnd; i += stride) { + coordinates2.push(chunk[i], chunk[i + 1]); + } + const end = coordinates2.length; + flatOffset = ends[o]; + this.drawChars_(begin, end); + begin = end; + } + } + this.endGeometry(feature); + } else { + let geometryWidths = textState.overflow ? null : []; + switch (geometryType) { + case "Point": + case "MultiPoint": + flatCoordinates = /** @type {import("../../geom/MultiPoint.js").default} */ + geometry.getFlatCoordinates(); + break; + case "LineString": + flatCoordinates = /** @type {import("../../geom/LineString.js").default} */ + geometry.getFlatMidpoint(); + break; + case "Circle": + flatCoordinates = /** @type {import("../../geom/Circle.js").default} */ + geometry.getCenter(); + break; + case "MultiLineString": + flatCoordinates = /** @type {import("../../geom/MultiLineString.js").default} */ + geometry.getFlatMidpoints(); + stride = 2; + break; + case "Polygon": + flatCoordinates = /** @type {import("../../geom/Polygon.js").default} */ + geometry.getFlatInteriorPoint(); + if (!textState.overflow) { + geometryWidths.push(flatCoordinates[2] / this.resolution); + } + stride = 3; + break; + case "MultiPolygon": + const interiorPoints = ( + /** @type {import("../../geom/MultiPolygon.js").default} */ + geometry.getFlatInteriorPoints() + ); + flatCoordinates = []; + for (let i = 0, ii = interiorPoints.length; i < ii; i += 3) { + if (!textState.overflow) { + geometryWidths.push(interiorPoints[i + 2] / this.resolution); + } + flatCoordinates.push(interiorPoints[i], interiorPoints[i + 1]); + } + if (flatCoordinates.length === 0) { + return; + } + stride = 2; + break; + } + const end = this.appendFlatPointCoordinates(flatCoordinates, stride); + if (end === begin) { + return; + } + if (geometryWidths && (end - begin) / 2 !== flatCoordinates.length / stride) { + let beg = begin / 2; + geometryWidths = geometryWidths.filter((w, i) => { + const keep = coordinates2[(beg + i) * 2] === flatCoordinates[i * stride] && coordinates2[(beg + i) * 2 + 1] === flatCoordinates[i * stride + 1]; + if (!keep) { + --beg; + } + return keep; + }); + } + this.saveTextStates_(); + if (textState.backgroundFill || textState.backgroundStroke) { + this.setFillStrokeStyle( + textState.backgroundFill, + textState.backgroundStroke + ); + if (textState.backgroundFill) { + this.updateFillStyle(this.state, this.createFill); + } + if (textState.backgroundStroke) { + this.updateStrokeStyle(this.state, this.applyStroke); + this.hitDetectionInstructions.push(this.createStroke(this.state)); + } + } + this.beginGeometry(geometry, feature); + let padding = textState.padding; + if (padding != defaultPadding && (textState.scale[0] < 0 || textState.scale[1] < 0)) { + let p0 = textState.padding[0]; + let p12 = textState.padding[1]; + let p22 = textState.padding[2]; + let p32 = textState.padding[3]; + if (textState.scale[0] < 0) { + p12 = -p12; + p32 = -p32; + } + if (textState.scale[1] < 0) { + p0 = -p0; + p22 = -p22; + } + padding = [p0, p12, p22, p32]; + } + const pixelRatio = this.pixelRatio; + this.instructions.push([ + CanvasInstruction.DRAW_IMAGE, + begin, + end, + null, + NaN, + NaN, + NaN, + 1, + 0, + 0, + this.textRotateWithView_, + this.textRotation_, + [1, 1], + NaN, + void 0, + this.declutterImageWithText_, + padding == defaultPadding ? defaultPadding : padding.map(function(p) { + return p * pixelRatio; + }), + !!textState.backgroundFill, + !!textState.backgroundStroke, + this.text_, + this.textKey_, + this.strokeKey_, + this.fillKey_, + this.textOffsetX_, + this.textOffsetY_, + geometryWidths + ]); + const scale2 = 1 / pixelRatio; + const currentFillStyle = this.state.fillStyle; + if (textState.backgroundFill) { + this.state.fillStyle = defaultFillStyle; + this.hitDetectionInstructions.push(this.createFill(this.state)); + } + this.hitDetectionInstructions.push([ + CanvasInstruction.DRAW_IMAGE, + begin, + end, + null, + NaN, + NaN, + NaN, + 1, + 0, + 0, + this.textRotateWithView_, + this.textRotation_, + [scale2, scale2], + NaN, + void 0, + this.declutterImageWithText_, + padding, + !!textState.backgroundFill, + !!textState.backgroundStroke, + this.text_, + this.textKey_, + this.strokeKey_, + this.fillKey_ ? defaultFillStyle : this.fillKey_, + this.textOffsetX_, + this.textOffsetY_, + geometryWidths + ]); + if (textState.backgroundFill) { + this.state.fillStyle = currentFillStyle; + this.hitDetectionInstructions.push(this.createFill(this.state)); + } + this.endGeometry(feature); + } + } + /** + * @private + */ + saveTextStates_() { + const strokeState = this.textStrokeState_; + const textState = this.textState_; + const fillState = this.textFillState_; + const strokeKey = this.strokeKey_; + if (strokeState) { + if (!(strokeKey in this.strokeStates)) { + this.strokeStates[strokeKey] = { + strokeStyle: strokeState.strokeStyle, + lineCap: strokeState.lineCap, + lineDashOffset: strokeState.lineDashOffset, + lineWidth: strokeState.lineWidth, + lineJoin: strokeState.lineJoin, + miterLimit: strokeState.miterLimit, + lineDash: strokeState.lineDash + }; + } + } + const textKey = this.textKey_; + if (!(textKey in this.textStates)) { + this.textStates[textKey] = { + font: textState.font, + textAlign: textState.textAlign || defaultTextAlign, + justify: textState.justify, + textBaseline: textState.textBaseline || defaultTextBaseline, + scale: textState.scale + }; + } + const fillKey = this.fillKey_; + if (fillState) { + if (!(fillKey in this.fillStates)) { + this.fillStates[fillKey] = { + fillStyle: fillState.fillStyle + }; + } + } + } + /** + * @private + * @param {number} begin Begin. + * @param {number} end End. + */ + drawChars_(begin, end) { + const strokeState = this.textStrokeState_; + const textState = this.textState_; + const strokeKey = this.strokeKey_; + const textKey = this.textKey_; + const fillKey = this.fillKey_; + this.saveTextStates_(); + const pixelRatio = this.pixelRatio; + const baseline = TEXT_ALIGN[textState.textBaseline]; + const offsetY = this.textOffsetY_ * pixelRatio; + const text = this.text_; + const strokeWidth = strokeState ? strokeState.lineWidth * Math.abs(textState.scale[0]) / 2 : 0; + this.instructions.push([ + CanvasInstruction.DRAW_CHARS, + begin, + end, + baseline, + textState.overflow, + fillKey, + textState.maxAngle, + pixelRatio, + offsetY, + strokeKey, + strokeWidth * pixelRatio, + text, + textKey, + 1 + ]); + this.hitDetectionInstructions.push([ + CanvasInstruction.DRAW_CHARS, + begin, + end, + baseline, + textState.overflow, + fillKey ? defaultFillStyle : fillKey, + textState.maxAngle, + pixelRatio, + offsetY, + strokeKey, + strokeWidth * pixelRatio, + text, + textKey, + 1 / pixelRatio + ]); + } + /** + * @param {import("../../style/Text.js").default} textStyle Text style. + * @param {Object} [sharedData] Shared data. + */ + setTextStyle(textStyle, sharedData) { + let textState, fillState, strokeState; + if (!textStyle) { + this.text_ = ""; + } else { + const textFillStyle = textStyle.getFill(); + if (!textFillStyle) { + fillState = null; + this.textFillState_ = fillState; + } else { + fillState = this.textFillState_; + if (!fillState) { + fillState = /** @type {import("../canvas.js").FillState} */ + {}; + this.textFillState_ = fillState; + } + fillState.fillStyle = asColorLike( + textFillStyle.getColor() || defaultFillStyle + ); + } + const textStrokeStyle = textStyle.getStroke(); + if (!textStrokeStyle) { + strokeState = null; + this.textStrokeState_ = strokeState; + } else { + strokeState = this.textStrokeState_; + if (!strokeState) { + strokeState = /** @type {import("../canvas.js").StrokeState} */ + {}; + this.textStrokeState_ = strokeState; + } + const lineDash = textStrokeStyle.getLineDash(); + const lineDashOffset = textStrokeStyle.getLineDashOffset(); + const lineWidth = textStrokeStyle.getWidth(); + const miterLimit = textStrokeStyle.getMiterLimit(); + strokeState.lineCap = textStrokeStyle.getLineCap() || defaultLineCap; + strokeState.lineDash = lineDash ? lineDash.slice() : defaultLineDash; + strokeState.lineDashOffset = lineDashOffset === void 0 ? defaultLineDashOffset : lineDashOffset; + strokeState.lineJoin = textStrokeStyle.getLineJoin() || defaultLineJoin; + strokeState.lineWidth = lineWidth === void 0 ? defaultLineWidth : lineWidth; + strokeState.miterLimit = miterLimit === void 0 ? defaultMiterLimit : miterLimit; + strokeState.strokeStyle = asColorLike( + textStrokeStyle.getColor() || defaultStrokeStyle + ); + } + textState = this.textState_; + const font = textStyle.getFont() || defaultFont; + registerFont(font); + const textScale = textStyle.getScaleArray(); + textState.overflow = textStyle.getOverflow(); + textState.font = font; + textState.maxAngle = textStyle.getMaxAngle(); + textState.placement = textStyle.getPlacement(); + textState.textAlign = textStyle.getTextAlign(); + textState.repeat = textStyle.getRepeat(); + textState.justify = textStyle.getJustify(); + textState.textBaseline = textStyle.getTextBaseline() || defaultTextBaseline; + textState.backgroundFill = textStyle.getBackgroundFill(); + textState.backgroundStroke = textStyle.getBackgroundStroke(); + textState.padding = textStyle.getPadding() || defaultPadding; + textState.scale = textScale === void 0 ? [1, 1] : textScale; + const textOffsetX = textStyle.getOffsetX(); + const textOffsetY = textStyle.getOffsetY(); + const textRotateWithView = textStyle.getRotateWithView(); + const textRotation = textStyle.getRotation(); + this.text_ = textStyle.getText() || ""; + this.textOffsetX_ = textOffsetX === void 0 ? 0 : textOffsetX; + this.textOffsetY_ = textOffsetY === void 0 ? 0 : textOffsetY; + this.textRotateWithView_ = textRotateWithView === void 0 ? false : textRotateWithView; + this.textRotation_ = textRotation === void 0 ? 0 : textRotation; + this.strokeKey_ = strokeState ? (typeof strokeState.strokeStyle == "string" ? strokeState.strokeStyle : getUid(strokeState.strokeStyle)) + strokeState.lineCap + strokeState.lineDashOffset + "|" + strokeState.lineWidth + strokeState.lineJoin + strokeState.miterLimit + "[" + strokeState.lineDash.join() + "]" : ""; + this.textKey_ = textState.font + textState.scale + (textState.textAlign || "?") + (textState.repeat || "?") + (textState.justify || "?") + (textState.textBaseline || "?"); + this.fillKey_ = fillState ? typeof fillState.fillStyle == "string" ? fillState.fillStyle : "|" + getUid(fillState.fillStyle) : ""; + } + this.declutterImageWithText_ = sharedData; + } +} +const BATCH_CONSTRUCTORS = { + "Circle": PolygonBuilder, + "Default": Builder, + "Image": ImageBuilder, + "LineString": LineStringBuilder, + "Polygon": PolygonBuilder, + "Text": CanvasTextBuilder +}; +class BuilderGroup { + /** + * @param {number} tolerance Tolerance. + * @param {import("../../extent.js").Extent} maxExtent Max extent. + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + */ + constructor(tolerance, maxExtent, resolution, pixelRatio) { + this.tolerance_ = tolerance; + this.maxExtent_ = maxExtent; + this.pixelRatio_ = pixelRatio; + this.resolution_ = resolution; + this.buildersByZIndex_ = {}; + } + /** + * @return {!Object>} The serializable instructions + */ + finish() { + const builderInstructions = {}; + for (const zKey in this.buildersByZIndex_) { + builderInstructions[zKey] = builderInstructions[zKey] || {}; + const builders = this.buildersByZIndex_[zKey]; + for (const builderKey in builders) { + const builderInstruction = builders[builderKey].finish(); + builderInstructions[zKey][builderKey] = builderInstruction; + } + } + return builderInstructions; + } + /** + * @param {number|undefined} zIndex Z index. + * @param {import("../canvas.js").BuilderType} builderType Replay type. + * @return {import("../VectorContext.js").default} Replay. + */ + getBuilder(zIndex, builderType) { + const zIndexKey = zIndex !== void 0 ? zIndex.toString() : "0"; + let replays = this.buildersByZIndex_[zIndexKey]; + if (replays === void 0) { + replays = {}; + this.buildersByZIndex_[zIndexKey] = replays; + } + let replay = replays[builderType]; + if (replay === void 0) { + const Constructor = BATCH_CONSTRUCTORS[builderType]; + replay = new Constructor( + this.tolerance_, + this.maxExtent_, + this.resolution_, + this.pixelRatio_ + ); + replays[builderType] = replay; + } + return replay; + } +} +const CanvasBuilderGroup = BuilderGroup; +class LayerRenderer extends Observable$1 { + /** + * @param {LayerType} layer Layer. + */ + constructor(layer) { + super(); + this.ready = true; + this.boundHandleImageChange_ = this.handleImageChange_.bind(this); + this.layer_ = layer; + this.declutterExecutorGroup = null; + } + /** + * Asynchronous layer level hit detection. + * @param {import("../pixel.js").Pixel} pixel Pixel. + * @return {Promise>} Promise that resolves with + * an array of features. + */ + getFeatures(pixel) { + return abstract(); + } + /** + * @param {import("../pixel.js").Pixel} pixel Pixel. + * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data. + */ + getData(pixel) { + return null; + } + /** + * Determine whether render should be called. + * @abstract + * @param {import("../Map.js").FrameState} frameState Frame state. + * @return {boolean} Layer is ready to be rendered. + */ + prepareFrame(frameState) { + return abstract(); + } + /** + * Render the layer. + * @abstract + * @param {import("../Map.js").FrameState} frameState Frame state. + * @param {HTMLElement|null} target Target that may be used to render content to. + * @return {HTMLElement|null} The rendered element. + */ + renderFrame(frameState, target) { + return abstract(); + } + /** + * @param {Object>} tiles Lookup of loaded tiles by zoom level. + * @param {number} zoom Zoom level. + * @param {import("../Tile.js").default} tile Tile. + * @return {boolean|void} If `false`, the tile will not be considered loaded. + */ + loadedTileCallback(tiles, zoom, tile) { + if (!tiles[zoom]) { + tiles[zoom] = {}; + } + tiles[zoom][tile.tileCoord.toString()] = tile; + return void 0; + } + /** + * Create a function that adds loaded tiles to the tile lookup. + * @param {import("../source/Tile.js").default} source Tile source. + * @param {import("../proj/Projection.js").default} projection Projection of the tiles. + * @param {Object>} tiles Lookup of loaded tiles by zoom level. + * @return {function(number, import("../TileRange.js").default):boolean} A function that can be + * called with a zoom level and a tile range to add loaded tiles to the lookup. + * @protected + */ + createLoadedTileFinder(source, projection, tiles) { + return ( + /** + * @param {number} zoom Zoom level. + * @param {import("../TileRange.js").default} tileRange Tile range. + * @return {boolean} The tile range is fully loaded. + */ + (zoom, tileRange) => { + const callback = this.loadedTileCallback.bind(this, tiles, zoom); + return source.forEachLoadedTile(projection, zoom, tileRange, callback); + } + ); + } + /** + * @abstract + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("../Map.js").FrameState} frameState Frame state. + * @param {number} hitTolerance Hit tolerance in pixels. + * @param {import("./vector.js").FeatureCallback} callback Feature callback. + * @param {Array>} matches The hit detected matches with tolerance. + * @return {T|undefined} Callback result. + * @template T + */ + forEachFeatureAtCoordinate(coordinate, frameState, hitTolerance, callback, matches) { + return void 0; + } + /** + * @return {LayerType} Layer. + */ + getLayer() { + return this.layer_; + } + /** + * Perform action necessary to get the layer rendered after new fonts have loaded + * @abstract + */ + handleFontsChanged() { + } + /** + * Handle changes in image state. + * @param {import("../events/Event.js").default} event Image change event. + * @private + */ + handleImageChange_(event) { + const image = ( + /** @type {import("../Image.js").default} */ + event.target + ); + if (image.getState() === ImageState.LOADED || image.getState() === ImageState.ERROR) { + this.renderIfReadyAndVisible(); + } + } + /** + * Load the image if not already loaded, and register the image change + * listener if needed. + * @param {import("../Image.js").default} image Image. + * @return {boolean} `true` if the image is already loaded, `false` otherwise. + * @protected + */ + loadImage(image) { + let imageState = image.getState(); + if (imageState != ImageState.LOADED && imageState != ImageState.ERROR) { + image.addEventListener(EventType.CHANGE, this.boundHandleImageChange_); + } + if (imageState == ImageState.IDLE) { + image.load(); + imageState = image.getState(); + } + return imageState == ImageState.LOADED; + } + /** + * @protected + */ + renderIfReadyAndVisible() { + const layer = this.getLayer(); + if (layer && layer.getVisible() && layer.getSourceState() === "ready") { + layer.changed(); + } + } + /** + * Clean up. + */ + disposeInternal() { + delete this.layer_; + super.disposeInternal(); + } +} +const LayerRenderer$1 = LayerRenderer; +const canvasPool = []; +let pixelContext = null; +function createPixelContext() { + pixelContext = createCanvasContext2D(1, 1, void 0, { + willReadFrequently: true + }); +} +class CanvasLayerRenderer extends LayerRenderer$1 { + /** + * @param {LayerType} layer Layer. + */ + constructor(layer) { + super(layer); + this.container = null; + this.renderedResolution; + this.tempTransform = create(); + this.pixelTransform = create(); + this.inversePixelTransform = create(); + this.context = null; + this.containerReused = false; + this.pixelContext_ = null; + this.frameState = null; + } + /** + * @param {import('../../DataTile.js').ImageLike} image Image. + * @param {number} col The column index. + * @param {number} row The row index. + * @return {Uint8ClampedArray|null} The image data. + */ + getImageData(image, col, row) { + if (!pixelContext) { + createPixelContext(); + } + pixelContext.clearRect(0, 0, 1, 1); + let data; + try { + pixelContext.drawImage(image, col, row, 1, 1, 0, 0, 1, 1); + data = pixelContext.getImageData(0, 0, 1, 1).data; + } catch (err) { + pixelContext = null; + return null; + } + return data; + } + /** + * @param {import('../../Map.js').FrameState} frameState Frame state. + * @return {string} Background color. + */ + getBackground(frameState) { + const layer = this.getLayer(); + let background = layer.getBackground(); + if (typeof background === "function") { + background = background(frameState.viewState.resolution); + } + return background || void 0; + } + /** + * Get a rendering container from an existing target, if compatible. + * @param {HTMLElement} target Potential render target. + * @param {string} transform CSS Transform. + * @param {string} [backgroundColor] Background color. + */ + useContainer(target, transform2, backgroundColor) { + const layerClassName = this.getLayer().getClassName(); + let container, context; + if (target && target.className === layerClassName && (!backgroundColor || target && target.style.backgroundColor && equals$2( + asArray(target.style.backgroundColor), + asArray(backgroundColor) + ))) { + const canvas = target.firstElementChild; + if (canvas instanceof HTMLCanvasElement) { + context = canvas.getContext("2d"); + } + } + if (context && context.canvas.style.transform === transform2) { + this.container = target; + this.context = context; + this.containerReused = true; + } else if (this.containerReused) { + this.container = null; + this.context = null; + this.containerReused = false; + } else if (this.container) { + this.container.style.backgroundColor = null; + } + if (!this.container) { + container = document.createElement("div"); + container.className = layerClassName; + let style = container.style; + style.position = "absolute"; + style.width = "100%"; + style.height = "100%"; + context = createCanvasContext2D(); + const canvas = context.canvas; + container.appendChild(canvas); + style = canvas.style; + style.position = "absolute"; + style.left = "0"; + style.transformOrigin = "top left"; + this.container = container; + this.context = context; + } + if (!this.containerReused && backgroundColor && !this.container.style.backgroundColor) { + this.container.style.backgroundColor = backgroundColor; + } + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {import("../../extent.js").Extent} extent Clip extent. + * @protected + */ + clipUnrotated(context, frameState, extent) { + const topLeft = getTopLeft(extent); + const topRight = getTopRight(extent); + const bottomRight = getBottomRight(extent); + const bottomLeft = getBottomLeft(extent); + apply(frameState.coordinateToPixelTransform, topLeft); + apply(frameState.coordinateToPixelTransform, topRight); + apply(frameState.coordinateToPixelTransform, bottomRight); + apply(frameState.coordinateToPixelTransform, bottomLeft); + const inverted = this.inversePixelTransform; + apply(inverted, topLeft); + apply(inverted, topRight); + apply(inverted, bottomRight); + apply(inverted, bottomLeft); + context.save(); + context.beginPath(); + context.moveTo(Math.round(topLeft[0]), Math.round(topLeft[1])); + context.lineTo(Math.round(topRight[0]), Math.round(topRight[1])); + context.lineTo(Math.round(bottomRight[0]), Math.round(bottomRight[1])); + context.lineTo(Math.round(bottomLeft[0]), Math.round(bottomLeft[1])); + context.clip(); + } + /** + * @param {import("../../render/EventType.js").default} type Event type. + * @param {CanvasRenderingContext2D} context Context. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @private + */ + dispatchRenderEvent_(type, context, frameState) { + const layer = this.getLayer(); + if (layer.hasListener(type)) { + const event = new RenderEvent$1( + type, + this.inversePixelTransform, + frameState, + context + ); + layer.dispatchEvent(event); + } + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @protected + */ + preRender(context, frameState) { + this.frameState = frameState; + this.dispatchRenderEvent_(RenderEventType.PRERENDER, context, frameState); + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @protected + */ + postRender(context, frameState) { + this.dispatchRenderEvent_(RenderEventType.POSTRENDER, context, frameState); + } + /** + * Creates a transform for rendering to an element that will be rotated after rendering. + * @param {import("../../coordinate.js").Coordinate} center Center. + * @param {number} resolution Resolution. + * @param {number} rotation Rotation. + * @param {number} pixelRatio Pixel ratio. + * @param {number} width Width of the rendered element (in pixels). + * @param {number} height Height of the rendered element (in pixels). + * @param {number} offsetX Offset on the x-axis in view coordinates. + * @protected + * @return {!import("../../transform.js").Transform} Transform. + */ + getRenderTransform(center, resolution, rotation, pixelRatio, width, height, offsetX) { + const dx1 = width / 2; + const dy1 = height / 2; + const sx = pixelRatio / resolution; + const sy = -sx; + const dx2 = -center[0] + offsetX; + const dy2 = -center[1]; + return compose( + this.tempTransform, + dx1, + dy1, + sx, + sy, + -rotation, + dx2, + dy2 + ); + } + /** + * Clean up. + */ + disposeInternal() { + delete this.frameState; + super.disposeInternal(); + } +} +const CanvasLayerRenderer$1 = CanvasLayerRenderer; +function drawTextOnPath(flatCoordinates, offset, end, stride, text, startM, maxAngle, scale2, measureAndCacheTextWidth2, font, cache2, rotation) { + let x2 = flatCoordinates[offset]; + let y2 = flatCoordinates[offset + 1]; + let x1 = 0; + let y1 = 0; + let segmentLength = 0; + let segmentM = 0; + function advance() { + x1 = x2; + y1 = y2; + offset += stride; + x2 = flatCoordinates[offset]; + y2 = flatCoordinates[offset + 1]; + segmentM += segmentLength; + segmentLength = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + } + do { + advance(); + } while (offset < end - stride && segmentM + segmentLength < startM); + let interpolate = segmentLength === 0 ? 0 : (startM - segmentM) / segmentLength; + const beginX = lerp(x1, x2, interpolate); + const beginY = lerp(y1, y2, interpolate); + const startOffset = offset - stride; + const startLength = segmentM; + const endM = startM + scale2 * measureAndCacheTextWidth2(font, text, cache2); + while (offset < end - stride && segmentM + segmentLength < endM) { + advance(); + } + interpolate = segmentLength === 0 ? 0 : (endM - segmentM) / segmentLength; + const endX = lerp(x1, x2, interpolate); + const endY = lerp(y1, y2, interpolate); + let reverse; + if (rotation) { + const flat = [beginX, beginY, endX, endY]; + rotate(flat, 0, 4, 2, rotation, flat, flat); + reverse = flat[0] > flat[2]; + } else { + reverse = beginX > endX; + } + const PI = Math.PI; + const result = []; + const singleSegment = startOffset + stride === offset; + offset = startOffset; + segmentLength = 0; + segmentM = startLength; + x2 = flatCoordinates[offset]; + y2 = flatCoordinates[offset + 1]; + let previousAngle; + if (singleSegment) { + advance(); + previousAngle = Math.atan2(y2 - y1, x2 - x1); + if (reverse) { + previousAngle += previousAngle > 0 ? -PI : PI; + } + const x = (endX + beginX) / 2; + const y = (endY + beginY) / 2; + result[0] = [x, y, (endM - startM) / 2, previousAngle, text]; + return result; + } + text = text.replace(/\n/g, " "); + for (let i = 0, ii = text.length; i < ii; ) { + advance(); + let angle = Math.atan2(y2 - y1, x2 - x1); + if (reverse) { + angle += angle > 0 ? -PI : PI; + } + if (previousAngle !== void 0) { + let delta = angle - previousAngle; + delta += delta > PI ? -2 * PI : delta < -PI ? 2 * PI : 0; + if (Math.abs(delta) > maxAngle) { + return null; + } + } + previousAngle = angle; + const iStart = i; + let charLength = 0; + for (; i < ii; ++i) { + const index = reverse ? ii - i - 1 : i; + const len = scale2 * measureAndCacheTextWidth2(font, text[index], cache2); + if (offset + stride < end && segmentM + segmentLength < startM + charLength + len / 2) { + break; + } + charLength += len; + } + if (i === iStart) { + continue; + } + const chars = reverse ? text.substring(ii - iStart, ii - i) : text.substring(iStart, i); + interpolate = segmentLength === 0 ? 0 : (startM + charLength / 2 - segmentM) / segmentLength; + const x = lerp(x1, x2, interpolate); + const y = lerp(y1, y2, interpolate); + result.push([x, y, charLength / 2, angle, chars]); + startM += charLength; + } + return result; +} +const tmpExtent = createEmpty(); +const p1 = []; +const p2 = []; +const p3 = []; +const p4 = []; +function getDeclutterBox(replayImageOrLabelArgs) { + return replayImageOrLabelArgs[3].declutterBox; +} +const rtlRegEx = new RegExp( + /* eslint-disable prettier/prettier */ + "[" + String.fromCharCode(1425) + "-" + String.fromCharCode(2303) + String.fromCharCode(64285) + "-" + String.fromCharCode(65023) + String.fromCharCode(65136) + "-" + String.fromCharCode(65276) + String.fromCharCode(67584) + "-" + String.fromCharCode(69631) + String.fromCharCode(124928) + "-" + String.fromCharCode(126975) + "]" + /* eslint-enable prettier/prettier */ +); +function horizontalTextAlign(text, align) { + if (align === "start") { + align = rtlRegEx.test(text) ? "right" : "left"; + } else if (align === "end") { + align = rtlRegEx.test(text) ? "left" : "right"; + } + return TEXT_ALIGN[align]; +} +function createTextChunks(acc, line, i) { + if (i > 0) { + acc.push("\n", ""); + } + acc.push(line, ""); + return acc; +} +class Executor { + /** + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + * @param {boolean} overlaps The replay can have overlapping geometries. + * @param {import("../canvas.js").SerializableInstructions} instructions The serializable instructions + */ + constructor(resolution, pixelRatio, overlaps, instructions) { + this.overlaps = overlaps; + this.pixelRatio = pixelRatio; + this.resolution = resolution; + this.alignFill_; + this.instructions = instructions.instructions; + this.coordinates = instructions.coordinates; + this.coordinateCache_ = {}; + this.renderedTransform_ = create(); + this.hitDetectionInstructions = instructions.hitDetectionInstructions; + this.pixelCoordinates_ = null; + this.viewRotation_ = 0; + this.fillStates = instructions.fillStates || {}; + this.strokeStates = instructions.strokeStates || {}; + this.textStates = instructions.textStates || {}; + this.widths_ = {}; + this.labels_ = {}; + } + /** + * @param {string|Array} text Text. + * @param {string} textKey Text style key. + * @param {string} fillKey Fill style key. + * @param {string} strokeKey Stroke style key. + * @return {import("../canvas.js").Label} Label. + */ + createLabel(text, textKey, fillKey, strokeKey) { + const key = text + textKey + fillKey + strokeKey; + if (this.labels_[key]) { + return this.labels_[key]; + } + const strokeState = strokeKey ? this.strokeStates[strokeKey] : null; + const fillState = fillKey ? this.fillStates[fillKey] : null; + const textState = this.textStates[textKey]; + const pixelRatio = this.pixelRatio; + const scale2 = [ + textState.scale[0] * pixelRatio, + textState.scale[1] * pixelRatio + ]; + const textIsArray = Array.isArray(text); + const align = textState.justify ? TEXT_ALIGN[textState.justify] : horizontalTextAlign( + Array.isArray(text) ? text[0] : text, + textState.textAlign || defaultTextAlign + ); + const strokeWidth = strokeKey && strokeState.lineWidth ? strokeState.lineWidth : 0; + const chunks = textIsArray ? text : text.split("\n").reduce(createTextChunks, []); + const { width, height, widths, heights, lineWidths } = getTextDimensions( + textState, + chunks + ); + const renderWidth = width + strokeWidth; + const contextInstructions = []; + const w = (renderWidth + 2) * scale2[0]; + const h = (height + strokeWidth) * scale2[1]; + const label = { + width: w < 0 ? Math.floor(w) : Math.ceil(w), + height: h < 0 ? Math.floor(h) : Math.ceil(h), + contextInstructions + }; + if (scale2[0] != 1 || scale2[1] != 1) { + contextInstructions.push("scale", scale2); + } + if (strokeKey) { + contextInstructions.push("strokeStyle", strokeState.strokeStyle); + contextInstructions.push("lineWidth", strokeWidth); + contextInstructions.push("lineCap", strokeState.lineCap); + contextInstructions.push("lineJoin", strokeState.lineJoin); + contextInstructions.push("miterLimit", strokeState.miterLimit); + contextInstructions.push("setLineDash", [strokeState.lineDash]); + contextInstructions.push("lineDashOffset", strokeState.lineDashOffset); + } + if (fillKey) { + contextInstructions.push("fillStyle", fillState.fillStyle); + } + contextInstructions.push("textBaseline", "middle"); + contextInstructions.push("textAlign", "center"); + const leftRight = 0.5 - align; + let x = align * renderWidth + leftRight * strokeWidth; + const strokeInstructions = []; + const fillInstructions = []; + let lineHeight = 0; + let lineOffset = 0; + let widthHeightIndex = 0; + let lineWidthIndex = 0; + let previousFont; + for (let i = 0, ii = chunks.length; i < ii; i += 2) { + const text2 = chunks[i]; + if (text2 === "\n") { + lineOffset += lineHeight; + lineHeight = 0; + x = align * renderWidth + leftRight * strokeWidth; + ++lineWidthIndex; + continue; + } + const font = chunks[i + 1] || textState.font; + if (font !== previousFont) { + if (strokeKey) { + strokeInstructions.push("font", font); + } + if (fillKey) { + fillInstructions.push("font", font); + } + previousFont = font; + } + lineHeight = Math.max(lineHeight, heights[widthHeightIndex]); + const fillStrokeArgs = [ + text2, + x + leftRight * widths[widthHeightIndex] + align * (widths[widthHeightIndex] - lineWidths[lineWidthIndex]), + 0.5 * (strokeWidth + lineHeight) + lineOffset + ]; + x += widths[widthHeightIndex]; + if (strokeKey) { + strokeInstructions.push("strokeText", fillStrokeArgs); + } + if (fillKey) { + fillInstructions.push("fillText", fillStrokeArgs); + } + ++widthHeightIndex; + } + Array.prototype.push.apply(contextInstructions, strokeInstructions); + Array.prototype.push.apply(contextInstructions, fillInstructions); + this.labels_[key] = label; + return label; + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {import("../../coordinate.js").Coordinate} p1 1st point of the background box. + * @param {import("../../coordinate.js").Coordinate} p2 2nd point of the background box. + * @param {import("../../coordinate.js").Coordinate} p3 3rd point of the background box. + * @param {import("../../coordinate.js").Coordinate} p4 4th point of the background box. + * @param {Array<*>} fillInstruction Fill instruction. + * @param {Array<*>} strokeInstruction Stroke instruction. + */ + replayTextBackground_(context, p12, p22, p32, p42, fillInstruction2, strokeInstruction2) { + context.beginPath(); + context.moveTo.apply(context, p12); + context.lineTo.apply(context, p22); + context.lineTo.apply(context, p32); + context.lineTo.apply(context, p42); + context.lineTo.apply(context, p12); + if (fillInstruction2) { + this.alignFill_ = /** @type {boolean} */ + fillInstruction2[2]; + this.fill_(context); + } + if (strokeInstruction2) { + this.setStrokeStyle_( + context, + /** @type {Array<*>} */ + strokeInstruction2 + ); + context.stroke(); + } + } + /** + * @private + * @param {number} sheetWidth Width of the sprite sheet. + * @param {number} sheetHeight Height of the sprite sheet. + * @param {number} centerX X. + * @param {number} centerY Y. + * @param {number} width Width. + * @param {number} height Height. + * @param {number} anchorX Anchor X. + * @param {number} anchorY Anchor Y. + * @param {number} originX Origin X. + * @param {number} originY Origin Y. + * @param {number} rotation Rotation. + * @param {import("../../size.js").Size} scale Scale. + * @param {boolean} snapToPixel Snap to pixel. + * @param {Array} padding Padding. + * @param {boolean} fillStroke Background fill or stroke. + * @param {import("../../Feature.js").FeatureLike} feature Feature. + * @return {ImageOrLabelDimensions} Dimensions for positioning and decluttering the image or label. + */ + calculateImageOrLabelDimensions_(sheetWidth, sheetHeight, centerX, centerY, width, height, anchorX, anchorY, originX, originY, rotation, scale2, snapToPixel, padding, fillStroke, feature) { + anchorX *= scale2[0]; + anchorY *= scale2[1]; + let x = centerX - anchorX; + let y = centerY - anchorY; + const w = width + originX > sheetWidth ? sheetWidth - originX : width; + const h = height + originY > sheetHeight ? sheetHeight - originY : height; + const boxW = padding[3] + w * scale2[0] + padding[1]; + const boxH = padding[0] + h * scale2[1] + padding[2]; + const boxX = x - padding[3]; + const boxY = y - padding[0]; + if (fillStroke || rotation !== 0) { + p1[0] = boxX; + p4[0] = boxX; + p1[1] = boxY; + p2[1] = boxY; + p2[0] = boxX + boxW; + p3[0] = p2[0]; + p3[1] = boxY + boxH; + p4[1] = p3[1]; + } + let transform2; + if (rotation !== 0) { + transform2 = compose( + create(), + centerX, + centerY, + 1, + 1, + rotation, + -centerX, + -centerY + ); + apply(transform2, p1); + apply(transform2, p2); + apply(transform2, p3); + apply(transform2, p4); + createOrUpdate$2( + Math.min(p1[0], p2[0], p3[0], p4[0]), + Math.min(p1[1], p2[1], p3[1], p4[1]), + Math.max(p1[0], p2[0], p3[0], p4[0]), + Math.max(p1[1], p2[1], p3[1], p4[1]), + tmpExtent + ); + } else { + createOrUpdate$2( + Math.min(boxX, boxX + boxW), + Math.min(boxY, boxY + boxH), + Math.max(boxX, boxX + boxW), + Math.max(boxY, boxY + boxH), + tmpExtent + ); + } + if (snapToPixel) { + x = Math.round(x); + y = Math.round(y); + } + return { + drawImageX: x, + drawImageY: y, + drawImageW: w, + drawImageH: h, + originX, + originY, + declutterBox: { + minX: tmpExtent[0], + minY: tmpExtent[1], + maxX: tmpExtent[2], + maxY: tmpExtent[3], + value: feature + }, + canvasTransform: transform2, + scale: scale2 + }; + } + /** + * @private + * @param {CanvasRenderingContext2D} context Context. + * @param {number} contextScale Scale of the context. + * @param {import("../canvas.js").Label|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} imageOrLabel Image. + * @param {ImageOrLabelDimensions} dimensions Dimensions. + * @param {number} opacity Opacity. + * @param {Array<*>} fillInstruction Fill instruction. + * @param {Array<*>} strokeInstruction Stroke instruction. + * @return {boolean} The image or label was rendered. + */ + replayImageOrLabel_(context, contextScale, imageOrLabel, dimensions, opacity, fillInstruction2, strokeInstruction2) { + const fillStroke = !!(fillInstruction2 || strokeInstruction2); + const box = dimensions.declutterBox; + const canvas = context.canvas; + const strokePadding = strokeInstruction2 ? strokeInstruction2[2] * dimensions.scale[0] / 2 : 0; + const intersects2 = box.minX - strokePadding <= canvas.width / contextScale && box.maxX + strokePadding >= 0 && box.minY - strokePadding <= canvas.height / contextScale && box.maxY + strokePadding >= 0; + if (intersects2) { + if (fillStroke) { + this.replayTextBackground_( + context, + p1, + p2, + p3, + p4, + /** @type {Array<*>} */ + fillInstruction2, + /** @type {Array<*>} */ + strokeInstruction2 + ); + } + drawImageOrLabel( + context, + dimensions.canvasTransform, + opacity, + imageOrLabel, + dimensions.originX, + dimensions.originY, + dimensions.drawImageW, + dimensions.drawImageH, + dimensions.drawImageX, + dimensions.drawImageY, + dimensions.scale + ); + } + return true; + } + /** + * @private + * @param {CanvasRenderingContext2D} context Context. + */ + fill_(context) { + if (this.alignFill_) { + const origin = apply(this.renderedTransform_, [0, 0]); + const repeatSize = 512 * this.pixelRatio; + context.save(); + context.translate(origin[0] % repeatSize, origin[1] % repeatSize); + context.rotate(this.viewRotation_); + } + context.fill(); + if (this.alignFill_) { + context.restore(); + } + } + /** + * @private + * @param {CanvasRenderingContext2D} context Context. + * @param {Array<*>} instruction Instruction. + */ + setStrokeStyle_(context, instruction) { + context["strokeStyle"] = /** @type {import("../../colorlike.js").ColorLike} */ + instruction[1]; + context.lineWidth = /** @type {number} */ + instruction[2]; + context.lineCap = /** @type {CanvasLineCap} */ + instruction[3]; + context.lineJoin = /** @type {CanvasLineJoin} */ + instruction[4]; + context.miterLimit = /** @type {number} */ + instruction[5]; + context.lineDashOffset = /** @type {number} */ + instruction[7]; + context.setLineDash( + /** @type {Array} */ + instruction[6] + ); + } + /** + * @private + * @param {string|Array} text The text to draw. + * @param {string} textKey The key of the text state. + * @param {string} strokeKey The key for the stroke state. + * @param {string} fillKey The key for the fill state. + * @return {{label: import("../canvas.js").Label, anchorX: number, anchorY: number}} The text image and its anchor. + */ + drawLabelWithPointPlacement_(text, textKey, strokeKey, fillKey) { + const textState = this.textStates[textKey]; + const label = this.createLabel(text, textKey, fillKey, strokeKey); + const strokeState = this.strokeStates[strokeKey]; + const pixelRatio = this.pixelRatio; + const align = horizontalTextAlign( + Array.isArray(text) ? text[0] : text, + textState.textAlign || defaultTextAlign + ); + const baseline = TEXT_ALIGN[textState.textBaseline || defaultTextBaseline]; + const strokeWidth = strokeState && strokeState.lineWidth ? strokeState.lineWidth : 0; + const width = label.width / pixelRatio - 2 * textState.scale[0]; + const anchorX = align * width + 2 * (0.5 - align) * strokeWidth; + const anchorY = baseline * label.height / pixelRatio + 2 * (0.5 - baseline) * strokeWidth; + return { + label, + anchorX, + anchorY + }; + } + /** + * @private + * @param {CanvasRenderingContext2D} context Context. + * @param {number} contextScale Scale of the context. + * @param {import("../../transform.js").Transform} transform Transform. + * @param {Array<*>} instructions Instructions array. + * @param {boolean} snapToPixel Snap point symbols and text to integer pixels. + * @param {FeatureCallback} [featureCallback] Feature callback. + * @param {import("../../extent.js").Extent} [hitExtent] Only check + * features that intersect this extent. + * @param {import("rbush").default} [declutterTree] Declutter tree. + * @return {T|undefined} Callback result. + * @template T + */ + execute_(context, contextScale, transform2, instructions, snapToPixel, featureCallback, hitExtent, declutterTree) { + let pixelCoordinates; + if (this.pixelCoordinates_ && equals$2(transform2, this.renderedTransform_)) { + pixelCoordinates = this.pixelCoordinates_; + } else { + if (!this.pixelCoordinates_) { + this.pixelCoordinates_ = []; + } + pixelCoordinates = transform2D( + this.coordinates, + 0, + this.coordinates.length, + 2, + transform2, + this.pixelCoordinates_ + ); + setFromArray(this.renderedTransform_, transform2); + } + let i = 0; + const ii = instructions.length; + let d = 0; + let dd; + let anchorX, anchorY, prevX, prevY, roundX, roundY, image, text, textKey, strokeKey, fillKey; + let pendingFill = 0; + let pendingStroke = 0; + let lastFillInstruction = null; + let lastStrokeInstruction = null; + const coordinateCache = this.coordinateCache_; + const viewRotation = this.viewRotation_; + const viewRotationFromTransform = Math.round(Math.atan2(-transform2[1], transform2[0]) * 1e12) / 1e12; + const state = ( + /** @type {import("../../render.js").State} */ + { + context, + pixelRatio: this.pixelRatio, + resolution: this.resolution, + rotation: viewRotation + } + ); + const batchSize = this.instructions != instructions || this.overlaps ? 0 : 200; + let feature; + let x, y, currentGeometry; + while (i < ii) { + const instruction = instructions[i]; + const type = ( + /** @type {import("./Instruction.js").default} */ + instruction[0] + ); + switch (type) { + case CanvasInstruction.BEGIN_GEOMETRY: + feature = /** @type {import("../../Feature.js").FeatureLike} */ + instruction[1]; + currentGeometry = instruction[3]; + if (!feature.getGeometry()) { + i = /** @type {number} */ + instruction[2]; + } else if (hitExtent !== void 0 && !intersects$1(hitExtent, currentGeometry.getExtent())) { + i = /** @type {number} */ + instruction[2] + 1; + } else { + ++i; + } + break; + case CanvasInstruction.BEGIN_PATH: + if (pendingFill > batchSize) { + this.fill_(context); + pendingFill = 0; + } + if (pendingStroke > batchSize) { + context.stroke(); + pendingStroke = 0; + } + if (!pendingFill && !pendingStroke) { + context.beginPath(); + prevX = NaN; + prevY = NaN; + } + ++i; + break; + case CanvasInstruction.CIRCLE: + d = /** @type {number} */ + instruction[1]; + const x1 = pixelCoordinates[d]; + const y1 = pixelCoordinates[d + 1]; + const x2 = pixelCoordinates[d + 2]; + const y2 = pixelCoordinates[d + 3]; + const dx = x2 - x1; + const dy = y2 - y1; + const r = Math.sqrt(dx * dx + dy * dy); + context.moveTo(x1 + r, y1); + context.arc(x1, y1, r, 0, 2 * Math.PI, true); + ++i; + break; + case CanvasInstruction.CLOSE_PATH: + context.closePath(); + ++i; + break; + case CanvasInstruction.CUSTOM: + d = /** @type {number} */ + instruction[1]; + dd = instruction[2]; + const geometry = ( + /** @type {import("../../geom/SimpleGeometry.js").default} */ + instruction[3] + ); + const renderer = instruction[4]; + const fn = instruction.length == 6 ? instruction[5] : void 0; + state.geometry = geometry; + state.feature = feature; + if (!(i in coordinateCache)) { + coordinateCache[i] = []; + } + const coords = coordinateCache[i]; + if (fn) { + fn(pixelCoordinates, d, dd, 2, coords); + } else { + coords[0] = pixelCoordinates[d]; + coords[1] = pixelCoordinates[d + 1]; + coords.length = 2; + } + renderer(coords, state); + ++i; + break; + case CanvasInstruction.DRAW_IMAGE: + d = /** @type {number} */ + instruction[1]; + dd = /** @type {number} */ + instruction[2]; + image = /** @type {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement} */ + instruction[3]; + anchorX = /** @type {number} */ + instruction[4]; + anchorY = /** @type {number} */ + instruction[5]; + let height = ( + /** @type {number} */ + instruction[6] + ); + const opacity = ( + /** @type {number} */ + instruction[7] + ); + const originX = ( + /** @type {number} */ + instruction[8] + ); + const originY = ( + /** @type {number} */ + instruction[9] + ); + const rotateWithView = ( + /** @type {boolean} */ + instruction[10] + ); + let rotation = ( + /** @type {number} */ + instruction[11] + ); + const scale2 = ( + /** @type {import("../../size.js").Size} */ + instruction[12] + ); + let width = ( + /** @type {number} */ + instruction[13] + ); + const declutterMode = ( + /** @type {"declutter"|"obstacle"|"none"|undefined} */ + instruction[14] + ); + const declutterImageWithText = ( + /** @type {import("../canvas.js").DeclutterImageWithText} */ + instruction[15] + ); + if (!image && instruction.length >= 20) { + text = /** @type {string} */ + instruction[19]; + textKey = /** @type {string} */ + instruction[20]; + strokeKey = /** @type {string} */ + instruction[21]; + fillKey = /** @type {string} */ + instruction[22]; + const labelWithAnchor = this.drawLabelWithPointPlacement_( + text, + textKey, + strokeKey, + fillKey + ); + image = labelWithAnchor.label; + instruction[3] = image; + const textOffsetX = ( + /** @type {number} */ + instruction[23] + ); + anchorX = (labelWithAnchor.anchorX - textOffsetX) * this.pixelRatio; + instruction[4] = anchorX; + const textOffsetY = ( + /** @type {number} */ + instruction[24] + ); + anchorY = (labelWithAnchor.anchorY - textOffsetY) * this.pixelRatio; + instruction[5] = anchorY; + height = image.height; + instruction[6] = height; + width = image.width; + instruction[13] = width; + } + let geometryWidths; + if (instruction.length > 25) { + geometryWidths = /** @type {number} */ + instruction[25]; + } + let padding, backgroundFill, backgroundStroke; + if (instruction.length > 17) { + padding = /** @type {Array} */ + instruction[16]; + backgroundFill = /** @type {boolean} */ + instruction[17]; + backgroundStroke = /** @type {boolean} */ + instruction[18]; + } else { + padding = defaultPadding; + backgroundFill = false; + backgroundStroke = false; + } + if (rotateWithView && viewRotationFromTransform) { + rotation += viewRotation; + } else if (!rotateWithView && !viewRotationFromTransform) { + rotation -= viewRotation; + } + let widthIndex = 0; + for (; d < dd; d += 2) { + if (geometryWidths && geometryWidths[widthIndex++] < width / this.pixelRatio) { + continue; + } + const dimensions = this.calculateImageOrLabelDimensions_( + image.width, + image.height, + pixelCoordinates[d], + pixelCoordinates[d + 1], + width, + height, + anchorX, + anchorY, + originX, + originY, + rotation, + scale2, + snapToPixel, + padding, + backgroundFill || backgroundStroke, + feature + ); + const args = [ + context, + contextScale, + image, + dimensions, + opacity, + backgroundFill ? ( + /** @type {Array<*>} */ + lastFillInstruction + ) : null, + backgroundStroke ? ( + /** @type {Array<*>} */ + lastStrokeInstruction + ) : null + ]; + if (declutterTree) { + if (declutterMode === "none") { + continue; + } else if (declutterMode === "obstacle") { + declutterTree.insert(dimensions.declutterBox); + continue; + } else { + let imageArgs; + let imageDeclutterBox; + if (declutterImageWithText) { + const index = dd - d; + if (!declutterImageWithText[index]) { + declutterImageWithText[index] = args; + continue; + } + imageArgs = declutterImageWithText[index]; + delete declutterImageWithText[index]; + imageDeclutterBox = getDeclutterBox(imageArgs); + if (declutterTree.collides(imageDeclutterBox)) { + continue; + } + } + if (declutterTree.collides(dimensions.declutterBox)) { + continue; + } + if (imageArgs) { + declutterTree.insert(imageDeclutterBox); + this.replayImageOrLabel_.apply(this, imageArgs); + } + declutterTree.insert(dimensions.declutterBox); + } + } + this.replayImageOrLabel_.apply(this, args); + } + ++i; + break; + case CanvasInstruction.DRAW_CHARS: + const begin = ( + /** @type {number} */ + instruction[1] + ); + const end = ( + /** @type {number} */ + instruction[2] + ); + const baseline = ( + /** @type {number} */ + instruction[3] + ); + const overflow = ( + /** @type {number} */ + instruction[4] + ); + fillKey = /** @type {string} */ + instruction[5]; + const maxAngle = ( + /** @type {number} */ + instruction[6] + ); + const measurePixelRatio = ( + /** @type {number} */ + instruction[7] + ); + const offsetY = ( + /** @type {number} */ + instruction[8] + ); + strokeKey = /** @type {string} */ + instruction[9]; + const strokeWidth = ( + /** @type {number} */ + instruction[10] + ); + text = /** @type {string} */ + instruction[11]; + textKey = /** @type {string} */ + instruction[12]; + const pixelRatioScale = [ + /** @type {number} */ + instruction[13], + /** @type {number} */ + instruction[13] + ]; + const textState = this.textStates[textKey]; + const font = textState.font; + const textScale = [ + textState.scale[0] * measurePixelRatio, + textState.scale[1] * measurePixelRatio + ]; + let cachedWidths; + if (font in this.widths_) { + cachedWidths = this.widths_[font]; + } else { + cachedWidths = {}; + this.widths_[font] = cachedWidths; + } + const pathLength = lineStringLength(pixelCoordinates, begin, end, 2); + const textLength = Math.abs(textScale[0]) * measureAndCacheTextWidth(font, text, cachedWidths); + if (overflow || textLength <= pathLength) { + const textAlign = this.textStates[textKey].textAlign; + const startM = (pathLength - textLength) * horizontalTextAlign(text, textAlign); + const parts = drawTextOnPath( + pixelCoordinates, + begin, + end, + 2, + text, + startM, + maxAngle, + Math.abs(textScale[0]), + measureAndCacheTextWidth, + font, + cachedWidths, + viewRotationFromTransform ? 0 : this.viewRotation_ + ); + drawChars: + if (parts) { + const replayImageOrLabelArgs = []; + let c, cc, chars, label, part; + if (strokeKey) { + for (c = 0, cc = parts.length; c < cc; ++c) { + part = parts[c]; + chars = /** @type {string} */ + part[4]; + label = this.createLabel(chars, textKey, "", strokeKey); + anchorX = /** @type {number} */ + part[2] + (textScale[0] < 0 ? -strokeWidth : strokeWidth); + anchorY = baseline * label.height + (0.5 - baseline) * 2 * strokeWidth * textScale[1] / textScale[0] - offsetY; + const dimensions = this.calculateImageOrLabelDimensions_( + label.width, + label.height, + part[0], + part[1], + label.width, + label.height, + anchorX, + anchorY, + 0, + 0, + part[3], + pixelRatioScale, + false, + defaultPadding, + false, + feature + ); + if (declutterTree && declutterTree.collides(dimensions.declutterBox)) { + break drawChars; + } + replayImageOrLabelArgs.push([ + context, + contextScale, + label, + dimensions, + 1, + null, + null + ]); + } + } + if (fillKey) { + for (c = 0, cc = parts.length; c < cc; ++c) { + part = parts[c]; + chars = /** @type {string} */ + part[4]; + label = this.createLabel(chars, textKey, fillKey, ""); + anchorX = /** @type {number} */ + part[2]; + anchorY = baseline * label.height - offsetY; + const dimensions = this.calculateImageOrLabelDimensions_( + label.width, + label.height, + part[0], + part[1], + label.width, + label.height, + anchorX, + anchorY, + 0, + 0, + part[3], + pixelRatioScale, + false, + defaultPadding, + false, + feature + ); + if (declutterTree && declutterTree.collides(dimensions.declutterBox)) { + break drawChars; + } + replayImageOrLabelArgs.push([ + context, + contextScale, + label, + dimensions, + 1, + null, + null + ]); + } + } + if (declutterTree) { + declutterTree.load(replayImageOrLabelArgs.map(getDeclutterBox)); + } + for (let i2 = 0, ii2 = replayImageOrLabelArgs.length; i2 < ii2; ++i2) { + this.replayImageOrLabel_.apply(this, replayImageOrLabelArgs[i2]); + } + } + } + ++i; + break; + case CanvasInstruction.END_GEOMETRY: + if (featureCallback !== void 0) { + feature = /** @type {import("../../Feature.js").FeatureLike} */ + instruction[1]; + const result = featureCallback(feature, currentGeometry); + if (result) { + return result; + } + } + ++i; + break; + case CanvasInstruction.FILL: + if (batchSize) { + pendingFill++; + } else { + this.fill_(context); + } + ++i; + break; + case CanvasInstruction.MOVE_TO_LINE_TO: + d = /** @type {number} */ + instruction[1]; + dd = /** @type {number} */ + instruction[2]; + x = pixelCoordinates[d]; + y = pixelCoordinates[d + 1]; + roundX = x + 0.5 | 0; + roundY = y + 0.5 | 0; + if (roundX !== prevX || roundY !== prevY) { + context.moveTo(x, y); + prevX = roundX; + prevY = roundY; + } + for (d += 2; d < dd; d += 2) { + x = pixelCoordinates[d]; + y = pixelCoordinates[d + 1]; + roundX = x + 0.5 | 0; + roundY = y + 0.5 | 0; + if (d == dd - 2 || roundX !== prevX || roundY !== prevY) { + context.lineTo(x, y); + prevX = roundX; + prevY = roundY; + } + } + ++i; + break; + case CanvasInstruction.SET_FILL_STYLE: + lastFillInstruction = instruction; + this.alignFill_ = instruction[2]; + if (pendingFill) { + this.fill_(context); + pendingFill = 0; + if (pendingStroke) { + context.stroke(); + pendingStroke = 0; + } + } + context.fillStyle = /** @type {import("../../colorlike.js").ColorLike} */ + instruction[1]; + ++i; + break; + case CanvasInstruction.SET_STROKE_STYLE: + lastStrokeInstruction = instruction; + if (pendingStroke) { + context.stroke(); + pendingStroke = 0; + } + this.setStrokeStyle_( + context, + /** @type {Array<*>} */ + instruction + ); + ++i; + break; + case CanvasInstruction.STROKE: + if (batchSize) { + pendingStroke++; + } else { + context.stroke(); + } + ++i; + break; + default: + ++i; + break; + } + } + if (pendingFill) { + this.fill_(context); + } + if (pendingStroke) { + context.stroke(); + } + return void 0; + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {number} contextScale Scale of the context. + * @param {import("../../transform.js").Transform} transform Transform. + * @param {number} viewRotation View rotation. + * @param {boolean} snapToPixel Snap point symbols and text to integer pixels. + * @param {import("rbush").default} [declutterTree] Declutter tree. + */ + execute(context, contextScale, transform2, viewRotation, snapToPixel, declutterTree) { + this.viewRotation_ = viewRotation; + this.execute_( + context, + contextScale, + transform2, + this.instructions, + snapToPixel, + void 0, + void 0, + declutterTree + ); + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {import("../../transform.js").Transform} transform Transform. + * @param {number} viewRotation View rotation. + * @param {FeatureCallback} [featureCallback] Feature callback. + * @param {import("../../extent.js").Extent} [hitExtent] Only check + * features that intersect this extent. + * @return {T|undefined} Callback result. + * @template T + */ + executeHitDetection(context, transform2, viewRotation, featureCallback, hitExtent) { + this.viewRotation_ = viewRotation; + return this.execute_( + context, + 1, + transform2, + this.hitDetectionInstructions, + true, + featureCallback, + hitExtent + ); + } +} +const Executor$1 = Executor; +const ORDER = ["Polygon", "Circle", "LineString", "Image", "Text", "Default"]; +class ExecutorGroup { + /** + * @param {import("../../extent.js").Extent} maxExtent Max extent for clipping. When a + * `maxExtent` was set on the Builder for this executor group, the same `maxExtent` + * should be set here, unless the target context does not exceed that extent (which + * can be the case when rendering to tiles). + * @param {number} resolution Resolution. + * @param {number} pixelRatio Pixel ratio. + * @param {boolean} overlaps The executor group can have overlapping geometries. + * @param {!Object>} allInstructions + * The serializable instructions. + * @param {number} [renderBuffer] Optional rendering buffer. + */ + constructor(maxExtent, resolution, pixelRatio, overlaps, allInstructions, renderBuffer) { + this.maxExtent_ = maxExtent; + this.overlaps_ = overlaps; + this.pixelRatio_ = pixelRatio; + this.resolution_ = resolution; + this.renderBuffer_ = renderBuffer; + this.executorsByZIndex_ = {}; + this.hitDetectionContext_ = null; + this.hitDetectionTransform_ = create(); + this.createExecutors_(allInstructions); + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {import("../../transform.js").Transform} transform Transform. + */ + clip(context, transform2) { + const flatClipCoords = this.getClipCoords(transform2); + context.beginPath(); + context.moveTo(flatClipCoords[0], flatClipCoords[1]); + context.lineTo(flatClipCoords[2], flatClipCoords[3]); + context.lineTo(flatClipCoords[4], flatClipCoords[5]); + context.lineTo(flatClipCoords[6], flatClipCoords[7]); + context.clip(); + } + /** + * Create executors and populate them using the provided instructions. + * @private + * @param {!Object>} allInstructions The serializable instructions + */ + createExecutors_(allInstructions) { + for (const zIndex in allInstructions) { + let executors = this.executorsByZIndex_[zIndex]; + if (executors === void 0) { + executors = {}; + this.executorsByZIndex_[zIndex] = executors; + } + const instructionByZindex = allInstructions[zIndex]; + for (const builderType in instructionByZindex) { + const instructions = instructionByZindex[builderType]; + executors[builderType] = new Executor$1( + this.resolution_, + this.pixelRatio_, + this.overlaps_, + instructions + ); + } + } + } + /** + * @param {Array} executors Executors. + * @return {boolean} Has executors of the provided types. + */ + hasExecutors(executors) { + for (const zIndex in this.executorsByZIndex_) { + const candidates = this.executorsByZIndex_[zIndex]; + for (let i = 0, ii = executors.length; i < ii; ++i) { + if (executors[i] in candidates) { + return true; + } + } + } + return false; + } + /** + * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate. + * @param {number} resolution Resolution. + * @param {number} rotation Rotation. + * @param {number} hitTolerance Hit tolerance in pixels. + * @param {function(import("../../Feature.js").FeatureLike, import("../../geom/SimpleGeometry.js").default, number): T} callback Feature callback. + * @param {Array} declutteredFeatures Decluttered features. + * @return {T|undefined} Callback result. + * @template T + */ + forEachFeatureAtCoordinate(coordinate, resolution, rotation, hitTolerance, callback, declutteredFeatures) { + hitTolerance = Math.round(hitTolerance); + const contextSize = hitTolerance * 2 + 1; + const transform2 = compose( + this.hitDetectionTransform_, + hitTolerance + 0.5, + hitTolerance + 0.5, + 1 / resolution, + -1 / resolution, + -rotation, + -coordinate[0], + -coordinate[1] + ); + const newContext = !this.hitDetectionContext_; + if (newContext) { + this.hitDetectionContext_ = createCanvasContext2D( + contextSize, + contextSize, + void 0, + { willReadFrequently: true } + ); + } + const context = this.hitDetectionContext_; + if (context.canvas.width !== contextSize || context.canvas.height !== contextSize) { + context.canvas.width = contextSize; + context.canvas.height = contextSize; + } else if (!newContext) { + context.clearRect(0, 0, contextSize, contextSize); + } + let hitExtent; + if (this.renderBuffer_ !== void 0) { + hitExtent = createEmpty(); + extendCoordinate(hitExtent, coordinate); + buffer( + hitExtent, + resolution * (this.renderBuffer_ + hitTolerance), + hitExtent + ); + } + const indexes = getPixelIndexArray(hitTolerance); + let builderType; + function featureCallback(feature, geometry) { + const imageData = context.getImageData( + 0, + 0, + contextSize, + contextSize + ).data; + for (let i2 = 0, ii = indexes.length; i2 < ii; i2++) { + if (imageData[indexes[i2]] > 0) { + if (!declutteredFeatures || builderType !== "Image" && builderType !== "Text" || declutteredFeatures.includes(feature)) { + const idx = (indexes[i2] - 3) / 4; + const x = hitTolerance - idx % contextSize; + const y = hitTolerance - (idx / contextSize | 0); + const result2 = callback(feature, geometry, x * x + y * y); + if (result2) { + return result2; + } + } + context.clearRect(0, 0, contextSize, contextSize); + break; + } + } + return void 0; + } + const zs = Object.keys(this.executorsByZIndex_).map(Number); + zs.sort(ascending); + let i, j, executors, executor, result; + for (i = zs.length - 1; i >= 0; --i) { + const zIndexKey = zs[i].toString(); + executors = this.executorsByZIndex_[zIndexKey]; + for (j = ORDER.length - 1; j >= 0; --j) { + builderType = ORDER[j]; + executor = executors[builderType]; + if (executor !== void 0) { + result = executor.executeHitDetection( + context, + transform2, + rotation, + featureCallback, + hitExtent + ); + if (result) { + return result; + } + } + } + } + return void 0; + } + /** + * @param {import("../../transform.js").Transform} transform Transform. + * @return {Array|null} Clip coordinates. + */ + getClipCoords(transform2) { + const maxExtent = this.maxExtent_; + if (!maxExtent) { + return null; + } + const minX = maxExtent[0]; + const minY = maxExtent[1]; + const maxX = maxExtent[2]; + const maxY = maxExtent[3]; + const flatClipCoords = [minX, minY, minX, maxY, maxX, maxY, maxX, minY]; + transform2D(flatClipCoords, 0, 8, 2, transform2, flatClipCoords); + return flatClipCoords; + } + /** + * @return {boolean} Is empty. + */ + isEmpty() { + return isEmpty$1(this.executorsByZIndex_); + } + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {number} contextScale Scale of the context. + * @param {import("../../transform.js").Transform} transform Transform. + * @param {number} viewRotation View rotation. + * @param {boolean} snapToPixel Snap point symbols and test to integer pixel. + * @param {Array} [builderTypes] Ordered replay types to replay. + * Default is {@link module:ol/render/replay~ORDER} + * @param {import("rbush").default} [declutterTree] Declutter tree. + */ + execute(context, contextScale, transform2, viewRotation, snapToPixel, builderTypes, declutterTree) { + const zs = Object.keys(this.executorsByZIndex_).map(Number); + zs.sort(ascending); + if (this.maxExtent_) { + context.save(); + this.clip(context, transform2); + } + builderTypes = builderTypes ? builderTypes : ORDER; + let i, ii, j, jj, replays, replay; + if (declutterTree) { + zs.reverse(); + } + for (i = 0, ii = zs.length; i < ii; ++i) { + const zIndexKey = zs[i].toString(); + replays = this.executorsByZIndex_[zIndexKey]; + for (j = 0, jj = builderTypes.length; j < jj; ++j) { + const builderType = builderTypes[j]; + replay = replays[builderType]; + if (replay !== void 0) { + replay.execute( + context, + contextScale, + transform2, + viewRotation, + snapToPixel, + declutterTree + ); + } + } + } + if (this.maxExtent_) { + context.restore(); + } + } +} +const circlePixelIndexArrayCache = {}; +function getPixelIndexArray(radius) { + if (circlePixelIndexArrayCache[radius] !== void 0) { + return circlePixelIndexArrayCache[radius]; + } + const size = radius * 2 + 1; + const maxDistanceSq = radius * radius; + const distances = new Array(maxDistanceSq + 1); + for (let i = 0; i <= radius; ++i) { + for (let j = 0; j <= radius; ++j) { + const distanceSq = i * i + j * j; + if (distanceSq > maxDistanceSq) { + break; + } + let distance = distances[distanceSq]; + if (!distance) { + distance = []; + distances[distanceSq] = distance; + } + distance.push(((radius + i) * size + (radius + j)) * 4 + 3); + if (i > 0) { + distance.push(((radius - i) * size + (radius + j)) * 4 + 3); + } + if (j > 0) { + distance.push(((radius + i) * size + (radius - j)) * 4 + 3); + if (i > 0) { + distance.push(((radius - i) * size + (radius - j)) * 4 + 3); + } + } + } + } + const pixelIndex = []; + for (let i = 0, ii = distances.length; i < ii; ++i) { + if (distances[i]) { + pixelIndex.push(...distances[i]); + } + } + circlePixelIndexArrayCache[radius] = pixelIndex; + return pixelIndex; +} +const ExecutorGroup$1 = ExecutorGroup; +class CanvasImmediateRenderer extends VectorContext$1 { + /** + * @param {CanvasRenderingContext2D} context Context. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../../extent.js").Extent} extent Extent. + * @param {import("../../transform.js").Transform} transform Transform. + * @param {number} viewRotation View rotation. + * @param {number} [squaredTolerance] Optional squared tolerance for simplification. + * @param {import("../../proj.js").TransformFunction} [userTransform] Transform from user to view projection. + */ + constructor(context, pixelRatio, extent, transform2, viewRotation, squaredTolerance, userTransform) { + super(); + this.context_ = context; + this.pixelRatio_ = pixelRatio; + this.extent_ = extent; + this.transform_ = transform2; + this.transformRotation_ = transform2 ? toFixed(Math.atan2(transform2[1], transform2[0]), 10) : 0; + this.viewRotation_ = viewRotation; + this.squaredTolerance_ = squaredTolerance; + this.userTransform_ = userTransform; + this.contextFillState_ = null; + this.contextStrokeState_ = null; + this.contextTextState_ = null; + this.fillState_ = null; + this.strokeState_ = null; + this.image_ = null; + this.imageAnchorX_ = 0; + this.imageAnchorY_ = 0; + this.imageHeight_ = 0; + this.imageOpacity_ = 0; + this.imageOriginX_ = 0; + this.imageOriginY_ = 0; + this.imageRotateWithView_ = false; + this.imageRotation_ = 0; + this.imageScale_ = [0, 0]; + this.imageWidth_ = 0; + this.text_ = ""; + this.textOffsetX_ = 0; + this.textOffsetY_ = 0; + this.textRotateWithView_ = false; + this.textRotation_ = 0; + this.textScale_ = [0, 0]; + this.textFillState_ = null; + this.textStrokeState_ = null; + this.textState_ = null; + this.pixelCoordinates_ = []; + this.tmpLocalTransform_ = create(); + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @private + */ + drawImages_(flatCoordinates, offset, end, stride) { + if (!this.image_) { + return; + } + const pixelCoordinates = transform2D( + flatCoordinates, + offset, + end, + stride, + this.transform_, + this.pixelCoordinates_ + ); + const context = this.context_; + const localTransform = this.tmpLocalTransform_; + const alpha = context.globalAlpha; + if (this.imageOpacity_ != 1) { + context.globalAlpha = alpha * this.imageOpacity_; + } + let rotation = this.imageRotation_; + if (this.transformRotation_ === 0) { + rotation -= this.viewRotation_; + } + if (this.imageRotateWithView_) { + rotation += this.viewRotation_; + } + for (let i = 0, ii = pixelCoordinates.length; i < ii; i += 2) { + const x = pixelCoordinates[i] - this.imageAnchorX_; + const y = pixelCoordinates[i + 1] - this.imageAnchorY_; + if (rotation !== 0 || this.imageScale_[0] != 1 || this.imageScale_[1] != 1) { + const centerX = x + this.imageAnchorX_; + const centerY = y + this.imageAnchorY_; + compose( + localTransform, + centerX, + centerY, + 1, + 1, + rotation, + -centerX, + -centerY + ); + context.save(); + context.transform.apply(context, localTransform); + context.translate(centerX, centerY); + context.scale(this.imageScale_[0], this.imageScale_[1]); + context.drawImage( + this.image_, + this.imageOriginX_, + this.imageOriginY_, + this.imageWidth_, + this.imageHeight_, + -this.imageAnchorX_, + -this.imageAnchorY_, + this.imageWidth_, + this.imageHeight_ + ); + context.restore(); + } else { + context.drawImage( + this.image_, + this.imageOriginX_, + this.imageOriginY_, + this.imageWidth_, + this.imageHeight_, + x, + y, + this.imageWidth_, + this.imageHeight_ + ); + } + } + if (this.imageOpacity_ != 1) { + context.globalAlpha = alpha; + } + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @private + */ + drawText_(flatCoordinates, offset, end, stride) { + if (!this.textState_ || this.text_ === "") { + return; + } + if (this.textFillState_) { + this.setContextFillState_(this.textFillState_); + } + if (this.textStrokeState_) { + this.setContextStrokeState_(this.textStrokeState_); + } + this.setContextTextState_(this.textState_); + const pixelCoordinates = transform2D( + flatCoordinates, + offset, + end, + stride, + this.transform_, + this.pixelCoordinates_ + ); + const context = this.context_; + let rotation = this.textRotation_; + if (this.transformRotation_ === 0) { + rotation -= this.viewRotation_; + } + if (this.textRotateWithView_) { + rotation += this.viewRotation_; + } + for (; offset < end; offset += stride) { + const x = pixelCoordinates[offset] + this.textOffsetX_; + const y = pixelCoordinates[offset + 1] + this.textOffsetY_; + if (rotation !== 0 || this.textScale_[0] != 1 || this.textScale_[1] != 1) { + context.save(); + context.translate(x - this.textOffsetX_, y - this.textOffsetY_); + context.rotate(rotation); + context.translate(this.textOffsetX_, this.textOffsetY_); + context.scale(this.textScale_[0], this.textScale_[1]); + if (this.textStrokeState_) { + context.strokeText(this.text_, 0, 0); + } + if (this.textFillState_) { + context.fillText(this.text_, 0, 0); + } + context.restore(); + } else { + if (this.textStrokeState_) { + context.strokeText(this.text_, x, y); + } + if (this.textFillState_) { + context.fillText(this.text_, x, y); + } + } + } + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {boolean} close Close. + * @private + * @return {number} end End. + */ + moveToLineTo_(flatCoordinates, offset, end, stride, close) { + const context = this.context_; + const pixelCoordinates = transform2D( + flatCoordinates, + offset, + end, + stride, + this.transform_, + this.pixelCoordinates_ + ); + context.moveTo(pixelCoordinates[0], pixelCoordinates[1]); + let length = pixelCoordinates.length; + if (close) { + length -= 2; + } + for (let i = 2; i < length; i += 2) { + context.lineTo(pixelCoordinates[i], pixelCoordinates[i + 1]); + } + if (close) { + context.closePath(); + } + return end; + } + /** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @private + * @return {number} End. + */ + drawRings_(flatCoordinates, offset, ends, stride) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + offset = this.moveToLineTo_( + flatCoordinates, + offset, + ends[i], + stride, + true + ); + } + return offset; + } + /** + * Render a circle geometry into the canvas. Rendering is immediate and uses + * the current fill and stroke styles. + * + * @param {import("../../geom/Circle.js").default} geometry Circle geometry. + * @api + */ + drawCircle(geometry) { + if (this.squaredTolerance_) { + geometry = /** @type {import("../../geom/Circle.js").default} */ + geometry.simplifyTransformed( + this.squaredTolerance_, + this.userTransform_ + ); + } + if (!intersects$1(this.extent_, geometry.getExtent())) { + return; + } + if (this.fillState_ || this.strokeState_) { + if (this.fillState_) { + this.setContextFillState_(this.fillState_); + } + if (this.strokeState_) { + this.setContextStrokeState_(this.strokeState_); + } + const pixelCoordinates = transformGeom2D( + geometry, + this.transform_, + this.pixelCoordinates_ + ); + const dx = pixelCoordinates[2] - pixelCoordinates[0]; + const dy = pixelCoordinates[3] - pixelCoordinates[1]; + const radius = Math.sqrt(dx * dx + dy * dy); + const context = this.context_; + context.beginPath(); + context.arc( + pixelCoordinates[0], + pixelCoordinates[1], + radius, + 0, + 2 * Math.PI + ); + if (this.fillState_) { + context.fill(); + } + if (this.strokeState_) { + context.stroke(); + } + } + if (this.text_ !== "") { + this.drawText_(geometry.getCenter(), 0, 2, 2); + } + } + /** + * Set the rendering style. Note that since this is an immediate rendering API, + * any `zIndex` on the provided style will be ignored. + * + * @param {import("../../style/Style.js").default} style The rendering style. + * @api + */ + setStyle(style) { + this.setFillStrokeStyle(style.getFill(), style.getStroke()); + this.setImageStyle(style.getImage()); + this.setTextStyle(style.getText()); + } + /** + * @param {import("../../transform.js").Transform} transform Transform. + */ + setTransform(transform2) { + this.transform_ = transform2; + } + /** + * Render a geometry into the canvas. Call + * {@link module:ol/render/canvas/Immediate~CanvasImmediateRenderer#setStyle renderer.setStyle()} first to set the rendering style. + * + * @param {import("../../geom/Geometry.js").default|import("../Feature.js").default} geometry The geometry to render. + * @api + */ + drawGeometry(geometry) { + const type = geometry.getType(); + switch (type) { + case "Point": + this.drawPoint( + /** @type {import("../../geom/Point.js").default} */ + geometry + ); + break; + case "LineString": + this.drawLineString( + /** @type {import("../../geom/LineString.js").default} */ + geometry + ); + break; + case "Polygon": + this.drawPolygon( + /** @type {import("../../geom/Polygon.js").default} */ + geometry + ); + break; + case "MultiPoint": + this.drawMultiPoint( + /** @type {import("../../geom/MultiPoint.js").default} */ + geometry + ); + break; + case "MultiLineString": + this.drawMultiLineString( + /** @type {import("../../geom/MultiLineString.js").default} */ + geometry + ); + break; + case "MultiPolygon": + this.drawMultiPolygon( + /** @type {import("../../geom/MultiPolygon.js").default} */ + geometry + ); + break; + case "GeometryCollection": + this.drawGeometryCollection( + /** @type {import("../../geom/GeometryCollection.js").default} */ + geometry + ); + break; + case "Circle": + this.drawCircle( + /** @type {import("../../geom/Circle.js").default} */ + geometry + ); + break; + } + } + /** + * Render a feature into the canvas. Note that any `zIndex` on the provided + * style will be ignored - features are rendered immediately in the order that + * this method is called. If you need `zIndex` support, you should be using an + * {@link module:ol/layer/Vector~VectorLayer} instead. + * + * @param {import("../../Feature.js").default} feature Feature. + * @param {import("../../style/Style.js").default} style Style. + * @api + */ + drawFeature(feature, style) { + const geometry = style.getGeometryFunction()(feature); + if (!geometry) { + return; + } + this.setStyle(style); + this.drawGeometry(geometry); + } + /** + * Render a GeometryCollection to the canvas. Rendering is immediate and + * uses the current styles appropriate for each geometry in the collection. + * + * @param {import("../../geom/GeometryCollection.js").default} geometry Geometry collection. + */ + drawGeometryCollection(geometry) { + const geometries = geometry.getGeometriesArray(); + for (let i = 0, ii = geometries.length; i < ii; ++i) { + this.drawGeometry(geometries[i]); + } + } + /** + * Render a Point geometry into the canvas. Rendering is immediate and uses + * the current style. + * + * @param {import("../../geom/Point.js").default|import("../Feature.js").default} geometry Point geometry. + */ + drawPoint(geometry) { + if (this.squaredTolerance_) { + geometry = /** @type {import("../../geom/Point.js").default} */ + geometry.simplifyTransformed( + this.squaredTolerance_, + this.userTransform_ + ); + } + const flatCoordinates = geometry.getFlatCoordinates(); + const stride = geometry.getStride(); + if (this.image_) { + this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride); + } + if (this.text_ !== "") { + this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride); + } + } + /** + * Render a MultiPoint geometry into the canvas. Rendering is immediate and + * uses the current style. + * + * @param {import("../../geom/MultiPoint.js").default|import("../Feature.js").default} geometry MultiPoint geometry. + */ + drawMultiPoint(geometry) { + if (this.squaredTolerance_) { + geometry = /** @type {import("../../geom/MultiPoint.js").default} */ + geometry.simplifyTransformed( + this.squaredTolerance_, + this.userTransform_ + ); + } + const flatCoordinates = geometry.getFlatCoordinates(); + const stride = geometry.getStride(); + if (this.image_) { + this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride); + } + if (this.text_ !== "") { + this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride); + } + } + /** + * Render a LineString into the canvas. Rendering is immediate and uses + * the current style. + * + * @param {import("../../geom/LineString.js").default|import("../Feature.js").default} geometry LineString geometry. + */ + drawLineString(geometry) { + if (this.squaredTolerance_) { + geometry = /** @type {import("../../geom/LineString.js").default} */ + geometry.simplifyTransformed( + this.squaredTolerance_, + this.userTransform_ + ); + } + if (!intersects$1(this.extent_, geometry.getExtent())) { + return; + } + if (this.strokeState_) { + this.setContextStrokeState_(this.strokeState_); + const context = this.context_; + const flatCoordinates = geometry.getFlatCoordinates(); + context.beginPath(); + this.moveToLineTo_( + flatCoordinates, + 0, + flatCoordinates.length, + geometry.getStride(), + false + ); + context.stroke(); + } + if (this.text_ !== "") { + const flatMidpoint = geometry.getFlatMidpoint(); + this.drawText_(flatMidpoint, 0, 2, 2); + } + } + /** + * Render a MultiLineString geometry into the canvas. Rendering is immediate + * and uses the current style. + * + * @param {import("../../geom/MultiLineString.js").default|import("../Feature.js").default} geometry MultiLineString geometry. + */ + drawMultiLineString(geometry) { + if (this.squaredTolerance_) { + geometry = /** @type {import("../../geom/MultiLineString.js").default} */ + geometry.simplifyTransformed( + this.squaredTolerance_, + this.userTransform_ + ); + } + const geometryExtent = geometry.getExtent(); + if (!intersects$1(this.extent_, geometryExtent)) { + return; + } + if (this.strokeState_) { + this.setContextStrokeState_(this.strokeState_); + const context = this.context_; + const flatCoordinates = geometry.getFlatCoordinates(); + let offset = 0; + const ends = ( + /** @type {Array} */ + geometry.getEnds() + ); + const stride = geometry.getStride(); + context.beginPath(); + for (let i = 0, ii = ends.length; i < ii; ++i) { + offset = this.moveToLineTo_( + flatCoordinates, + offset, + ends[i], + stride, + false + ); + } + context.stroke(); + } + if (this.text_ !== "") { + const flatMidpoints = geometry.getFlatMidpoints(); + this.drawText_(flatMidpoints, 0, flatMidpoints.length, 2); + } + } + /** + * Render a Polygon geometry into the canvas. Rendering is immediate and uses + * the current style. + * + * @param {import("../../geom/Polygon.js").default|import("../Feature.js").default} geometry Polygon geometry. + */ + drawPolygon(geometry) { + if (this.squaredTolerance_) { + geometry = /** @type {import("../../geom/Polygon.js").default} */ + geometry.simplifyTransformed( + this.squaredTolerance_, + this.userTransform_ + ); + } + if (!intersects$1(this.extent_, geometry.getExtent())) { + return; + } + if (this.strokeState_ || this.fillState_) { + if (this.fillState_) { + this.setContextFillState_(this.fillState_); + } + if (this.strokeState_) { + this.setContextStrokeState_(this.strokeState_); + } + const context = this.context_; + context.beginPath(); + this.drawRings_( + geometry.getOrientedFlatCoordinates(), + 0, + /** @type {Array} */ + geometry.getEnds(), + geometry.getStride() + ); + if (this.fillState_) { + context.fill(); + } + if (this.strokeState_) { + context.stroke(); + } + } + if (this.text_ !== "") { + const flatInteriorPoint = geometry.getFlatInteriorPoint(); + this.drawText_(flatInteriorPoint, 0, 2, 2); + } + } + /** + * Render MultiPolygon geometry into the canvas. Rendering is immediate and + * uses the current style. + * @param {import("../../geom/MultiPolygon.js").default} geometry MultiPolygon geometry. + */ + drawMultiPolygon(geometry) { + if (this.squaredTolerance_) { + geometry = /** @type {import("../../geom/MultiPolygon.js").default} */ + geometry.simplifyTransformed( + this.squaredTolerance_, + this.userTransform_ + ); + } + if (!intersects$1(this.extent_, geometry.getExtent())) { + return; + } + if (this.strokeState_ || this.fillState_) { + if (this.fillState_) { + this.setContextFillState_(this.fillState_); + } + if (this.strokeState_) { + this.setContextStrokeState_(this.strokeState_); + } + const context = this.context_; + const flatCoordinates = geometry.getOrientedFlatCoordinates(); + let offset = 0; + const endss = geometry.getEndss(); + const stride = geometry.getStride(); + context.beginPath(); + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + offset = this.drawRings_(flatCoordinates, offset, ends, stride); + } + if (this.fillState_) { + context.fill(); + } + if (this.strokeState_) { + context.stroke(); + } + } + if (this.text_ !== "") { + const flatInteriorPoints = geometry.getFlatInteriorPoints(); + this.drawText_(flatInteriorPoints, 0, flatInteriorPoints.length, 2); + } + } + /** + * @param {import("../canvas.js").FillState} fillState Fill state. + * @private + */ + setContextFillState_(fillState) { + const context = this.context_; + const contextFillState = this.contextFillState_; + if (!contextFillState) { + context.fillStyle = fillState.fillStyle; + this.contextFillState_ = { + fillStyle: fillState.fillStyle + }; + } else { + if (contextFillState.fillStyle != fillState.fillStyle) { + contextFillState.fillStyle = fillState.fillStyle; + context.fillStyle = fillState.fillStyle; + } + } + } + /** + * @param {import("../canvas.js").StrokeState} strokeState Stroke state. + * @private + */ + setContextStrokeState_(strokeState) { + const context = this.context_; + const contextStrokeState = this.contextStrokeState_; + if (!contextStrokeState) { + context.lineCap = strokeState.lineCap; + context.setLineDash(strokeState.lineDash); + context.lineDashOffset = strokeState.lineDashOffset; + context.lineJoin = strokeState.lineJoin; + context.lineWidth = strokeState.lineWidth; + context.miterLimit = strokeState.miterLimit; + context.strokeStyle = strokeState.strokeStyle; + this.contextStrokeState_ = { + lineCap: strokeState.lineCap, + lineDash: strokeState.lineDash, + lineDashOffset: strokeState.lineDashOffset, + lineJoin: strokeState.lineJoin, + lineWidth: strokeState.lineWidth, + miterLimit: strokeState.miterLimit, + strokeStyle: strokeState.strokeStyle + }; + } else { + if (contextStrokeState.lineCap != strokeState.lineCap) { + contextStrokeState.lineCap = strokeState.lineCap; + context.lineCap = strokeState.lineCap; + } + if (!equals$2(contextStrokeState.lineDash, strokeState.lineDash)) { + context.setLineDash( + contextStrokeState.lineDash = strokeState.lineDash + ); + } + if (contextStrokeState.lineDashOffset != strokeState.lineDashOffset) { + contextStrokeState.lineDashOffset = strokeState.lineDashOffset; + context.lineDashOffset = strokeState.lineDashOffset; + } + if (contextStrokeState.lineJoin != strokeState.lineJoin) { + contextStrokeState.lineJoin = strokeState.lineJoin; + context.lineJoin = strokeState.lineJoin; + } + if (contextStrokeState.lineWidth != strokeState.lineWidth) { + contextStrokeState.lineWidth = strokeState.lineWidth; + context.lineWidth = strokeState.lineWidth; + } + if (contextStrokeState.miterLimit != strokeState.miterLimit) { + contextStrokeState.miterLimit = strokeState.miterLimit; + context.miterLimit = strokeState.miterLimit; + } + if (contextStrokeState.strokeStyle != strokeState.strokeStyle) { + contextStrokeState.strokeStyle = strokeState.strokeStyle; + context.strokeStyle = strokeState.strokeStyle; + } + } + } + /** + * @param {import("../canvas.js").TextState} textState Text state. + * @private + */ + setContextTextState_(textState) { + const context = this.context_; + const contextTextState = this.contextTextState_; + const textAlign = textState.textAlign ? textState.textAlign : defaultTextAlign; + if (!contextTextState) { + context.font = textState.font; + context.textAlign = textAlign; + context.textBaseline = textState.textBaseline; + this.contextTextState_ = { + font: textState.font, + textAlign, + textBaseline: textState.textBaseline + }; + } else { + if (contextTextState.font != textState.font) { + contextTextState.font = textState.font; + context.font = textState.font; + } + if (contextTextState.textAlign != textAlign) { + contextTextState.textAlign = textAlign; + context.textAlign = textAlign; + } + if (contextTextState.textBaseline != textState.textBaseline) { + contextTextState.textBaseline = textState.textBaseline; + context.textBaseline = textState.textBaseline; + } + } + } + /** + * Set the fill and stroke style for subsequent draw operations. To clear + * either fill or stroke styles, pass null for the appropriate parameter. + * + * @param {import("../../style/Fill.js").default} fillStyle Fill style. + * @param {import("../../style/Stroke.js").default} strokeStyle Stroke style. + */ + setFillStrokeStyle(fillStyle, strokeStyle) { + if (!fillStyle) { + this.fillState_ = null; + } else { + const fillStyleColor = fillStyle.getColor(); + this.fillState_ = { + fillStyle: asColorLike( + fillStyleColor ? fillStyleColor : defaultFillStyle + ) + }; + } + if (!strokeStyle) { + this.strokeState_ = null; + } else { + const strokeStyleColor = strokeStyle.getColor(); + const strokeStyleLineCap = strokeStyle.getLineCap(); + const strokeStyleLineDash = strokeStyle.getLineDash(); + const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset(); + const strokeStyleLineJoin = strokeStyle.getLineJoin(); + const strokeStyleWidth = strokeStyle.getWidth(); + const strokeStyleMiterLimit = strokeStyle.getMiterLimit(); + const lineDash = strokeStyleLineDash ? strokeStyleLineDash : defaultLineDash; + this.strokeState_ = { + lineCap: strokeStyleLineCap !== void 0 ? strokeStyleLineCap : defaultLineCap, + lineDash: this.pixelRatio_ === 1 ? lineDash : lineDash.map((n) => n * this.pixelRatio_), + lineDashOffset: (strokeStyleLineDashOffset ? strokeStyleLineDashOffset : defaultLineDashOffset) * this.pixelRatio_, + lineJoin: strokeStyleLineJoin !== void 0 ? strokeStyleLineJoin : defaultLineJoin, + lineWidth: (strokeStyleWidth !== void 0 ? strokeStyleWidth : defaultLineWidth) * this.pixelRatio_, + miterLimit: strokeStyleMiterLimit !== void 0 ? strokeStyleMiterLimit : defaultMiterLimit, + strokeStyle: asColorLike( + strokeStyleColor ? strokeStyleColor : defaultStrokeStyle + ) + }; + } + } + /** + * Set the image style for subsequent draw operations. Pass null to remove + * the image style. + * + * @param {import("../../style/Image.js").default} imageStyle Image style. + */ + setImageStyle(imageStyle) { + let imageSize; + if (!imageStyle || !(imageSize = imageStyle.getSize())) { + this.image_ = null; + return; + } + const imagePixelRatio = imageStyle.getPixelRatio(this.pixelRatio_); + const imageAnchor = imageStyle.getAnchor(); + const imageOrigin = imageStyle.getOrigin(); + this.image_ = imageStyle.getImage(this.pixelRatio_); + this.imageAnchorX_ = imageAnchor[0] * imagePixelRatio; + this.imageAnchorY_ = imageAnchor[1] * imagePixelRatio; + this.imageHeight_ = imageSize[1] * imagePixelRatio; + this.imageOpacity_ = imageStyle.getOpacity(); + this.imageOriginX_ = imageOrigin[0]; + this.imageOriginY_ = imageOrigin[1]; + this.imageRotateWithView_ = imageStyle.getRotateWithView(); + this.imageRotation_ = imageStyle.getRotation(); + const imageScale = imageStyle.getScaleArray(); + this.imageScale_ = [ + imageScale[0] * this.pixelRatio_ / imagePixelRatio, + imageScale[1] * this.pixelRatio_ / imagePixelRatio + ]; + this.imageWidth_ = imageSize[0] * imagePixelRatio; + } + /** + * Set the text style for subsequent draw operations. Pass null to + * remove the text style. + * + * @param {import("../../style/Text.js").default} textStyle Text style. + */ + setTextStyle(textStyle) { + if (!textStyle) { + this.text_ = ""; + } else { + const textFillStyle = textStyle.getFill(); + if (!textFillStyle) { + this.textFillState_ = null; + } else { + const textFillStyleColor = textFillStyle.getColor(); + this.textFillState_ = { + fillStyle: asColorLike( + textFillStyleColor ? textFillStyleColor : defaultFillStyle + ) + }; + } + const textStrokeStyle = textStyle.getStroke(); + if (!textStrokeStyle) { + this.textStrokeState_ = null; + } else { + const textStrokeStyleColor = textStrokeStyle.getColor(); + const textStrokeStyleLineCap = textStrokeStyle.getLineCap(); + const textStrokeStyleLineDash = textStrokeStyle.getLineDash(); + const textStrokeStyleLineDashOffset = textStrokeStyle.getLineDashOffset(); + const textStrokeStyleLineJoin = textStrokeStyle.getLineJoin(); + const textStrokeStyleWidth = textStrokeStyle.getWidth(); + const textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit(); + this.textStrokeState_ = { + lineCap: textStrokeStyleLineCap !== void 0 ? textStrokeStyleLineCap : defaultLineCap, + lineDash: textStrokeStyleLineDash ? textStrokeStyleLineDash : defaultLineDash, + lineDashOffset: textStrokeStyleLineDashOffset ? textStrokeStyleLineDashOffset : defaultLineDashOffset, + lineJoin: textStrokeStyleLineJoin !== void 0 ? textStrokeStyleLineJoin : defaultLineJoin, + lineWidth: textStrokeStyleWidth !== void 0 ? textStrokeStyleWidth : defaultLineWidth, + miterLimit: textStrokeStyleMiterLimit !== void 0 ? textStrokeStyleMiterLimit : defaultMiterLimit, + strokeStyle: asColorLike( + textStrokeStyleColor ? textStrokeStyleColor : defaultStrokeStyle + ) + }; + } + const textFont = textStyle.getFont(); + const textOffsetX = textStyle.getOffsetX(); + const textOffsetY = textStyle.getOffsetY(); + const textRotateWithView = textStyle.getRotateWithView(); + const textRotation = textStyle.getRotation(); + const textScale = textStyle.getScaleArray(); + const textText = textStyle.getText(); + const textTextAlign = textStyle.getTextAlign(); + const textTextBaseline = textStyle.getTextBaseline(); + this.textState_ = { + font: textFont !== void 0 ? textFont : defaultFont, + textAlign: textTextAlign !== void 0 ? textTextAlign : defaultTextAlign, + textBaseline: textTextBaseline !== void 0 ? textTextBaseline : defaultTextBaseline + }; + this.text_ = textText !== void 0 ? Array.isArray(textText) ? textText.reduce((acc, t, i) => acc += i % 2 ? " " : t, "") : textText : ""; + this.textOffsetX_ = textOffsetX !== void 0 ? this.pixelRatio_ * textOffsetX : 0; + this.textOffsetY_ = textOffsetY !== void 0 ? this.pixelRatio_ * textOffsetY : 0; + this.textRotateWithView_ = textRotateWithView !== void 0 ? textRotateWithView : false; + this.textRotation_ = textRotation !== void 0 ? textRotation : 0; + this.textScale_ = [ + this.pixelRatio_ * textScale[0], + this.pixelRatio_ * textScale[1] + ]; + } + } +} +const CanvasImmediateRenderer$1 = CanvasImmediateRenderer; +const HIT_DETECT_RESOLUTION = 0.5; +function createHitDetectionImageData(size, transforms2, features, styleFunction, extent, resolution, rotation) { + const width = size[0] * HIT_DETECT_RESOLUTION; + const height = size[1] * HIT_DETECT_RESOLUTION; + const context = createCanvasContext2D(width, height); + context.imageSmoothingEnabled = false; + const canvas = context.canvas; + const renderer = new CanvasImmediateRenderer$1( + context, + HIT_DETECT_RESOLUTION, + extent, + null, + rotation + ); + const featureCount = features.length; + const indexFactor = Math.floor((256 * 256 * 256 - 1) / featureCount); + const featuresByZIndex = {}; + for (let i = 1; i <= featureCount; ++i) { + const feature = features[i - 1]; + const featureStyleFunction = feature.getStyleFunction() || styleFunction; + if (!featureStyleFunction) { + continue; + } + let styles = featureStyleFunction(feature, resolution); + if (!styles) { + continue; + } + if (!Array.isArray(styles)) { + styles = [styles]; + } + const index = i * indexFactor; + const color = index.toString(16).padStart(7, "#00000"); + for (let j = 0, jj = styles.length; j < jj; ++j) { + const originalStyle = styles[j]; + const geometry = originalStyle.getGeometryFunction()(feature); + if (!geometry || !intersects$1(extent, geometry.getExtent())) { + continue; + } + const style = originalStyle.clone(); + const fill = style.getFill(); + if (fill) { + fill.setColor(color); + } + const stroke = style.getStroke(); + if (stroke) { + stroke.setColor(color); + stroke.setLineDash(null); + } + style.setText(void 0); + const image = originalStyle.getImage(); + if (image) { + const imgSize = image.getImageSize(); + if (!imgSize) { + continue; + } + const imgContext = createCanvasContext2D( + imgSize[0], + imgSize[1], + void 0, + { alpha: false } + ); + const img = imgContext.canvas; + imgContext.fillStyle = color; + imgContext.fillRect(0, 0, img.width, img.height); + style.setImage( + new OlIcon({ + img, + anchor: image.getAnchor(), + anchorXUnits: "pixels", + anchorYUnits: "pixels", + offset: image.getOrigin(), + opacity: 1, + size: image.getSize(), + scale: image.getScale(), + rotation: image.getRotation(), + rotateWithView: image.getRotateWithView() + }) + ); + } + const zIndex = style.getZIndex() || 0; + let byGeometryType = featuresByZIndex[zIndex]; + if (!byGeometryType) { + byGeometryType = {}; + featuresByZIndex[zIndex] = byGeometryType; + byGeometryType["Polygon"] = []; + byGeometryType["Circle"] = []; + byGeometryType["LineString"] = []; + byGeometryType["Point"] = []; + } + const type = geometry.getType(); + if (type === "GeometryCollection") { + const geometries = ( + /** @type {import("../../geom/GeometryCollection.js").default} */ + geometry.getGeometriesArrayRecursive() + ); + for (let i2 = 0, ii = geometries.length; i2 < ii; ++i2) { + const geometry2 = geometries[i2]; + byGeometryType[geometry2.getType().replace("Multi", "")].push( + geometry2, + style + ); + } + } else { + byGeometryType[type.replace("Multi", "")].push(geometry, style); + } + } + } + const zIndexKeys = Object.keys(featuresByZIndex).map(Number).sort(ascending); + for (let i = 0, ii = zIndexKeys.length; i < ii; ++i) { + const byGeometryType = featuresByZIndex[zIndexKeys[i]]; + for (const type in byGeometryType) { + const geomAndStyle = byGeometryType[type]; + for (let j = 0, jj = geomAndStyle.length; j < jj; j += 2) { + renderer.setStyle(geomAndStyle[j + 1]); + for (let k = 0, kk = transforms2.length; k < kk; ++k) { + renderer.setTransform(transforms2[k]); + renderer.drawGeometry(geomAndStyle[j]); + } + } + } + } + return context.getImageData(0, 0, canvas.width, canvas.height); +} +function hitDetect(pixel, features, imageData) { + const resultFeatures = []; + if (imageData) { + const x = Math.floor(Math.round(pixel[0]) * HIT_DETECT_RESOLUTION); + const y = Math.floor(Math.round(pixel[1]) * HIT_DETECT_RESOLUTION); + const index = (clamp(x, 0, imageData.width - 1) + clamp(y, 0, imageData.height - 1) * imageData.width) * 4; + const r = imageData.data[index]; + const g = imageData.data[index + 1]; + const b = imageData.data[index + 2]; + const i = b + 256 * (g + 256 * r); + const indexFactor = Math.floor((256 * 256 * 256 - 1) / features.length); + if (i && i % indexFactor === 0) { + resultFeatures.push(features[i / indexFactor - 1]); + } + } + return resultFeatures; +} +const SIMPLIFY_TOLERANCE = 0.5; +const GEOMETRY_RENDERERS = { + "Point": renderPointGeometry, + "LineString": renderLineStringGeometry, + "Polygon": renderPolygonGeometry, + "MultiPoint": renderMultiPointGeometry, + "MultiLineString": renderMultiLineStringGeometry, + "MultiPolygon": renderMultiPolygonGeometry, + "GeometryCollection": renderGeometryCollectionGeometry, + "Circle": renderCircleGeometry +}; +function defaultOrder(feature1, feature2) { + return parseInt(getUid(feature1), 10) - parseInt(getUid(feature2), 10); +} +function getSquaredTolerance(resolution, pixelRatio) { + const tolerance = getTolerance(resolution, pixelRatio); + return tolerance * tolerance; +} +function getTolerance(resolution, pixelRatio) { + return SIMPLIFY_TOLERANCE * resolution / pixelRatio; +} +function renderCircleGeometry(builderGroup, geometry, style, feature, declutterBuilderGroup) { + const fillStyle = style.getFill(); + const strokeStyle = style.getStroke(); + if (fillStyle || strokeStyle) { + const circleReplay = builderGroup.getBuilder(style.getZIndex(), "Circle"); + circleReplay.setFillStrokeStyle(fillStyle, strokeStyle); + circleReplay.drawCircle(geometry, feature); + } + const textStyle = style.getText(); + if (textStyle && textStyle.getText()) { + const textReplay = (declutterBuilderGroup || builderGroup).getBuilder( + style.getZIndex(), + "Text" + ); + textReplay.setTextStyle(textStyle); + textReplay.drawText(geometry, feature); + } +} +function renderFeature(replayGroup, feature, style, squaredTolerance, listener, transform2, declutterBuilderGroup) { + let loading = false; + const imageStyle = style.getImage(); + if (imageStyle) { + const imageState = imageStyle.getImageState(); + if (imageState == ImageState.LOADED || imageState == ImageState.ERROR) { + imageStyle.unlistenImageChange(listener); + } else { + if (imageState == ImageState.IDLE) { + imageStyle.load(); + } + imageStyle.listenImageChange(listener); + loading = true; + } + } + renderFeatureInternal( + replayGroup, + feature, + style, + squaredTolerance, + transform2, + declutterBuilderGroup + ); + return loading; +} +function renderFeatureInternal(replayGroup, feature, style, squaredTolerance, transform2, declutterBuilderGroup) { + const geometry = style.getGeometryFunction()(feature); + if (!geometry) { + return; + } + const simplifiedGeometry = geometry.simplifyTransformed( + squaredTolerance, + transform2 + ); + const renderer = style.getRenderer(); + if (renderer) { + renderGeometry(replayGroup, simplifiedGeometry, style, feature); + } else { + const geometryRenderer = GEOMETRY_RENDERERS[simplifiedGeometry.getType()]; + geometryRenderer( + replayGroup, + simplifiedGeometry, + style, + feature, + declutterBuilderGroup + ); + } +} +function renderGeometry(replayGroup, geometry, style, feature) { + if (geometry.getType() == "GeometryCollection") { + const geometries = ( + /** @type {import("../geom/GeometryCollection.js").default} */ + geometry.getGeometries() + ); + for (let i = 0, ii = geometries.length; i < ii; ++i) { + renderGeometry(replayGroup, geometries[i], style, feature); + } + return; + } + const replay = replayGroup.getBuilder(style.getZIndex(), "Default"); + replay.drawCustom( + /** @type {import("../geom/SimpleGeometry.js").default} */ + geometry, + feature, + style.getRenderer(), + style.getHitDetectionRenderer() + ); +} +function renderGeometryCollectionGeometry(replayGroup, geometry, style, feature, declutterBuilderGroup) { + const geometries = geometry.getGeometriesArray(); + let i, ii; + for (i = 0, ii = geometries.length; i < ii; ++i) { + const geometryRenderer = GEOMETRY_RENDERERS[geometries[i].getType()]; + geometryRenderer( + replayGroup, + geometries[i], + style, + feature, + declutterBuilderGroup + ); + } +} +function renderLineStringGeometry(builderGroup, geometry, style, feature, declutterBuilderGroup) { + const strokeStyle = style.getStroke(); + if (strokeStyle) { + const lineStringReplay = builderGroup.getBuilder( + style.getZIndex(), + "LineString" + ); + lineStringReplay.setFillStrokeStyle(null, strokeStyle); + lineStringReplay.drawLineString(geometry, feature); + } + const textStyle = style.getText(); + if (textStyle && textStyle.getText()) { + const textReplay = (declutterBuilderGroup || builderGroup).getBuilder( + style.getZIndex(), + "Text" + ); + textReplay.setTextStyle(textStyle); + textReplay.drawText(geometry, feature); + } +} +function renderMultiLineStringGeometry(builderGroup, geometry, style, feature, declutterBuilderGroup) { + const strokeStyle = style.getStroke(); + if (strokeStyle) { + const lineStringReplay = builderGroup.getBuilder( + style.getZIndex(), + "LineString" + ); + lineStringReplay.setFillStrokeStyle(null, strokeStyle); + lineStringReplay.drawMultiLineString(geometry, feature); + } + const textStyle = style.getText(); + if (textStyle && textStyle.getText()) { + const textReplay = (declutterBuilderGroup || builderGroup).getBuilder( + style.getZIndex(), + "Text" + ); + textReplay.setTextStyle(textStyle); + textReplay.drawText(geometry, feature); + } +} +function renderMultiPolygonGeometry(builderGroup, geometry, style, feature, declutterBuilderGroup) { + const fillStyle = style.getFill(); + const strokeStyle = style.getStroke(); + if (strokeStyle || fillStyle) { + const polygonReplay = builderGroup.getBuilder(style.getZIndex(), "Polygon"); + polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle); + polygonReplay.drawMultiPolygon(geometry, feature); + } + const textStyle = style.getText(); + if (textStyle && textStyle.getText()) { + const textReplay = (declutterBuilderGroup || builderGroup).getBuilder( + style.getZIndex(), + "Text" + ); + textReplay.setTextStyle(textStyle); + textReplay.drawText(geometry, feature); + } +} +function renderPointGeometry(builderGroup, geometry, style, feature, declutterBuilderGroup) { + const imageStyle = style.getImage(); + const textStyle = style.getText(); + let declutterImageWithText; + if (imageStyle) { + if (imageStyle.getImageState() != ImageState.LOADED) { + return; + } + let imageBuilderGroup = builderGroup; + if (declutterBuilderGroup) { + const declutterMode = imageStyle.getDeclutterMode(); + if (declutterMode !== "none") { + imageBuilderGroup = declutterBuilderGroup; + if (declutterMode === "obstacle") { + const imageReplay2 = builderGroup.getBuilder( + style.getZIndex(), + "Image" + ); + imageReplay2.setImageStyle(imageStyle, declutterImageWithText); + imageReplay2.drawPoint(geometry, feature); + } else if (textStyle && textStyle.getText()) { + declutterImageWithText = {}; + } + } + } + const imageReplay = imageBuilderGroup.getBuilder( + style.getZIndex(), + "Image" + ); + imageReplay.setImageStyle(imageStyle, declutterImageWithText); + imageReplay.drawPoint(geometry, feature); + } + if (textStyle && textStyle.getText()) { + let textBuilderGroup = builderGroup; + if (declutterBuilderGroup) { + textBuilderGroup = declutterBuilderGroup; + } + const textReplay = textBuilderGroup.getBuilder(style.getZIndex(), "Text"); + textReplay.setTextStyle(textStyle, declutterImageWithText); + textReplay.drawText(geometry, feature); + } +} +function renderMultiPointGeometry(builderGroup, geometry, style, feature, declutterBuilderGroup) { + const imageStyle = style.getImage(); + const textStyle = style.getText(); + let declutterImageWithText; + if (imageStyle) { + if (imageStyle.getImageState() != ImageState.LOADED) { + return; + } + let imageBuilderGroup = builderGroup; + if (declutterBuilderGroup) { + const declutterMode = imageStyle.getDeclutterMode(); + if (declutterMode !== "none") { + imageBuilderGroup = declutterBuilderGroup; + if (declutterMode === "obstacle") { + const imageReplay2 = builderGroup.getBuilder( + style.getZIndex(), + "Image" + ); + imageReplay2.setImageStyle(imageStyle, declutterImageWithText); + imageReplay2.drawMultiPoint(geometry, feature); + } else if (textStyle && textStyle.getText()) { + declutterImageWithText = {}; + } + } + } + const imageReplay = imageBuilderGroup.getBuilder( + style.getZIndex(), + "Image" + ); + imageReplay.setImageStyle(imageStyle, declutterImageWithText); + imageReplay.drawMultiPoint(geometry, feature); + } + if (textStyle && textStyle.getText()) { + let textBuilderGroup = builderGroup; + if (declutterBuilderGroup) { + textBuilderGroup = declutterBuilderGroup; + } + const textReplay = textBuilderGroup.getBuilder(style.getZIndex(), "Text"); + textReplay.setTextStyle(textStyle, declutterImageWithText); + textReplay.drawText(geometry, feature); + } +} +function renderPolygonGeometry(builderGroup, geometry, style, feature, declutterBuilderGroup) { + const fillStyle = style.getFill(); + const strokeStyle = style.getStroke(); + if (fillStyle || strokeStyle) { + const polygonReplay = builderGroup.getBuilder(style.getZIndex(), "Polygon"); + polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle); + polygonReplay.drawPolygon(geometry, feature); + } + const textStyle = style.getText(); + if (textStyle && textStyle.getText()) { + const textReplay = (declutterBuilderGroup || builderGroup).getBuilder( + style.getZIndex(), + "Text" + ); + textReplay.setTextStyle(textStyle); + textReplay.drawText(geometry, feature); + } +} +class CanvasVectorLayerRenderer extends CanvasLayerRenderer$1 { + /** + * @param {import("../../layer/BaseVector.js").default} vectorLayer Vector layer. + */ + constructor(vectorLayer) { + super(vectorLayer); + this.boundHandleStyleImageChange_ = this.handleStyleImageChange_.bind(this); + this.animatingOrInteracting_; + this.hitDetectionImageData_ = null; + this.renderedFeatures_ = null; + this.renderedRevision_ = -1; + this.renderedResolution_ = NaN; + this.renderedExtent_ = createEmpty(); + this.wrappedRenderedExtent_ = createEmpty(); + this.renderedRotation_; + this.renderedCenter_ = null; + this.renderedProjection_ = null; + this.renderedRenderOrder_ = null; + this.replayGroup_ = null; + this.replayGroupChanged = true; + this.declutterExecutorGroup = null; + this.clipping = true; + this.compositionContext_ = null; + this.opacity_ = 1; + } + /** + * @param {ExecutorGroup} executorGroup Executor group. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {import("rbush").default} [declutterTree] Declutter tree. + */ + renderWorlds(executorGroup, frameState, declutterTree) { + const extent = frameState.extent; + const viewState = frameState.viewState; + const center = viewState.center; + const resolution = viewState.resolution; + const projection = viewState.projection; + const rotation = viewState.rotation; + const projectionExtent = projection.getExtent(); + const vectorSource = this.getLayer().getSource(); + const pixelRatio = frameState.pixelRatio; + const viewHints = frameState.viewHints; + const snapToPixel = !(viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]); + const context = this.compositionContext_; + const width = Math.round(frameState.size[0] * pixelRatio); + const height = Math.round(frameState.size[1] * pixelRatio); + const multiWorld = vectorSource.getWrapX() && projection.canWrapX(); + const worldWidth = multiWorld ? getWidth(projectionExtent) : null; + const endWorld = multiWorld ? Math.ceil((extent[2] - projectionExtent[2]) / worldWidth) + 1 : 1; + let world = multiWorld ? Math.floor((extent[0] - projectionExtent[0]) / worldWidth) : 0; + do { + const transform2 = this.getRenderTransform( + center, + resolution, + rotation, + pixelRatio, + width, + height, + world * worldWidth + ); + executorGroup.execute( + context, + 1, + transform2, + rotation, + snapToPixel, + void 0, + declutterTree + ); + } while (++world < endWorld); + } + setupCompositionContext_() { + if (this.opacity_ !== 1) { + const compositionContext = createCanvasContext2D( + this.context.canvas.width, + this.context.canvas.height, + canvasPool + ); + this.compositionContext_ = compositionContext; + } else { + this.compositionContext_ = this.context; + } + } + releaseCompositionContext_() { + if (this.opacity_ !== 1) { + const alpha = this.context.globalAlpha; + this.context.globalAlpha = this.opacity_; + this.context.drawImage(this.compositionContext_.canvas, 0, 0); + this.context.globalAlpha = alpha; + releaseCanvas(this.compositionContext_); + canvasPool.push(this.compositionContext_.canvas); + this.compositionContext_ = null; + } + } + /** + * Render declutter items for this layer + * @param {import("../../Map.js").FrameState} frameState Frame state. + */ + renderDeclutter(frameState) { + if (this.declutterExecutorGroup) { + this.setupCompositionContext_(); + this.renderWorlds( + this.declutterExecutorGroup, + frameState, + frameState.declutterTree + ); + this.releaseCompositionContext_(); + } + } + /** + * Render the layer. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {HTMLElement|null} target Target that may be used to render content to. + * @return {HTMLElement|null} The rendered element. + */ + renderFrame(frameState, target) { + const pixelRatio = frameState.pixelRatio; + const layerState = frameState.layerStatesArray[frameState.layerIndex]; + makeScale(this.pixelTransform, 1 / pixelRatio, 1 / pixelRatio); + makeInverse(this.inversePixelTransform, this.pixelTransform); + const canvasTransform = toString$1(this.pixelTransform); + this.useContainer(target, canvasTransform, this.getBackground(frameState)); + const context = this.context; + const canvas = context.canvas; + const replayGroup = this.replayGroup_; + const declutterExecutorGroup = this.declutterExecutorGroup; + let render2 = replayGroup && !replayGroup.isEmpty() || declutterExecutorGroup && !declutterExecutorGroup.isEmpty(); + if (!render2) { + const hasRenderListeners = this.getLayer().hasListener(RenderEventType.PRERENDER) || this.getLayer().hasListener(RenderEventType.POSTRENDER); + if (!hasRenderListeners) { + return null; + } + } + const width = Math.round(frameState.size[0] * pixelRatio); + const height = Math.round(frameState.size[1] * pixelRatio); + if (canvas.width != width || canvas.height != height) { + canvas.width = width; + canvas.height = height; + if (canvas.style.transform !== canvasTransform) { + canvas.style.transform = canvasTransform; + } + } else if (!this.containerReused) { + context.clearRect(0, 0, width, height); + } + this.preRender(context, frameState); + const viewState = frameState.viewState; + viewState.projection; + this.opacity_ = layerState.opacity; + this.setupCompositionContext_(); + let clipped = false; + if (render2 && layerState.extent && this.clipping) { + const layerExtent = fromUserExtent(layerState.extent); + render2 = intersects$1(layerExtent, frameState.extent); + clipped = render2 && !containsExtent(layerExtent, frameState.extent); + if (clipped) { + this.clipUnrotated(this.compositionContext_, frameState, layerExtent); + } + } + if (render2) { + this.renderWorlds(replayGroup, frameState); + } + if (clipped) { + this.compositionContext_.restore(); + } + this.releaseCompositionContext_(); + this.postRender(context, frameState); + if (this.renderedRotation_ !== viewState.rotation) { + this.renderedRotation_ = viewState.rotation; + this.hitDetectionImageData_ = null; + } + return this.container; + } + /** + * Asynchronous layer level hit detection. + * @param {import("../../pixel.js").Pixel} pixel Pixel. + * @return {Promise>} Promise + * that resolves with an array of features. + */ + getFeatures(pixel) { + return new Promise((resolve) => { + if (!this.hitDetectionImageData_ && !this.animatingOrInteracting_) { + const size = [this.context.canvas.width, this.context.canvas.height]; + apply(this.pixelTransform, size); + const center = this.renderedCenter_; + const resolution = this.renderedResolution_; + const rotation = this.renderedRotation_; + const projection = this.renderedProjection_; + const extent = this.wrappedRenderedExtent_; + const layer = this.getLayer(); + const transforms2 = []; + const width = size[0] * HIT_DETECT_RESOLUTION; + const height = size[1] * HIT_DETECT_RESOLUTION; + transforms2.push( + this.getRenderTransform( + center, + resolution, + rotation, + HIT_DETECT_RESOLUTION, + width, + height, + 0 + ).slice() + ); + const source = layer.getSource(); + const projectionExtent = projection.getExtent(); + if (source.getWrapX() && projection.canWrapX() && !containsExtent(projectionExtent, extent)) { + let startX = extent[0]; + const worldWidth = getWidth(projectionExtent); + let world = 0; + let offsetX; + while (startX < projectionExtent[0]) { + --world; + offsetX = worldWidth * world; + transforms2.push( + this.getRenderTransform( + center, + resolution, + rotation, + HIT_DETECT_RESOLUTION, + width, + height, + offsetX + ).slice() + ); + startX += worldWidth; + } + world = 0; + startX = extent[2]; + while (startX > projectionExtent[2]) { + ++world; + offsetX = worldWidth * world; + transforms2.push( + this.getRenderTransform( + center, + resolution, + rotation, + HIT_DETECT_RESOLUTION, + width, + height, + offsetX + ).slice() + ); + startX -= worldWidth; + } + } + this.hitDetectionImageData_ = createHitDetectionImageData( + size, + transforms2, + this.renderedFeatures_, + layer.getStyleFunction(), + extent, + resolution, + rotation + ); + } + resolve( + hitDetect(pixel, this.renderedFeatures_, this.hitDetectionImageData_) + ); + }); + } + /** + * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {number} hitTolerance Hit tolerance in pixels. + * @param {import("../vector.js").FeatureCallback} callback Feature callback. + * @param {Array>} matches The hit detected matches with tolerance. + * @return {T|undefined} Callback result. + * @template T + */ + forEachFeatureAtCoordinate(coordinate, frameState, hitTolerance, callback, matches) { + if (!this.replayGroup_) { + return void 0; + } + const resolution = frameState.viewState.resolution; + const rotation = frameState.viewState.rotation; + const layer = this.getLayer(); + const features = {}; + const featureCallback = function(feature, geometry, distanceSq) { + const key = getUid(feature); + const match = features[key]; + if (!match) { + if (distanceSq === 0) { + features[key] = true; + return callback(feature, layer, geometry); + } + matches.push( + features[key] = { + feature, + layer, + geometry, + distanceSq, + callback + } + ); + } else if (match !== true && distanceSq < match.distanceSq) { + if (distanceSq === 0) { + features[key] = true; + matches.splice(matches.lastIndexOf(match), 1); + return callback(feature, layer, geometry); + } + match.geometry = geometry; + match.distanceSq = distanceSq; + } + return void 0; + }; + let result; + const executorGroups = [this.replayGroup_]; + if (this.declutterExecutorGroup) { + executorGroups.push(this.declutterExecutorGroup); + } + executorGroups.some((executorGroup) => { + return result = executorGroup.forEachFeatureAtCoordinate( + coordinate, + resolution, + rotation, + hitTolerance, + featureCallback, + executorGroup === this.declutterExecutorGroup && frameState.declutterTree ? frameState.declutterTree.all().map((item) => item.value) : null + ); + }); + return result; + } + /** + * Perform action necessary to get the layer rendered after new fonts have loaded + */ + handleFontsChanged() { + const layer = this.getLayer(); + if (layer.getVisible() && this.replayGroup_) { + layer.changed(); + } + } + /** + * Handle changes in image style state. + * @param {import("../../events/Event.js").default} event Image style change event. + * @private + */ + handleStyleImageChange_(event) { + this.renderIfReadyAndVisible(); + } + /** + * Determine whether render should be called. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @return {boolean} Layer is ready to be rendered. + */ + prepareFrame(frameState) { + const vectorLayer = this.getLayer(); + const vectorSource = vectorLayer.getSource(); + if (!vectorSource) { + return false; + } + const animating = frameState.viewHints[ViewHint.ANIMATING]; + const interacting = frameState.viewHints[ViewHint.INTERACTING]; + const updateWhileAnimating = vectorLayer.getUpdateWhileAnimating(); + const updateWhileInteracting = vectorLayer.getUpdateWhileInteracting(); + if (this.ready && !updateWhileAnimating && animating || !updateWhileInteracting && interacting) { + this.animatingOrInteracting_ = true; + return true; + } + this.animatingOrInteracting_ = false; + const frameStateExtent = frameState.extent; + const viewState = frameState.viewState; + const projection = viewState.projection; + const resolution = viewState.resolution; + const pixelRatio = frameState.pixelRatio; + const vectorLayerRevision = vectorLayer.getRevision(); + const vectorLayerRenderBuffer = vectorLayer.getRenderBuffer(); + let vectorLayerRenderOrder = vectorLayer.getRenderOrder(); + if (vectorLayerRenderOrder === void 0) { + vectorLayerRenderOrder = defaultOrder; + } + const center = viewState.center.slice(); + const extent = buffer( + frameStateExtent, + vectorLayerRenderBuffer * resolution + ); + const renderedExtent = extent.slice(); + const loadExtents = [extent.slice()]; + const projectionExtent = projection.getExtent(); + if (vectorSource.getWrapX() && projection.canWrapX() && !containsExtent(projectionExtent, frameState.extent)) { + const worldWidth = getWidth(projectionExtent); + const gutter = Math.max(getWidth(extent) / 2, worldWidth); + extent[0] = projectionExtent[0] - gutter; + extent[2] = projectionExtent[2] + gutter; + wrapX$1(center, projection); + const loadExtent = wrapX$2(loadExtents[0], projection); + if (loadExtent[0] < projectionExtent[0] && loadExtent[2] < projectionExtent[2]) { + loadExtents.push([ + loadExtent[0] + worldWidth, + loadExtent[1], + loadExtent[2] + worldWidth, + loadExtent[3] + ]); + } else if (loadExtent[0] > projectionExtent[0] && loadExtent[2] > projectionExtent[2]) { + loadExtents.push([ + loadExtent[0] - worldWidth, + loadExtent[1], + loadExtent[2] - worldWidth, + loadExtent[3] + ]); + } + } + if (this.ready && this.renderedResolution_ == resolution && this.renderedRevision_ == vectorLayerRevision && this.renderedRenderOrder_ == vectorLayerRenderOrder && containsExtent(this.wrappedRenderedExtent_, extent)) { + if (!equals$2(this.renderedExtent_, renderedExtent)) { + this.hitDetectionImageData_ = null; + this.renderedExtent_ = renderedExtent; + } + this.renderedCenter_ = center; + this.replayGroupChanged = false; + return true; + } + this.replayGroup_ = null; + const replayGroup = new CanvasBuilderGroup( + getTolerance(resolution, pixelRatio), + extent, + resolution, + pixelRatio + ); + let declutterBuilderGroup; + if (this.getLayer().getDeclutter()) { + declutterBuilderGroup = new CanvasBuilderGroup( + getTolerance(resolution, pixelRatio), + extent, + resolution, + pixelRatio + ); + } + let userTransform; + { + for (let i = 0, ii = loadExtents.length; i < ii; ++i) { + vectorSource.loadFeatures(loadExtents[i], resolution, projection); + } + } + const squaredTolerance = getSquaredTolerance(resolution, pixelRatio); + let ready = true; + const render2 = ( + /** + * @param {import("../../Feature.js").default} feature Feature. + */ + (feature) => { + let styles; + const styleFunction = feature.getStyleFunction() || vectorLayer.getStyleFunction(); + if (styleFunction) { + styles = styleFunction(feature, resolution); + } + if (styles) { + const dirty = this.renderFeature( + feature, + squaredTolerance, + styles, + replayGroup, + userTransform, + declutterBuilderGroup + ); + ready = ready && !dirty; + } + } + ); + const userExtent = toUserExtent(extent); + const features = vectorSource.getFeaturesInExtent(userExtent); + if (vectorLayerRenderOrder) { + features.sort(vectorLayerRenderOrder); + } + for (let i = 0, ii = features.length; i < ii; ++i) { + render2(features[i]); + } + this.renderedFeatures_ = features; + this.ready = ready; + const replayGroupInstructions = replayGroup.finish(); + const executorGroup = new ExecutorGroup$1( + extent, + resolution, + pixelRatio, + vectorSource.getOverlaps(), + replayGroupInstructions, + vectorLayer.getRenderBuffer() + ); + if (declutterBuilderGroup) { + this.declutterExecutorGroup = new ExecutorGroup$1( + extent, + resolution, + pixelRatio, + vectorSource.getOverlaps(), + declutterBuilderGroup.finish(), + vectorLayer.getRenderBuffer() + ); + } + this.renderedResolution_ = resolution; + this.renderedRevision_ = vectorLayerRevision; + this.renderedRenderOrder_ = vectorLayerRenderOrder; + this.renderedExtent_ = renderedExtent; + this.wrappedRenderedExtent_ = extent; + this.renderedCenter_ = center; + this.renderedProjection_ = projection; + this.replayGroup_ = executorGroup; + this.hitDetectionImageData_ = null; + this.replayGroupChanged = true; + return true; + } + /** + * @param {import("../../Feature.js").default} feature Feature. + * @param {number} squaredTolerance Squared render tolerance. + * @param {import("../../style/Style.js").default|Array} styles The style or array of styles. + * @param {import("../../render/canvas/BuilderGroup.js").default} builderGroup Builder group. + * @param {import("../../proj.js").TransformFunction} [transform] Transform from user to view projection. + * @param {import("../../render/canvas/BuilderGroup.js").default} [declutterBuilderGroup] Builder for decluttering. + * @return {boolean} `true` if an image is loading. + */ + renderFeature(feature, squaredTolerance, styles, builderGroup, transform2, declutterBuilderGroup) { + if (!styles) { + return false; + } + let loading = false; + if (Array.isArray(styles)) { + for (let i = 0, ii = styles.length; i < ii; ++i) { + loading = renderFeature( + builderGroup, + feature, + styles[i], + squaredTolerance, + this.boundHandleStyleImageChange_, + transform2, + declutterBuilderGroup + ) || loading; + } + } else { + loading = renderFeature( + builderGroup, + feature, + styles, + squaredTolerance, + this.boundHandleStyleImageChange_, + transform2, + declutterBuilderGroup + ); + } + return loading; + } +} +const CanvasVectorLayerRenderer$1 = CanvasVectorLayerRenderer; +class VectorLayer extends BaseVectorLayer$1 { + /** + * @param {import("./BaseVector.js").Options} [options] Options. + */ + constructor(options) { + super(options); + } + createRenderer() { + return new CanvasVectorLayerRenderer$1(this); + } +} +const OlLayerVector = VectorLayer; +const TileProperty = { + PRELOAD: "preload", + USE_INTERIM_TILES_ON_ERROR: "useInterimTilesOnError" +}; +class BaseTileLayer extends Layer$1 { + /** + * @param {Options} [options] Tile layer options. + */ + constructor(options) { + options = options ? options : {}; + const baseOptions = Object.assign({}, options); + delete baseOptions.preload; + delete baseOptions.useInterimTilesOnError; + super(baseOptions); + this.on; + this.once; + this.un; + this.setPreload(options.preload !== void 0 ? options.preload : 0); + this.setUseInterimTilesOnError( + options.useInterimTilesOnError !== void 0 ? options.useInterimTilesOnError : true + ); + } + /** + * Return the level as number to which we will preload tiles up to. + * @return {number} The level to preload tiles up to. + * @observable + * @api + */ + getPreload() { + return ( + /** @type {number} */ + this.get(TileProperty.PRELOAD) + ); + } + /** + * Set the level as number to which we will preload tiles up to. + * @param {number} preload The level to preload tiles up to. + * @observable + * @api + */ + setPreload(preload) { + this.set(TileProperty.PRELOAD, preload); + } + /** + * Whether we use interim tiles on error. + * @return {boolean} Use interim tiles on error. + * @observable + * @api + */ + getUseInterimTilesOnError() { + return ( + /** @type {boolean} */ + this.get(TileProperty.USE_INTERIM_TILES_ON_ERROR) + ); + } + /** + * Set whether we use interim tiles on error. + * @param {boolean} useInterimTilesOnError Use interim tiles on error. + * @observable + * @api + */ + setUseInterimTilesOnError(useInterimTilesOnError) { + this.set(TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError); + } + /** + * Get data for a pixel location. The return type depends on the source data. For image tiles, + * a four element RGBA array will be returned. For data tiles, the array length will match the + * number of bands in the dataset. For requests outside the layer extent, `null` will be returned. + * Data for a image tiles can only be retrieved if the source's `crossOrigin` property is set. + * + * ```js + * // display layer data on every pointer move + * map.on('pointermove', (event) => { + * console.log(layer.getData(event.pixel)); + * }); + * ``` + * @param {import("../pixel").Pixel} pixel Pixel. + * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data. + * @api + */ + getData(pixel) { + return super.getData(pixel); + } +} +const BaseTileLayer$1 = BaseTileLayer; +class CanvasTileLayerRenderer extends CanvasLayerRenderer$1 { + /** + * @param {LayerType} tileLayer Tile layer. + */ + constructor(tileLayer) { + super(tileLayer); + this.extentChanged = true; + this.renderedExtent_ = null; + this.renderedPixelRatio; + this.renderedProjection = null; + this.renderedRevision; + this.renderedTiles = []; + this.newTiles_ = false; + this.tmpExtent = createEmpty(); + this.tmpTileRange_ = new TileRange$1(0, 0, 0, 0); + } + /** + * @protected + * @param {import("../../Tile.js").default} tile Tile. + * @return {boolean} Tile is drawable. + */ + isDrawableTile(tile) { + const tileLayer = this.getLayer(); + const tileState = tile.getState(); + const useInterimTilesOnError = tileLayer.getUseInterimTilesOnError(); + return tileState == TileState.LOADED || tileState == TileState.EMPTY || tileState == TileState.ERROR && !useInterimTilesOnError; + } + /** + * @param {number} z Tile coordinate z. + * @param {number} x Tile coordinate x. + * @param {number} y Tile coordinate y. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @return {!import("../../Tile.js").default} Tile. + */ + getTile(z, x, y, frameState) { + const pixelRatio = frameState.pixelRatio; + const projection = frameState.viewState.projection; + const tileLayer = this.getLayer(); + const tileSource = tileLayer.getSource(); + let tile = tileSource.getTile(z, x, y, pixelRatio, projection); + if (tile.getState() == TileState.ERROR) { + if (tileLayer.getUseInterimTilesOnError() && tileLayer.getPreload() > 0) { + this.newTiles_ = true; + } + } + if (!this.isDrawableTile(tile)) { + tile = tile.getInterimTile(); + } + return tile; + } + /** + * @param {import("../../pixel.js").Pixel} pixel Pixel. + * @return {Uint8ClampedArray} Data at the pixel location. + */ + getData(pixel) { + const frameState = this.frameState; + if (!frameState) { + return null; + } + const layer = this.getLayer(); + const coordinate = apply( + frameState.pixelToCoordinateTransform, + pixel.slice() + ); + const layerExtent = layer.getExtent(); + if (layerExtent) { + if (!containsCoordinate(layerExtent, coordinate)) { + return null; + } + } + const pixelRatio = frameState.pixelRatio; + const projection = frameState.viewState.projection; + const viewState = frameState.viewState; + const source = layer.getRenderSource(); + const tileGrid = source.getTileGridForProjection(viewState.projection); + const tilePixelRatio = source.getTilePixelRatio(frameState.pixelRatio); + for (let z = tileGrid.getZForResolution(viewState.resolution); z >= tileGrid.getMinZoom(); --z) { + const tileCoord = tileGrid.getTileCoordForCoordAndZ(coordinate, z); + const tile = source.getTile( + z, + tileCoord[1], + tileCoord[2], + pixelRatio, + projection + ); + if (!(tile instanceof ImageTile$1 || tile instanceof ReprojTile$1) || tile instanceof ReprojTile$1 && tile.getState() === TileState.EMPTY) { + return null; + } + if (tile.getState() !== TileState.LOADED) { + continue; + } + const tileOrigin = tileGrid.getOrigin(z); + const tileSize = toSize(tileGrid.getTileSize(z)); + const tileResolution = tileGrid.getResolution(z); + const col = Math.floor( + tilePixelRatio * ((coordinate[0] - tileOrigin[0]) / tileResolution - tileCoord[1] * tileSize[0]) + ); + const row = Math.floor( + tilePixelRatio * ((tileOrigin[1] - coordinate[1]) / tileResolution - tileCoord[2] * tileSize[1]) + ); + const gutter = Math.round( + tilePixelRatio * source.getGutterForProjection(viewState.projection) + ); + return this.getImageData(tile.getImage(), col + gutter, row + gutter); + } + return null; + } + /** + * @param {Object>} tiles Lookup of loaded tiles by zoom level. + * @param {number} zoom Zoom level. + * @param {import("../../Tile.js").default} tile Tile. + * @return {boolean|void} If `false`, the tile will not be considered loaded. + */ + loadedTileCallback(tiles, zoom, tile) { + if (this.isDrawableTile(tile)) { + return super.loadedTileCallback(tiles, zoom, tile); + } + return false; + } + /** + * Determine whether render should be called. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @return {boolean} Layer is ready to be rendered. + */ + prepareFrame(frameState) { + return !!this.getLayer().getSource(); + } + /** + * Render the layer. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {HTMLElement} target Target that may be used to render content to. + * @return {HTMLElement} The rendered element. + */ + renderFrame(frameState, target) { + const layerState = frameState.layerStatesArray[frameState.layerIndex]; + const viewState = frameState.viewState; + const projection = viewState.projection; + const viewResolution = viewState.resolution; + const viewCenter = viewState.center; + const rotation = viewState.rotation; + const pixelRatio = frameState.pixelRatio; + const tileLayer = this.getLayer(); + const tileSource = tileLayer.getSource(); + const sourceRevision = tileSource.getRevision(); + const tileGrid = tileSource.getTileGridForProjection(projection); + const z = tileGrid.getZForResolution(viewResolution, tileSource.zDirection); + const tileResolution = tileGrid.getResolution(z); + let extent = frameState.extent; + const resolution = frameState.viewState.resolution; + const tilePixelRatio = tileSource.getTilePixelRatio(pixelRatio); + const width = Math.round(getWidth(extent) / resolution * pixelRatio); + const height = Math.round(getHeight(extent) / resolution * pixelRatio); + const layerExtent = layerState.extent && fromUserExtent(layerState.extent); + if (layerExtent) { + extent = getIntersection( + extent, + fromUserExtent(layerState.extent) + ); + } + const dx = tileResolution * width / 2 / tilePixelRatio; + const dy = tileResolution * height / 2 / tilePixelRatio; + const canvasExtent = [ + viewCenter[0] - dx, + viewCenter[1] - dy, + viewCenter[0] + dx, + viewCenter[1] + dy + ]; + const tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z); + const tilesToDrawByZ = {}; + tilesToDrawByZ[z] = {}; + const findLoadedTiles = this.createLoadedTileFinder( + tileSource, + projection, + tilesToDrawByZ + ); + const tmpExtent2 = this.tmpExtent; + const tmpTileRange = this.tmpTileRange_; + this.newTiles_ = false; + const viewport = rotation ? getRotatedViewport( + viewState.center, + resolution, + rotation, + frameState.size + ) : void 0; + for (let x = tileRange.minX; x <= tileRange.maxX; ++x) { + for (let y = tileRange.minY; y <= tileRange.maxY; ++y) { + if (rotation && !tileGrid.tileCoordIntersectsViewport([z, x, y], viewport)) { + continue; + } + const tile = this.getTile(z, x, y, frameState); + if (this.isDrawableTile(tile)) { + const uid = getUid(this); + if (tile.getState() == TileState.LOADED) { + tilesToDrawByZ[z][tile.tileCoord.toString()] = tile; + let inTransition = tile.inTransition(uid); + if (inTransition && layerState.opacity !== 1) { + tile.endTransition(uid); + inTransition = false; + } + if (!this.newTiles_ && (inTransition || !this.renderedTiles.includes(tile))) { + this.newTiles_ = true; + } + } + if (tile.getAlpha(uid, frameState.time) === 1) { + continue; + } + } + const childTileRange = tileGrid.getTileCoordChildTileRange( + tile.tileCoord, + tmpTileRange, + tmpExtent2 + ); + let covered = false; + if (childTileRange) { + covered = findLoadedTiles(z + 1, childTileRange); + } + if (!covered) { + tileGrid.forEachTileCoordParentTileRange( + tile.tileCoord, + findLoadedTiles, + tmpTileRange, + tmpExtent2 + ); + } + } + } + const canvasScale = tileResolution / viewResolution * pixelRatio / tilePixelRatio; + compose( + this.pixelTransform, + frameState.size[0] / 2, + frameState.size[1] / 2, + 1 / pixelRatio, + 1 / pixelRatio, + rotation, + -width / 2, + -height / 2 + ); + const canvasTransform = toString$1(this.pixelTransform); + this.useContainer(target, canvasTransform, this.getBackground(frameState)); + const context = this.context; + const canvas = context.canvas; + makeInverse(this.inversePixelTransform, this.pixelTransform); + compose( + this.tempTransform, + width / 2, + height / 2, + canvasScale, + canvasScale, + 0, + -width / 2, + -height / 2 + ); + if (canvas.width != width || canvas.height != height) { + canvas.width = width; + canvas.height = height; + } else if (!this.containerReused) { + context.clearRect(0, 0, width, height); + } + if (layerExtent) { + this.clipUnrotated(context, frameState, layerExtent); + } + if (!tileSource.getInterpolate()) { + context.imageSmoothingEnabled = false; + } + this.preRender(context, frameState); + this.renderedTiles.length = 0; + let zs = Object.keys(tilesToDrawByZ).map(Number); + zs.sort(ascending); + let clips, clipZs, currentClip; + if (layerState.opacity === 1 && (!this.containerReused || tileSource.getOpaque(frameState.viewState.projection))) { + zs = zs.reverse(); + } else { + clips = []; + clipZs = []; + } + for (let i = zs.length - 1; i >= 0; --i) { + const currentZ = zs[i]; + const currentTilePixelSize = tileSource.getTilePixelSize( + currentZ, + pixelRatio, + projection + ); + const currentResolution = tileGrid.getResolution(currentZ); + const currentScale = currentResolution / tileResolution; + const dx2 = currentTilePixelSize[0] * currentScale * canvasScale; + const dy2 = currentTilePixelSize[1] * currentScale * canvasScale; + const originTileCoord = tileGrid.getTileCoordForCoordAndZ( + getTopLeft(canvasExtent), + currentZ + ); + const originTileExtent = tileGrid.getTileCoordExtent(originTileCoord); + const origin = apply(this.tempTransform, [ + tilePixelRatio * (originTileExtent[0] - canvasExtent[0]) / tileResolution, + tilePixelRatio * (canvasExtent[3] - originTileExtent[3]) / tileResolution + ]); + const tileGutter = tilePixelRatio * tileSource.getGutterForProjection(projection); + const tilesToDraw = tilesToDrawByZ[currentZ]; + for (const tileCoordKey in tilesToDraw) { + const tile = ( + /** @type {import("../../ImageTile.js").default} */ + tilesToDraw[tileCoordKey] + ); + const tileCoord = tile.tileCoord; + const xIndex = originTileCoord[1] - tileCoord[1]; + const nextX = Math.round(origin[0] - (xIndex - 1) * dx2); + const yIndex = originTileCoord[2] - tileCoord[2]; + const nextY = Math.round(origin[1] - (yIndex - 1) * dy2); + const x = Math.round(origin[0] - xIndex * dx2); + const y = Math.round(origin[1] - yIndex * dy2); + const w = nextX - x; + const h = nextY - y; + const transition = z === currentZ; + const inTransition = transition && tile.getAlpha(getUid(this), frameState.time) !== 1; + let contextSaved = false; + if (!inTransition) { + if (clips) { + currentClip = [x, y, x + w, y, x + w, y + h, x, y + h]; + for (let i2 = 0, ii = clips.length; i2 < ii; ++i2) { + if (z !== currentZ && currentZ < clipZs[i2]) { + const clip = clips[i2]; + if (intersects$1( + [x, y, x + w, y + h], + [clip[0], clip[3], clip[4], clip[7]] + )) { + if (!contextSaved) { + context.save(); + contextSaved = true; + } + context.beginPath(); + context.moveTo(currentClip[0], currentClip[1]); + context.lineTo(currentClip[2], currentClip[3]); + context.lineTo(currentClip[4], currentClip[5]); + context.lineTo(currentClip[6], currentClip[7]); + context.moveTo(clip[6], clip[7]); + context.lineTo(clip[4], clip[5]); + context.lineTo(clip[2], clip[3]); + context.lineTo(clip[0], clip[1]); + context.clip(); + } + } + } + clips.push(currentClip); + clipZs.push(currentZ); + } else { + context.clearRect(x, y, w, h); + } + } + this.drawTileImage( + tile, + frameState, + x, + y, + w, + h, + tileGutter, + transition + ); + if (clips && !inTransition) { + if (contextSaved) { + context.restore(); + } + this.renderedTiles.unshift(tile); + } else { + this.renderedTiles.push(tile); + } + this.updateUsedTiles(frameState.usedTiles, tileSource, tile); + } + } + this.renderedRevision = sourceRevision; + this.renderedResolution = tileResolution; + this.extentChanged = !this.renderedExtent_ || !equals$1(this.renderedExtent_, canvasExtent); + this.renderedExtent_ = canvasExtent; + this.renderedPixelRatio = pixelRatio; + this.renderedProjection = projection; + this.manageTilePyramid( + frameState, + tileSource, + tileGrid, + pixelRatio, + projection, + extent, + z, + tileLayer.getPreload() + ); + this.scheduleExpireCache(frameState, tileSource); + this.postRender(context, frameState); + if (layerState.extent) { + context.restore(); + } + context.imageSmoothingEnabled = true; + if (canvasTransform !== canvas.style.transform) { + canvas.style.transform = canvasTransform; + } + return this.container; + } + /** + * @param {import("../../ImageTile.js").default} tile Tile. + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {number} x Left of the tile. + * @param {number} y Top of the tile. + * @param {number} w Width of the tile. + * @param {number} h Height of the tile. + * @param {number} gutter Tile gutter. + * @param {boolean} transition Apply an alpha transition. + */ + drawTileImage(tile, frameState, x, y, w, h, gutter, transition) { + const image = this.getTileImage(tile); + if (!image) { + return; + } + const uid = getUid(this); + const layerState = frameState.layerStatesArray[frameState.layerIndex]; + const alpha = layerState.opacity * (transition ? tile.getAlpha(uid, frameState.time) : 1); + const alphaChanged = alpha !== this.context.globalAlpha; + if (alphaChanged) { + this.context.save(); + this.context.globalAlpha = alpha; + } + this.context.drawImage( + image, + gutter, + gutter, + image.width - 2 * gutter, + image.height - 2 * gutter, + x, + y, + w, + h + ); + if (alphaChanged) { + this.context.restore(); + } + if (alpha !== layerState.opacity) { + frameState.animate = true; + } else if (transition) { + tile.endTransition(uid); + } + } + /** + * @return {HTMLCanvasElement} Image + */ + getImage() { + const context = this.context; + return context ? context.canvas : null; + } + /** + * Get the image from a tile. + * @param {import("../../ImageTile.js").default} tile Tile. + * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image. + * @protected + */ + getTileImage(tile) { + return tile.getImage(); + } + /** + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {import("../../source/Tile.js").default} tileSource Tile source. + * @protected + */ + scheduleExpireCache(frameState, tileSource) { + if (tileSource.canExpireCache()) { + const postRenderFunction = (function(tileSource2, map, frameState2) { + const tileSourceKey = getUid(tileSource2); + if (tileSourceKey in frameState2.usedTiles) { + tileSource2.expireCache( + frameState2.viewState.projection, + frameState2.usedTiles[tileSourceKey] + ); + } + }).bind(null, tileSource); + frameState.postRenderFunctions.push( + /** @type {import("../../Map.js").PostRenderFunction} */ + postRenderFunction + ); + } + } + /** + * @param {!Object>} usedTiles Used tiles. + * @param {import("../../source/Tile.js").default} tileSource Tile source. + * @param {import('../../Tile.js').default} tile Tile. + * @protected + */ + updateUsedTiles(usedTiles, tileSource, tile) { + const tileSourceKey = getUid(tileSource); + if (!(tileSourceKey in usedTiles)) { + usedTiles[tileSourceKey] = {}; + } + usedTiles[tileSourceKey][tile.getKey()] = true; + } + /** + * Manage tile pyramid. + * This function performs a number of functions related to the tiles at the + * current zoom and lower zoom levels: + * - registers idle tiles in frameState.wantedTiles so that they are not + * discarded by the tile queue + * - enqueues missing tiles + * @param {import("../../Map.js").FrameState} frameState Frame state. + * @param {import("../../source/Tile.js").default} tileSource Tile source. + * @param {import("../../tilegrid/TileGrid.js").default} tileGrid Tile grid. + * @param {number} pixelRatio Pixel ratio. + * @param {import("../../proj/Projection.js").default} projection Projection. + * @param {import("../../extent.js").Extent} extent Extent. + * @param {number} currentZ Current Z. + * @param {number} preload Load low resolution tiles up to `preload` levels. + * @param {function(import("../../Tile.js").default):void} [tileCallback] Tile callback. + * @protected + */ + manageTilePyramid(frameState, tileSource, tileGrid, pixelRatio, projection, extent, currentZ, preload, tileCallback) { + const tileSourceKey = getUid(tileSource); + if (!(tileSourceKey in frameState.wantedTiles)) { + frameState.wantedTiles[tileSourceKey] = {}; + } + const wantedTiles = frameState.wantedTiles[tileSourceKey]; + const tileQueue = frameState.tileQueue; + const minZoom = tileGrid.getMinZoom(); + const rotation = frameState.viewState.rotation; + const viewport = rotation ? getRotatedViewport( + frameState.viewState.center, + frameState.viewState.resolution, + rotation, + frameState.size + ) : void 0; + let tileCount = 0; + let tile, tileRange, tileResolution, x, y, z; + for (z = minZoom; z <= currentZ; ++z) { + tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z, tileRange); + tileResolution = tileGrid.getResolution(z); + for (x = tileRange.minX; x <= tileRange.maxX; ++x) { + for (y = tileRange.minY; y <= tileRange.maxY; ++y) { + if (rotation && !tileGrid.tileCoordIntersectsViewport([z, x, y], viewport)) { + continue; + } + if (currentZ - z <= preload) { + ++tileCount; + tile = tileSource.getTile(z, x, y, pixelRatio, projection); + if (tile.getState() == TileState.IDLE) { + wantedTiles[tile.getKey()] = true; + if (!tileQueue.isKeyQueued(tile.getKey())) { + tileQueue.enqueue([ + tile, + tileSourceKey, + tileGrid.getTileCoordCenter(tile.tileCoord), + tileResolution + ]); + } + } + if (tileCallback !== void 0) { + tileCallback(tile); + } + } else { + tileSource.useTile(z, x, y, projection); + } + } + } + } + tileSource.updateCacheSize(tileCount, projection); + } +} +const CanvasTileLayerRenderer$1 = CanvasTileLayerRenderer; +class TileLayer extends BaseTileLayer$1 { + /** + * @param {import("./BaseTile.js").Options} [options] Tile layer options. + */ + constructor(options) { + super(options); + } + createRenderer() { + return new CanvasTileLayerRenderer$1(this); + } +} +const OlLayerTile = TileLayer; +const SelectEventType = { + /** + * Triggered when feature(s) has been (de)selected. + * @event SelectEvent#select + * @api + */ + SELECT: "select" +}; +class SelectEvent extends Event { + /** + * @param {SelectEventType} type The event type. + * @param {Array} selected Selected features. + * @param {Array} deselected Deselected features. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Associated + * {@link module:ol/MapBrowserEvent~MapBrowserEvent}. + */ + constructor(type, selected, deselected, mapBrowserEvent) { + super(type); + this.selected = selected; + this.deselected = deselected; + this.mapBrowserEvent = mapBrowserEvent; + } +} +const originalFeatureStyles = {}; +class Select extends Interaction$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + super(); + this.on; + this.once; + this.un; + options = options ? options : {}; + this.boundAddFeature_ = this.addFeature_.bind(this); + this.boundRemoveFeature_ = this.removeFeature_.bind(this); + this.condition_ = options.condition ? options.condition : singleClick; + this.addCondition_ = options.addCondition ? options.addCondition : never; + this.removeCondition_ = options.removeCondition ? options.removeCondition : never; + this.toggleCondition_ = options.toggleCondition ? options.toggleCondition : shiftKeyOnly; + this.multi_ = options.multi ? options.multi : false; + this.filter_ = options.filter ? options.filter : TRUE; + this.hitTolerance_ = options.hitTolerance ? options.hitTolerance : 0; + this.style_ = options.style !== void 0 ? options.style : getDefaultStyleFunction(); + this.features_ = options.features || new Collection$1(); + let layerFilter; + if (options.layers) { + if (typeof options.layers === "function") { + layerFilter = options.layers; + } else { + const layers = options.layers; + layerFilter = function(layer) { + return layers.includes(layer); + }; + } + } else { + layerFilter = TRUE; + } + this.layerFilter_ = layerFilter; + this.featureLayerAssociation_ = {}; + } + /** + * @param {import("../Feature.js").default} feature Feature. + * @param {import("../layer/Layer.js").default} layer Layer. + * @private + */ + addFeatureLayerAssociation_(feature, layer) { + this.featureLayerAssociation_[getUid(feature)] = layer; + } + /** + * Get the selected features. + * @return {Collection} Features collection. + * @api + */ + getFeatures() { + return this.features_; + } + /** + * Returns the Hit-detection tolerance. + * @return {number} Hit tolerance in pixels. + * @api + */ + getHitTolerance() { + return this.hitTolerance_; + } + /** + * Returns the associated {@link module:ol/layer/Vector~VectorLayer vector layer} of + * a selected feature. + * @param {import("../Feature.js").default} feature Feature + * @return {import('../layer/Vector.js').default} Layer. + * @api + */ + getLayer(feature) { + return ( + /** @type {import('../layer/Vector.js').default} */ + this.featureLayerAssociation_[getUid(feature)] + ); + } + /** + * Hit-detection tolerance. Pixels inside the radius around the given position + * will be checked for features. + * @param {number} hitTolerance Hit tolerance in pixels. + * @api + */ + setHitTolerance(hitTolerance) { + this.hitTolerance_ = hitTolerance; + } + /** + * Remove the interaction from its current map, if any, and attach it to a new + * map, if any. Pass `null` to just remove the interaction from the current map. + * @param {import("../Map.js").default|null} map Map. + * @api + */ + setMap(map) { + const currentMap = this.getMap(); + if (currentMap && this.style_) { + this.features_.forEach(this.restorePreviousStyle_.bind(this)); + } + super.setMap(map); + if (map) { + this.features_.addEventListener( + CollectionEventType.ADD, + this.boundAddFeature_ + ); + this.features_.addEventListener( + CollectionEventType.REMOVE, + this.boundRemoveFeature_ + ); + if (this.style_) { + this.features_.forEach(this.applySelectedStyle_.bind(this)); + } + } else { + this.features_.removeEventListener( + CollectionEventType.ADD, + this.boundAddFeature_ + ); + this.features_.removeEventListener( + CollectionEventType.REMOVE, + this.boundRemoveFeature_ + ); + } + } + /** + * @param {import("../Collection.js").CollectionEvent} evt Event. + * @private + */ + addFeature_(evt) { + const feature = evt.element; + if (this.style_) { + this.applySelectedStyle_(feature); + } + if (!this.getLayer(feature)) { + const layer = ( + /** @type {VectorLayer} */ + this.getMap().getAllLayers().find(function(layer2) { + if (layer2 instanceof OlLayerVector && layer2.getSource() && layer2.getSource().hasFeature(feature)) { + return layer2; + } + }) + ); + if (layer) { + this.addFeatureLayerAssociation_(feature, layer); + } + } + } + /** + * @param {import("../Collection.js").CollectionEvent} evt Event. + * @private + */ + removeFeature_(evt) { + if (this.style_) { + this.restorePreviousStyle_(evt.element); + } + } + /** + * @return {import("../style/Style.js").StyleLike|null} Select style. + */ + getStyle() { + return this.style_; + } + /** + * @param {Feature} feature Feature + * @private + */ + applySelectedStyle_(feature) { + const key = getUid(feature); + if (!(key in originalFeatureStyles)) { + originalFeatureStyles[key] = feature.getStyle(); + } + feature.setStyle(this.style_); + } + /** + * @param {Feature} feature Feature + * @private + */ + restorePreviousStyle_(feature) { + const interactions = this.getMap().getInteractions().getArray(); + for (let i = interactions.length - 1; i >= 0; --i) { + const interaction = interactions[i]; + if (interaction !== this && interaction instanceof Select && interaction.getStyle() && interaction.getFeatures().getArray().lastIndexOf(feature) !== -1) { + feature.setStyle(interaction.getStyle()); + return; + } + } + const key = getUid(feature); + feature.setStyle(originalFeatureStyles[key]); + delete originalFeatureStyles[key]; + } + /** + * @param {Feature} feature Feature. + * @private + */ + removeFeatureLayerAssociation_(feature) { + delete this.featureLayerAssociation_[getUid(feature)]; + } + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may change the + * selected state of features. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + */ + handleEvent(mapBrowserEvent) { + if (!this.condition_(mapBrowserEvent)) { + return true; + } + const add2 = this.addCondition_(mapBrowserEvent); + const remove = this.removeCondition_(mapBrowserEvent); + const toggle = this.toggleCondition_(mapBrowserEvent); + const set2 = !add2 && !remove && !toggle; + const map = mapBrowserEvent.map; + const features = this.getFeatures(); + const deselected = []; + const selected = []; + if (set2) { + clear(this.featureLayerAssociation_); + map.forEachFeatureAtPixel( + mapBrowserEvent.pixel, + /** + * @param {import("../Feature.js").FeatureLike} feature Feature. + * @param {import("../layer/Layer.js").default} layer Layer. + * @return {boolean|undefined} Continue to iterate over the features. + */ + (feature, layer) => { + if (!(feature instanceof Feature$1) || !this.filter_(feature, layer)) { + return; + } + this.addFeatureLayerAssociation_(feature, layer); + selected.push(feature); + return !this.multi_; + }, + { + layerFilter: this.layerFilter_, + hitTolerance: this.hitTolerance_ + } + ); + for (let i = features.getLength() - 1; i >= 0; --i) { + const feature = features.item(i); + const index = selected.indexOf(feature); + if (index > -1) { + selected.splice(index, 1); + } else { + features.remove(feature); + deselected.push(feature); + } + } + if (selected.length !== 0) { + features.extend(selected); + } + } else { + map.forEachFeatureAtPixel( + mapBrowserEvent.pixel, + /** + * @param {import("../Feature.js").FeatureLike} feature Feature. + * @param {import("../layer/Layer.js").default} layer Layer. + * @return {boolean|undefined} Continue to iterate over the features. + */ + (feature, layer) => { + if (!(feature instanceof Feature$1) || !this.filter_(feature, layer)) { + return; + } + if ((add2 || toggle) && !features.getArray().includes(feature)) { + this.addFeatureLayerAssociation_(feature, layer); + selected.push(feature); + } else if ((remove || toggle) && features.getArray().includes(feature)) { + deselected.push(feature); + this.removeFeatureLayerAssociation_(feature); + } + return !this.multi_; + }, + { + layerFilter: this.layerFilter_, + hitTolerance: this.hitTolerance_ + } + ); + for (let j = deselected.length - 1; j >= 0; --j) { + features.remove(deselected[j]); + } + features.extend(selected); + } + if (selected.length > 0 || deselected.length > 0) { + this.dispatchEvent( + new SelectEvent( + SelectEventType.SELECT, + selected, + deselected, + mapBrowserEvent + ) + ); + } + return true; + } +} +function getDefaultStyleFunction() { + const styles = createEditingStyle(); + extend$2(styles["Polygon"], styles["LineString"]); + extend$2(styles["GeometryCollection"], styles["LineString"]); + return function(feature) { + if (!feature.getGeometry()) { + return null; + } + return styles[feature.getGeometry().getType()]; + }; +} +const OlInteractionSelect = Select; +class TextFeature extends FeatureFormat { + constructor() { + super(); + } + /** + * @return {import("./Feature.js").Type} Format. + */ + getType() { + return "text"; + } + /** + * Read the feature from the source. + * + * @param {Document|Element|Object|string} source Source. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @return {import("../Feature.js").default} Feature. + * @api + */ + readFeature(source, options) { + return this.readFeatureFromText( + getText(source), + this.adaptOptions(options) + ); + } + /** + * @abstract + * @param {string} text Text. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {import("../Feature.js").default} Feature. + */ + readFeatureFromText(text, options) { + return abstract(); + } + /** + * Read the features from the source. + * + * @param {Document|Element|Object|string} source Source. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @return {Array} Features. + * @api + */ + readFeatures(source, options) { + return this.readFeaturesFromText( + getText(source), + this.adaptOptions(options) + ); + } + /** + * @abstract + * @param {string} text Text. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {Array} Features. + */ + readFeaturesFromText(text, options) { + return abstract(); + } + /** + * Read the geometry from the source. + * + * @param {Document|Element|Object|string} source Source. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @return {import("../geom/Geometry.js").default} Geometry. + * @api + */ + readGeometry(source, options) { + return this.readGeometryFromText( + getText(source), + this.adaptOptions(options) + ); + } + /** + * @abstract + * @param {string} text Text. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {import("../geom/Geometry.js").default} Geometry. + */ + readGeometryFromText(text, options) { + return abstract(); + } + /** + * Read the projection from the source. + * + * @param {Document|Element|Object|string} source Source. + * @return {import("../proj/Projection.js").default|undefined} Projection. + * @api + */ + readProjection(source) { + return this.readProjectionFromText(getText(source)); + } + /** + * @param {string} text Text. + * @protected + * @return {import("../proj/Projection.js").default|undefined} Projection. + */ + readProjectionFromText(text) { + return this.dataProjection; + } + /** + * Encode a feature as a string. + * + * @param {import("../Feature.js").default} feature Feature. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {string} Encoded feature. + * @api + */ + writeFeature(feature, options) { + return this.writeFeatureText(feature, this.adaptOptions(options)); + } + /** + * @abstract + * @param {import("../Feature.js").default} feature Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @protected + * @return {string} Text. + */ + writeFeatureText(feature, options) { + return abstract(); + } + /** + * Encode an array of features as string. + * + * @param {Array} features Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {string} Encoded features. + * @api + */ + writeFeatures(features, options) { + return this.writeFeaturesText(features, this.adaptOptions(options)); + } + /** + * @abstract + * @param {Array} features Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @protected + * @return {string} Text. + */ + writeFeaturesText(features, options) { + return abstract(); + } + /** + * Write a single geometry. + * + * @param {import("../geom/Geometry.js").default} geometry Geometry. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @return {string} Geometry. + * @api + */ + writeGeometry(geometry, options) { + return this.writeGeometryText(geometry, this.adaptOptions(options)); + } + /** + * @abstract + * @param {import("../geom/Geometry.js").default} geometry Geometry. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @protected + * @return {string} Text. + */ + writeGeometryText(geometry, options) { + return abstract(); + } +} +function getText(source) { + if (typeof source === "string") { + return source; + } + return ""; +} +const TextFeature$1 = TextFeature; +const GeometryConstructor = { + "POINT": OlPoint, + "LINESTRING": LineString$1, + "POLYGON": Polygon$1, + "MULTIPOINT": MultiPoint$1, + "MULTILINESTRING": MultiLineString$1, + "MULTIPOLYGON": MultiPolygon$1 +}; +const EMPTY = "EMPTY"; +const Z = "Z"; +const M = "M"; +const ZM = "ZM"; +const TokenType = { + START: 0, + TEXT: 1, + LEFT_PAREN: 2, + RIGHT_PAREN: 3, + NUMBER: 4, + COMMA: 5, + EOF: 6 +}; +const wktTypeLookup = { + Point: "POINT", + LineString: "LINESTRING", + Polygon: "POLYGON", + MultiPoint: "MULTIPOINT", + MultiLineString: "MULTILINESTRING", + MultiPolygon: "MULTIPOLYGON", + GeometryCollection: "GEOMETRYCOLLECTION", + Circle: "CIRCLE" +}; +class Lexer { + /** + * @param {string} wkt WKT string. + */ + constructor(wkt) { + this.wkt = wkt; + this.index_ = -1; + } + /** + * @param {string} c Character. + * @return {boolean} Whether the character is alphabetic. + * @private + */ + isAlpha_(c) { + return c >= "a" && c <= "z" || c >= "A" && c <= "Z"; + } + /** + * @param {string} c Character. + * @param {boolean} [decimal] Whether the string number + * contains a dot, i.e. is a decimal number. + * @return {boolean} Whether the character is numeric. + * @private + */ + isNumeric_(c, decimal) { + decimal = decimal !== void 0 ? decimal : false; + return c >= "0" && c <= "9" || c == "." && !decimal; + } + /** + * @param {string} c Character. + * @return {boolean} Whether the character is whitespace. + * @private + */ + isWhiteSpace_(c) { + return c == " " || c == " " || c == "\r" || c == "\n"; + } + /** + * @return {string} Next string character. + * @private + */ + nextChar_() { + return this.wkt.charAt(++this.index_); + } + /** + * Fetch and return the next token. + * @return {Token} Next string token. + */ + nextToken() { + const c = this.nextChar_(); + const position = this.index_; + let value = c; + let type; + if (c == "(") { + type = TokenType.LEFT_PAREN; + } else if (c == ",") { + type = TokenType.COMMA; + } else if (c == ")") { + type = TokenType.RIGHT_PAREN; + } else if (this.isNumeric_(c) || c == "-") { + type = TokenType.NUMBER; + value = this.readNumber_(); + } else if (this.isAlpha_(c)) { + type = TokenType.TEXT; + value = this.readText_(); + } else if (this.isWhiteSpace_(c)) { + return this.nextToken(); + } else if (c === "") { + type = TokenType.EOF; + } else { + throw new Error("Unexpected character: " + c); + } + return { position, value, type }; + } + /** + * @return {number} Numeric token value. + * @private + */ + readNumber_() { + let c; + const index = this.index_; + let decimal = false; + let scientificNotation = false; + do { + if (c == ".") { + decimal = true; + } else if (c == "e" || c == "E") { + scientificNotation = true; + } + c = this.nextChar_(); + } while (this.isNumeric_(c, decimal) || // if we haven't detected a scientific number before, 'e' or 'E' + // hint that we should continue to read + !scientificNotation && (c == "e" || c == "E") || // once we know that we have a scientific number, both '-' and '+' + // are allowed + scientificNotation && (c == "-" || c == "+")); + return parseFloat(this.wkt.substring(index, this.index_--)); + } + /** + * @return {string} String token value. + * @private + */ + readText_() { + let c; + const index = this.index_; + do { + c = this.nextChar_(); + } while (this.isAlpha_(c)); + return this.wkt.substring(index, this.index_--).toUpperCase(); + } +} +class Parser { + /** + * @param {Lexer} lexer The lexer. + */ + constructor(lexer) { + this.lexer_ = lexer; + this.token_ = { + position: 0, + type: TokenType.START + }; + this.layout_ = "XY"; + } + /** + * Fetch the next token form the lexer and replace the active token. + * @private + */ + consume_() { + this.token_ = this.lexer_.nextToken(); + } + /** + * Tests if the given type matches the type of the current token. + * @param {TokenType} type Token type. + * @return {boolean} Whether the token matches the given type. + */ + isTokenType(type) { + return this.token_.type == type; + } + /** + * If the given type matches the current token, consume it. + * @param {TokenType} type Token type. + * @return {boolean} Whether the token matches the given type. + */ + match(type) { + const isMatch = this.isTokenType(type); + if (isMatch) { + this.consume_(); + } + return isMatch; + } + /** + * Try to parse the tokens provided by the lexer. + * @return {import("../geom/Geometry.js").default} The geometry. + */ + parse() { + this.consume_(); + return this.parseGeometry_(); + } + /** + * Try to parse the dimensional info. + * @return {import("../geom/Geometry.js").GeometryLayout} The layout. + * @private + */ + parseGeometryLayout_() { + let layout = "XY"; + const dimToken = this.token_; + if (this.isTokenType(TokenType.TEXT)) { + const dimInfo = dimToken.value; + if (dimInfo === Z) { + layout = "XYZ"; + } else if (dimInfo === M) { + layout = "XYM"; + } else if (dimInfo === ZM) { + layout = "XYZM"; + } + if (layout !== "XY") { + this.consume_(); + } + } + return layout; + } + /** + * @return {Array} A collection of geometries. + * @private + */ + parseGeometryCollectionText_() { + if (this.match(TokenType.LEFT_PAREN)) { + const geometries = []; + do { + geometries.push(this.parseGeometry_()); + } while (this.match(TokenType.COMMA)); + if (this.match(TokenType.RIGHT_PAREN)) { + return geometries; + } + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array} All values in a point. + * @private + */ + parsePointText_() { + if (this.match(TokenType.LEFT_PAREN)) { + const coordinates2 = this.parsePoint_(); + if (this.match(TokenType.RIGHT_PAREN)) { + return coordinates2; + } + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array>} All points in a linestring. + * @private + */ + parseLineStringText_() { + if (this.match(TokenType.LEFT_PAREN)) { + const coordinates2 = this.parsePointList_(); + if (this.match(TokenType.RIGHT_PAREN)) { + return coordinates2; + } + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array>>} All points in a polygon. + * @private + */ + parsePolygonText_() { + if (this.match(TokenType.LEFT_PAREN)) { + const coordinates2 = this.parseLineStringTextList_(); + if (this.match(TokenType.RIGHT_PAREN)) { + return coordinates2; + } + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array>} All points in a multipoint. + * @private + */ + parseMultiPointText_() { + if (this.match(TokenType.LEFT_PAREN)) { + let coordinates2; + if (this.token_.type == TokenType.LEFT_PAREN) { + coordinates2 = this.parsePointTextList_(); + } else { + coordinates2 = this.parsePointList_(); + } + if (this.match(TokenType.RIGHT_PAREN)) { + return coordinates2; + } + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array>>} All linestring points + * in a multilinestring. + * @private + */ + parseMultiLineStringText_() { + if (this.match(TokenType.LEFT_PAREN)) { + const coordinates2 = this.parseLineStringTextList_(); + if (this.match(TokenType.RIGHT_PAREN)) { + return coordinates2; + } + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array>>>} All polygon points in a multipolygon. + * @private + */ + parseMultiPolygonText_() { + if (this.match(TokenType.LEFT_PAREN)) { + const coordinates2 = this.parsePolygonTextList_(); + if (this.match(TokenType.RIGHT_PAREN)) { + return coordinates2; + } + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array} A point. + * @private + */ + parsePoint_() { + const coordinates2 = []; + const dimensions = this.layout_.length; + for (let i = 0; i < dimensions; ++i) { + const token = this.token_; + if (this.match(TokenType.NUMBER)) { + coordinates2.push( + /** @type {number} */ + token.value + ); + } else { + break; + } + } + if (coordinates2.length == dimensions) { + return coordinates2; + } + throw new Error(this.formatErrorMessage_()); + } + /** + * @return {Array>} An array of points. + * @private + */ + parsePointList_() { + const coordinates2 = [this.parsePoint_()]; + while (this.match(TokenType.COMMA)) { + coordinates2.push(this.parsePoint_()); + } + return coordinates2; + } + /** + * @return {Array>} An array of points. + * @private + */ + parsePointTextList_() { + const coordinates2 = [this.parsePointText_()]; + while (this.match(TokenType.COMMA)) { + coordinates2.push(this.parsePointText_()); + } + return coordinates2; + } + /** + * @return {Array>>} An array of points. + * @private + */ + parseLineStringTextList_() { + const coordinates2 = [this.parseLineStringText_()]; + while (this.match(TokenType.COMMA)) { + coordinates2.push(this.parseLineStringText_()); + } + return coordinates2; + } + /** + * @return {Array>>>} An array of points. + * @private + */ + parsePolygonTextList_() { + const coordinates2 = [this.parsePolygonText_()]; + while (this.match(TokenType.COMMA)) { + coordinates2.push(this.parsePolygonText_()); + } + return coordinates2; + } + /** + * @return {boolean} Whether the token implies an empty geometry. + * @private + */ + isEmptyGeometry_() { + const isEmpty2 = this.isTokenType(TokenType.TEXT) && this.token_.value == EMPTY; + if (isEmpty2) { + this.consume_(); + } + return isEmpty2; + } + /** + * Create an error message for an unexpected token error. + * @return {string} Error message. + * @private + */ + formatErrorMessage_() { + return "Unexpected `" + this.token_.value + "` at position " + this.token_.position + " in `" + this.lexer_.wkt + "`"; + } + /** + * @return {import("../geom/Geometry.js").default} The geometry. + * @private + */ + parseGeometry_() { + const token = this.token_; + if (this.match(TokenType.TEXT)) { + const geomType = ( + /** @type {string} */ + token.value + ); + this.layout_ = this.parseGeometryLayout_(); + const isEmpty2 = this.isEmptyGeometry_(); + if (geomType == "GEOMETRYCOLLECTION") { + if (isEmpty2) { + return new GeometryCollection$1([]); + } + const geometries = this.parseGeometryCollectionText_(); + return new GeometryCollection$1(geometries); + } + const ctor = GeometryConstructor[geomType]; + if (!ctor) { + throw new Error("Invalid geometry type: " + geomType); + } + let coordinates2; + if (isEmpty2) { + if (geomType == "POINT") { + coordinates2 = [NaN, NaN]; + } else { + coordinates2 = []; + } + } else { + switch (geomType) { + case "POINT": { + coordinates2 = this.parsePointText_(); + break; + } + case "LINESTRING": { + coordinates2 = this.parseLineStringText_(); + break; + } + case "POLYGON": { + coordinates2 = this.parsePolygonText_(); + break; + } + case "MULTIPOINT": { + coordinates2 = this.parseMultiPointText_(); + break; + } + case "MULTILINESTRING": { + coordinates2 = this.parseMultiLineStringText_(); + break; + } + case "MULTIPOLYGON": { + coordinates2 = this.parseMultiPolygonText_(); + break; + } + } + } + return new ctor(coordinates2, this.layout_); + } + throw new Error(this.formatErrorMessage_()); + } +} +class WKT extends TextFeature$1 { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + super(); + options = options ? options : {}; + this.splitCollection_ = options.splitCollection !== void 0 ? options.splitCollection : false; + } + /** + * Parse a WKT string. + * @param {string} wkt WKT string. + * @return {import("../geom/Geometry.js").default} + * The geometry created. + * @private + */ + parse_(wkt) { + const lexer = new Lexer(wkt); + const parser = new Parser(lexer); + return parser.parse(); + } + /** + * @protected + * @param {string} text Text. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @return {import("../Feature.js").default} Feature. + */ + readFeatureFromText(text, options) { + const geom = this.readGeometryFromText(text, options); + const feature = new Feature$1(); + feature.setGeometry(geom); + return feature; + } + /** + * @param {string} text Text. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {Array} Features. + */ + readFeaturesFromText(text, options) { + let geometries = []; + const geometry = this.readGeometryFromText(text, options); + if (this.splitCollection_ && geometry.getType() == "GeometryCollection") { + geometries = /** @type {GeometryCollection} */ + geometry.getGeometriesArray(); + } else { + geometries = [geometry]; + } + const features = []; + for (let i = 0, ii = geometries.length; i < ii; ++i) { + const feature = new Feature$1(); + feature.setGeometry(geometries[i]); + features.push(feature); + } + return features; + } + /** + * @param {string} text Text. + * @param {import("./Feature.js").ReadOptions} [options] Read options. + * @protected + * @return {import("../geom/Geometry.js").default} Geometry. + */ + readGeometryFromText(text, options) { + const geometry = this.parse_(text); + return transformGeometryWithOptions(geometry, false, options); + } + /** + * @param {import("../Feature.js").default} feature Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @protected + * @return {string} Text. + */ + writeFeatureText(feature, options) { + const geometry = feature.getGeometry(); + if (geometry) { + return this.writeGeometryText(geometry, options); + } + return ""; + } + /** + * @param {Array} features Features. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @protected + * @return {string} Text. + */ + writeFeaturesText(features, options) { + if (features.length == 1) { + return this.writeFeatureText(features[0], options); + } + const geometries = []; + for (let i = 0, ii = features.length; i < ii; ++i) { + geometries.push(features[i].getGeometry()); + } + const collection = new GeometryCollection$1(geometries); + return this.writeGeometryText(collection, options); + } + /** + * @param {import("../geom/Geometry.js").default} geometry Geometry. + * @param {import("./Feature.js").WriteOptions} [options] Write options. + * @protected + * @return {string} Text. + */ + writeGeometryText(geometry, options) { + return encode(transformGeometryWithOptions(geometry, true, options)); + } +} +function encodePointGeometry(geom) { + const coordinates2 = geom.getCoordinates(); + if (coordinates2.length === 0) { + return ""; + } + return coordinates2.join(" "); +} +function encodeMultiPointGeometry(geom) { + const array = []; + const components = geom.getPoints(); + for (let i = 0, ii = components.length; i < ii; ++i) { + array.push("(" + encodePointGeometry(components[i]) + ")"); + } + return array.join(","); +} +function encodeGeometryCollectionGeometry(geom) { + const array = []; + const geoms = geom.getGeometries(); + for (let i = 0, ii = geoms.length; i < ii; ++i) { + array.push(encode(geoms[i])); + } + return array.join(","); +} +function encodeLineStringGeometry(geom) { + const coordinates2 = geom.getCoordinates(); + const array = []; + for (let i = 0, ii = coordinates2.length; i < ii; ++i) { + array.push(coordinates2[i].join(" ")); + } + return array.join(","); +} +function encodeMultiLineStringGeometry(geom) { + const array = []; + const components = geom.getLineStrings(); + for (let i = 0, ii = components.length; i < ii; ++i) { + array.push("(" + encodeLineStringGeometry(components[i]) + ")"); + } + return array.join(","); +} +function encodePolygonGeometry(geom) { + const array = []; + const rings = geom.getLinearRings(); + for (let i = 0, ii = rings.length; i < ii; ++i) { + array.push("(" + encodeLineStringGeometry(rings[i]) + ")"); + } + return array.join(","); +} +function encodeMultiPolygonGeometry(geom) { + const array = []; + const components = geom.getPolygons(); + for (let i = 0, ii = components.length; i < ii; ++i) { + array.push("(" + encodePolygonGeometry(components[i]) + ")"); + } + return array.join(","); +} +function encodeGeometryLayout(geom) { + const layout = geom.getLayout(); + let dimInfo = ""; + if (layout === "XYZ" || layout === "XYZM") { + dimInfo += Z; + } + if (layout === "XYM" || layout === "XYZM") { + dimInfo += M; + } + return dimInfo; +} +const GeometryEncoder = { + "Point": encodePointGeometry, + "LineString": encodeLineStringGeometry, + "Polygon": encodePolygonGeometry, + "MultiPoint": encodeMultiPointGeometry, + "MultiLineString": encodeMultiLineStringGeometry, + "MultiPolygon": encodeMultiPolygonGeometry, + "GeometryCollection": encodeGeometryCollectionGeometry +}; +function encode(geom) { + const type = geom.getType(); + const geometryEncoder = GeometryEncoder[type]; + const enc = geometryEncoder(geom); + let wktType = wktTypeLookup[type]; + if (typeof /** @type {?} */ + geom.getFlatCoordinates === "function") { + const dimInfo = encodeGeometryLayout( + /** @type {import("../geom/SimpleGeometry.js").default} */ + geom + ); + if (dimInfo.length > 0) { + wktType += " " + dimInfo; + } + } + if (enc.length === 0) { + return wktType + " " + EMPTY; + } + return wktType + "(" + enc + ")"; +} +const OlFormatWkt = WKT; +function init_wrmap(_, jq_map_element) { + var _a, _b, _c, _d, _e; + let EPSG4326 = get$1("EPSG:4326"); + let EPSG3857 = get$1("EPSG:3857"); + function createElement(tagName, attributes = {}) { + let element = $(document.createElement(tagName)); + for (let attribute in attributes) { + element.attr(attribute, attributes[attribute]); + } + return element; + } + function appendElement(parentElement, tagName, attributes = {}) { + let element = createElement(tagName, attributes); + parentElement.append(element); + return element; + } + let jq_map = $(jq_map_element); + let ext_path = jq_map.attr("data-ext-path"); + let img_path = ext_path + "/img"; + let json_string = jq_map.children().last().text(); + jq_map.empty(); + let json_js = JSON.parse(json_string); + let format_geojson = new OlGeoJson(); + let features_all = format_geojson.readFeatures(json_js, { dataProjection: EPSG4326, featureProjection: EPSG3857 }); + function get_feature_title(feature) { + let title = feature.get("type"); + if (title == "sledrun") + return feature.get("name"); + title = title.charAt(0).toUpperCase() + title.slice(1); + if (feature.get("name")) + title += ": " + feature.get("name"); + return title; + } + let get_sledrun_condition = function(feature) { + let condition = feature.get("condition"); + if (condition === void 0) + return 0; + return condition; + }; + function sledrun_icon_style(condition, highlight) { + let hl = highlight ? "h" : "n"; + let src = img_path + "/marker_c_sledrun_" + condition + "n" + hl + ".png"; + return new Style({ + image: new OlIcon({ + src, + size: [17, 17], + anchor: [0.5, 0.5] + }) + }); + } + function sledrun_icon_shadow_style() { + return new Style({ + image: new OlIcon({ + src: img_path + "/marker_c_shadow.png", + size: [23, 23], + anchor: [0.4, 0.4] + }) + }); + } + function marker_icon_style(feature) { + let src = img_path + "/marker_p_" + feature.get("type") + ".png"; + return new Style({ + image: new OlIcon({ + src, + size: [20, 34], + anchor: [0.5, 1] + }) + }); + } + function point_style(feature, highlight) { + let sledrun = feature.get("type") == "sledrun"; + let icon_style; + if (sledrun) { + let condition = get_sledrun_condition(feature); + icon_style = sledrun_icon_style(condition, highlight); + } else + icon_style = marker_icon_style(feature); + if (highlight) { + icon_style.setText(new OlText({ + text: get_feature_title(feature), + font: "icon", + offsetY: 14, + stroke: new OlStroke({ + color: "#ddd", + width: 2 + }) + })); + } + if (sledrun) { + let shadow_style = sledrun_icon_shadow_style(); + return [shadow_style, icon_style]; + } + return [icon_style]; + } + function style_point_function(feature, _resolution) { + return point_style(feature, false); + } + function style_point_function_highlight(feature, _resolution) { + return point_style(feature, true); + } + function style_path_function(feature, _resolution) { + let line_color = { + "rodelbahn": "#014e9a", + "gehweg": "#e98401", + "alternative": "#7f7fff", + "lift": "#000000", + "anfahrt": "#e1e100" + }; + let featureType = feature.get("type"); + let color = feature.get("strokeColor") || line_color[featureType] || "#e7525b"; + let width2 = ["lift", "anfahrt"].indexOf(feature.get("type")) >= 0 ? 3 : 6; + return new Style({ + stroke: new OlStroke({ + color, + width: width2 + }) + }); + } + function style_function(feature, resolution) { + if (feature.getGeometry() instanceof OlPoint) + return style_point_function(feature); + return style_path_function(feature); + } + function style_function_highlight(feature, resolution) { + if (feature.getGeometry() instanceof OlPoint) + return style_point_function_highlight(feature); + return style_path_function(feature); + } + let popup_container = document.createElement("div"); + popup_container.setAttribute("class", "ol-popup"); + popup_container = jq_map_element.insertAdjacentElement("afterend", popup_container); + let popup_closer = document.createElement("a"); + popup_closer.setAttribute("href", "#"); + popup_closer.setAttribute("class", "ol-popup-closer"); + popup_closer = popup_container.insertAdjacentElement("beforeend", popup_closer); + let popup_content = document.createElement("div"); + popup_content = popup_container.insertAdjacentElement("beforeend", popup_content); + let popup_overlay = new OlOverlay({ element: popup_container, autoPan: { animation: { duration: 250 } } }); + popup_closer.onclick = function() { + popup_overlay.setPosition(void 0); + popup_closer.blur(); + return false; + }; + function create_popup_dom(feature) { + let popup_div = createElement("div"); + if (feature.get("name") !== void 0 && (feature.get("wiki") !== void 0 || feature.get("thumb_url") !== void 0)) { + let h2 = appendElement(popup_div, "h2"); + if (feature.get("wiki") === void 0) + h2.text(feature.get("name")); + else + appendElement(h2, "a", { href: new mw.Title(feature.get("wiki")).getUrl({}) }).text(feature.get("name")); + } + if (feature.get("type") == "sledrun") { + let p = appendElement(popup_div, "p").text("Rodelbahnzustand").append(createElement("br")); + let wiki_title = new mw.Title(feature.get("wiki")); + if (feature.get("condition") !== void 0) { + let condition_text = { 1: "Sehr gut", 2: "Gut", 3: "Mittelmäßig", 4: "Schlecht", 5: "Geht nicht" }; + let condition = feature.get("condition"); + let year_month_day = feature.get("date_report").split("-"); + p.append(createElement("a", { href: wiki_title.getUrl({}) + "#Eintr.C3.A4ge" }).text(condition_text[condition]), " "); + p.append(createElement("small").text(year_month_day[2] + "." + year_month_day[1] + "."), " "); + p.append(createElement("em").append(createElement("a", { href: wiki_title.getUrl({}) + "#Eintragen" }).text("Neu"))); + } else { + p.append(createElement("em").append(createElement("a", { href: wiki_title.getUrl({}) + "#Eintragen" }).text("Bitte eintragen"))); + } + } + if (feature.get("wiki") !== void 0) { + let a = appendElement(appendElement(popup_div, "p"), "a", { href: new mw.Title(feature.get("wiki")).getUrl({}) }); + let detail_text = "Details"; + if (feature.get("type") == "sledrun") + detail_text += " zur Rodelbahn"; + if (feature.get("type") == "gasthaus") + detail_text += " zum Gasthaus"; + if (feature.get("thumb_url") !== void 0) { + a.append(createElement("img", { src: feature.get("thumb_url"), alt: detail_text, title: detail_text })); + } else { + a.text(detail_text); + let api = new mw.Api(); + api.get({ + action: "query", + prop: "pageimages", + pithumbsize: "200", + titles: feature.get("wiki") + }).done(function(data) { + var _a2; + let pages = (_a2 = data == null ? void 0 : data.query) == null ? void 0 : _a2.pages; + if (pages instanceof Object) { + for (let pageNumber in pages) { + let page = pages[pageNumber]; + let thumbnail = page.thumbnail; + if (thumbnail instanceof Object) { + a.empty(); + a.append(createElement("img", { src: thumbnail.source, alt: detail_text, title: detail_text, width: thumbnail.width, height: thumbnail.height })); + popup_overlay.panIntoView(); + } + } + } + }); + } + } + return popup_div; + } + let lon = ((_a = json_js.wr_properties) == null ? void 0 : _a.lon) ?? 11; + let lat = ((_b = json_js.wr_properties) == null ? void 0 : _b.lat) ?? 47; + let zoom = ((_c = json_js.wr_properties) == null ? void 0 : _c.zoom) ?? 10; + let width = ((_d = json_js.wr_properties) == null ? void 0 : _d.width) ?? "100%"; + let height = ((_e = json_js.properties) == null ? void 0 : _e.height) ?? 450; + jq_map.width(width); + jq_map.height(height); + let layer_sledrun_source = new OlSourceVector({ features: features_all }); + let layer_sledrun = new OlLayerVector({ + source: layer_sledrun_source, + style: style_function + }); + let map = new OlMap({ + target: jq_map[0], + layers: [ + layer_sledrun + ], + overlays: [popup_overlay], + view: new OlView({ + center: fromLonLat([lon, lat]), + zoom + }), + controls: defaults$1({ + attributionOptions: { + collapsible: false + } + }), + interactions: defaults({ + mouseWheelZoom: false, + dragPan: false + }).extend([ + new OlInteractionDragPan({ + condition: function(event) { + let dragPan = this; + return dragPan.getPointerCount() === 2 || platformModifierKeyOnly(event); + } + }), + new OlInteractionMouseWheelZoom({ + condition: platformModifierKeyOnly + }), + new OlInteractionSelect({ + condition: pointerMove, + style: style_function_highlight + }) + ]) + }); + let select_click = new OlInteractionSelect({ + condition: click, + style: null + }); + map.addInteraction(select_click); + select_click.on("select", function(event) { + if (event.selected.length > 0) { + let feature = event.selected[0]; + let geometry = feature.getGeometry(); + let coordinates2 = geometry.getFirstCoordinate(); + let popup_dom = create_popup_dom(feature); + if (popup_dom.children().length > 0) { + $(popup_content).empty().append(popup_dom); + popup_overlay.setPosition(coordinates2); + } + } + }); + function get_austria_feature() { + let austria_wkt = "POLYGON ((9.599 47.269, 9.767 47.523, 9.986 47.442, 10.192 47.234, 10.366 47.287, 10.488 47.497, 10.814 47.477, 11.052 47.349, 11.732 47.539, 12.211 47.578, 12.269 47.656, 12.474 47.593, 12.676 47.622, 12.839 47.471, 13.039 47.436, 13.120 47.661, 12.989 47.754, 13.019 47.900, 12.864 48.130, 13.419 48.328, 13.516 48.523, 13.769 48.509, 13.867 48.699, 14.173 48.535, 14.726 48.561, 14.851 48.728, 14.983 48.751, 15.036 48.954, 15.803 48.820, 16.041 48.711, 16.374 48.694, 16.496 48.754, 16.831 48.668, 16.800 48.376, 17.050 48.001, 16.985 47.742, 16.583 47.795, 16.363 47.696, 16.605 47.538, 16.379 47.412, 16.402 47.043, 15.994 46.879, 15.914 46.732, 14.874 46.649, 14.538 46.455, 12.501 46.715, 12.213 46.957, 12.267 47.065, 12.181 47.126, 11.762 47.031, 11.220 47.018, 10.925 46.815, 10.520 46.900, 10.359 47.029, 10.134 46.899, 9.674 47.095, 9.599 47.269))"; + let format = new OlFormatWkt(); + let feature = format.readFeature(austria_wkt, { + dataProjection: EPSG4326, + featureProjection: EPSG3857 + }); + return feature; + } + let austriaFeature = get_austria_feature(); + let austriaGeometry = austriaFeature.getGeometry(); + function is_in_austria(feature) { + let featureGeometry = feature.getGeometry(); + return austriaGeometry.intersectsCoordinate(featureGeometry.getFirstCoordinate()); + } + let austria_only = features_all.every(is_in_austria); + let capabilitiesUrl = austria_only ? "https://mapsneu.wien.gv.at/basemapneu/1.0.0/WMTSCapabilities.xml" : "https://mapsneu.wien.gv.at/vaoneu/1.0.0/WMTSCapabilities.xml"; + fetch(capabilitiesUrl).then(function(response) { + return response.text(); + }).then(function(text) { + let result = new OlFormatWmtsCapabilities().read(text); + let options = optionsFromCapabilities(result, { + layer: austria_only ? "bmapgrau" : "vaoausland", + matrixSet: "google3857", + style: "normal" + }); + options["attributions"] = austria_only ? 'Grundkarte: basemap.at' : 'Grundkarte: OpenStreetMap'; + let layer_map = new OlLayerTile({ + source: new OlSourceWmts(options) + }); + map.getLayers().insertAt(0, layer_map); + }); +} +function init_wrmaps() { + let jq_maps = $(".wrmap"); + jq_maps.each(init_wrmap); +} +$(init_wrmaps); +//# sourceMappingURL=wrmap.mjs.map diff --git a/dist/wrmap.mjs.map b/dist/wrmap.mjs.map new file mode 100644 index 0000000..09a17a1 --- /dev/null +++ b/dist/wrmap.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"wrmap.mjs","sources":["../node_modules/ol/events/Event.js","../node_modules/ol/ObjectEventType.js","../node_modules/ol/Disposable.js","../node_modules/ol/array.js","../node_modules/ol/functions.js","../node_modules/ol/obj.js","../node_modules/ol/events/Target.js","../node_modules/ol/events/EventType.js","../node_modules/ol/events.js","../node_modules/ol/Observable.js","../node_modules/ol/util.js","../node_modules/ol/Object.js","../node_modules/ol/CollectionEventType.js","../node_modules/ol/Collection.js","../node_modules/ol/has.js","../node_modules/ol/asserts.js","../node_modules/ol/transform.js","../node_modules/ol/extent/Relationship.js","../node_modules/ol/extent.js","../node_modules/ol/math.js","../node_modules/ol/color.js","../node_modules/ol/style/IconImageCache.js","../node_modules/ol/layer/Property.js","../node_modules/ol/layer/Base.js","../node_modules/ol/render/EventType.js","../node_modules/ol/ViewHint.js","../node_modules/ol/ViewProperty.js","../node_modules/ol/tilegrid/common.js","../node_modules/ol/proj/Units.js","../node_modules/ol/proj/Projection.js","../node_modules/ol/proj/epsg3857.js","../node_modules/ol/proj/epsg4326.js","../node_modules/ol/proj/projections.js","../node_modules/ol/proj/transforms.js","../node_modules/ol/coordinate.js","../node_modules/ol/sphere.js","../node_modules/ol/console.js","../node_modules/ol/proj.js","../node_modules/ol/centerconstraint.js","../node_modules/ol/resolutionconstraint.js","../node_modules/ol/rotationconstraint.js","../node_modules/ol/easing.js","../node_modules/ol/geom/flat/transform.js","../node_modules/ol/geom/Geometry.js","../node_modules/ol/geom/SimpleGeometry.js","../node_modules/ol/geom/flat/closest.js","../node_modules/ol/geom/flat/deflate.js","../node_modules/ol/geom/flat/simplify.js","../node_modules/ol/geom/flat/inflate.js","../node_modules/ol/geom/flat/area.js","../node_modules/ol/geom/LinearRing.js","../node_modules/ol/geom/Point.js","../node_modules/ol/geom/flat/contains.js","../node_modules/ol/geom/flat/interiorpoint.js","../node_modules/ol/geom/flat/segments.js","../node_modules/ol/geom/flat/intersectsextent.js","../node_modules/ol/geom/flat/reverse.js","../node_modules/ol/geom/flat/orient.js","../node_modules/ol/geom/Polygon.js","../node_modules/ol/View.js","../node_modules/ol/layer/Layer.js","../node_modules/ol/renderer/Map.js","../node_modules/ol/render/Event.js","../node_modules/ol/css.js","../node_modules/ol/dom.js","../node_modules/ol/render/canvas.js","../node_modules/ol/renderer/Composite.js","../node_modules/ol/layer/Group.js","../node_modules/ol/MapEvent.js","../node_modules/ol/MapBrowserEvent.js","../node_modules/ol/MapBrowserEventType.js","../node_modules/ol/pointer/EventType.js","../node_modules/ol/MapBrowserEventHandler.js","../node_modules/ol/MapEventType.js","../node_modules/ol/MapProperty.js","../node_modules/ol/structs/PriorityQueue.js","../node_modules/ol/TileState.js","../node_modules/ol/TileQueue.js","../node_modules/ol/control/Control.js","../node_modules/ol/control/Attribution.js","../node_modules/ol/control/Rotate.js","../node_modules/ol/control/Zoom.js","../node_modules/ol/control/defaults.js","../node_modules/ol/interaction/Property.js","../node_modules/ol/interaction/Interaction.js","../node_modules/ol/interaction/DoubleClickZoom.js","../node_modules/ol/interaction/Pointer.js","../node_modules/ol/events/condition.js","../node_modules/ol/interaction/DragPan.js","../node_modules/ol/interaction/DragRotate.js","../node_modules/ol/render/Box.js","../node_modules/ol/interaction/DragBox.js","../node_modules/ol/interaction/DragZoom.js","../node_modules/ol/events/Key.js","../node_modules/ol/interaction/KeyboardPan.js","../node_modules/ol/interaction/KeyboardZoom.js","../node_modules/ol/Kinetic.js","../node_modules/ol/interaction/MouseWheelZoom.js","../node_modules/ol/interaction/PinchRotate.js","../node_modules/ol/interaction/PinchZoom.js","../node_modules/ol/interaction/defaults.js","../node_modules/ol/size.js","../node_modules/ol/Map.js","../node_modules/ol/ImageState.js","../node_modules/ol/style/Image.js","../node_modules/ol/colorlike.js","../node_modules/ol/style/RegularShape.js","../node_modules/ol/style/Circle.js","../node_modules/ol/style/Fill.js","../node_modules/ol/style/Stroke.js","../node_modules/ol/style/Style.js","../node_modules/ol/style/Text.js","../node_modules/ol/Image.js","../node_modules/ol/style/IconImage.js","../node_modules/ol/style/Icon.js","../node_modules/ol/Feature.js","../node_modules/ol/geom/GeometryCollection.js","../node_modules/ol/format/Feature.js","../node_modules/ol/format/JSONFeature.js","../node_modules/ol/geom/flat/interpolate.js","../node_modules/ol/geom/flat/length.js","../node_modules/ol/geom/LineString.js","../node_modules/ol/geom/MultiLineString.js","../node_modules/ol/geom/MultiPoint.js","../node_modules/ol/geom/flat/center.js","../node_modules/ol/geom/MultiPolygon.js","../node_modules/ol/format/GeoJSON.js","../node_modules/ol/Overlay.js","../node_modules/quickselect/index.js","../node_modules/rbush/index.js","../node_modules/ol/structs/RBush.js","../node_modules/ol/source/Source.js","../node_modules/ol/source/VectorEventType.js","../node_modules/ol/loadingstrategy.js","../node_modules/ol/featureloader.js","../node_modules/ol/source/Vector.js","../node_modules/ol/Tile.js","../node_modules/ol/ImageTile.js","../node_modules/ol/reproj/common.js","../node_modules/ol/reproj/Triangulation.js","../node_modules/ol/reproj.js","../node_modules/ol/reproj/Tile.js","../node_modules/ol/structs/LRUCache.js","../node_modules/ol/tilecoord.js","../node_modules/ol/TileCache.js","../node_modules/ol/source/TileEventType.js","../node_modules/ol/TileRange.js","../node_modules/ol/tilegrid/TileGrid.js","../node_modules/ol/tilegrid.js","../node_modules/ol/source/Tile.js","../node_modules/ol/tileurlfunction.js","../node_modules/ol/source/UrlTile.js","../node_modules/ol/source/TileImage.js","../node_modules/ol/uri.js","../node_modules/ol/tilegrid/WMTS.js","../node_modules/ol/source/WMTS.js","../node_modules/ol/xml.js","../node_modules/ol/format/XML.js","../node_modules/ol/format/xlink.js","../node_modules/ol/format/xsd.js","../node_modules/ol/format/OWS.js","../node_modules/ol/format/WMTSCapabilities.js","../node_modules/ol/expr/expression.js","../node_modules/ol/expr/cpu.js","../node_modules/ol/render/canvas/style.js","../node_modules/ol/layer/BaseVector.js","../node_modules/ol/render/canvas/Instruction.js","../node_modules/ol/render/VectorContext.js","../node_modules/ol/render/canvas/Builder.js","../node_modules/ol/render/canvas/ImageBuilder.js","../node_modules/ol/render/canvas/LineStringBuilder.js","../node_modules/ol/render/canvas/PolygonBuilder.js","../node_modules/ol/geom/flat/linechunk.js","../node_modules/ol/geom/flat/straightchunk.js","../node_modules/ol/render/canvas/TextBuilder.js","../node_modules/ol/render/canvas/BuilderGroup.js","../node_modules/ol/renderer/Layer.js","../node_modules/ol/renderer/canvas/Layer.js","../node_modules/ol/geom/flat/textpath.js","../node_modules/ol/render/canvas/Executor.js","../node_modules/ol/render/canvas/ExecutorGroup.js","../node_modules/ol/render/canvas/Immediate.js","../node_modules/ol/render/canvas/hitdetect.js","../node_modules/ol/renderer/vector.js","../node_modules/ol/renderer/canvas/VectorLayer.js","../node_modules/ol/layer/Vector.js","../node_modules/ol/layer/TileProperty.js","../node_modules/ol/layer/BaseTile.js","../node_modules/ol/renderer/canvas/TileLayer.js","../node_modules/ol/layer/Tile.js","../node_modules/ol/interaction/Select.js","../node_modules/ol/format/TextFeature.js","../node_modules/ol/format/WKT.js","../src/wrmap.ts"],"sourcesContent":["/**\n * @module ol/events/Event\n */\n\n/**\n * @classdesc\n * Stripped down implementation of the W3C DOM Level 2 Event interface.\n * See https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface.\n *\n * This implementation only provides `type` and `target` properties, and\n * `stopPropagation` and `preventDefault` methods. It is meant as base class\n * for higher level events defined in the library, and works with\n * {@link module:ol/events/Target~Target}.\n */\nclass BaseEvent {\n /**\n * @param {string} type Type.\n */\n constructor(type) {\n /**\n * @type {boolean}\n */\n this.propagationStopped;\n\n /**\n * @type {boolean}\n */\n this.defaultPrevented;\n\n /**\n * The event type.\n * @type {string}\n * @api\n */\n this.type = type;\n\n /**\n * The event target.\n * @type {Object}\n * @api\n */\n this.target = null;\n }\n\n /**\n * Prevent default. This means that no emulated `click`, `singleclick` or `doubleclick` events\n * will be fired.\n * @api\n */\n preventDefault() {\n this.defaultPrevented = true;\n }\n\n /**\n * Stop event propagation.\n * @api\n */\n stopPropagation() {\n this.propagationStopped = true;\n }\n}\n\n/**\n * @param {Event|import(\"./Event.js\").default} evt Event\n */\nexport function stopPropagation(evt) {\n evt.stopPropagation();\n}\n\n/**\n * @param {Event|import(\"./Event.js\").default} evt Event\n */\nexport function preventDefault(evt) {\n evt.preventDefault();\n}\n\nexport default BaseEvent;\n","/**\n * @module ol/ObjectEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered when a property is changed.\n * @event module:ol/Object.ObjectEvent#propertychange\n * @api\n */\n PROPERTYCHANGE: 'propertychange',\n};\n\n/**\n * @typedef {'propertychange'} Types\n */\n","/**\n * @module ol/Disposable\n */\n\n/**\n * @classdesc\n * Objects that need to clean up after themselves.\n */\nclass Disposable {\n constructor() {\n /**\n * The object has already been disposed.\n * @type {boolean}\n * @protected\n */\n this.disposed = false;\n }\n\n /**\n * Clean up.\n */\n dispose() {\n if (!this.disposed) {\n this.disposed = true;\n this.disposeInternal();\n }\n }\n\n /**\n * Extension point for disposable objects.\n * @protected\n */\n disposeInternal() {}\n}\n\nexport default Disposable;\n","/**\n * @module ol/array\n */\n\n/**\n * Performs a binary search on the provided sorted list and returns the index of the item if found. If it can't be found it'll return -1.\n * https://github.com/darkskyapp/binary-search\n *\n * @param {Array<*>} haystack Items to search through.\n * @param {*} needle The item to look for.\n * @param {Function} [comparator] Comparator function.\n * @return {number} The index of the item if found, -1 if not.\n */\nexport function binarySearch(haystack, needle, comparator) {\n let mid, cmp;\n comparator = comparator || ascending;\n let low = 0;\n let high = haystack.length;\n let found = false;\n\n while (low < high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + ((high - low) >> 1);\n cmp = +comparator(haystack[mid], needle);\n\n if (cmp < 0.0) {\n /* Too low. */\n low = mid + 1;\n } else {\n /* Key found or too high */\n high = mid;\n found = !cmp;\n }\n }\n\n /* Key not found. */\n return found ? low : ~low;\n}\n\n/**\n * Compare function sorting arrays in ascending order. Safe to use for numeric values.\n * @param {*} a The first object to be compared.\n * @param {*} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is less than, equal to, or greater than the second.\n */\nexport function ascending(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n}\n\n/**\n * Compare function sorting arrays in descending order. Safe to use for numeric values.\n * @param {*} a The first object to be compared.\n * @param {*} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is greater than, equal to, or less than the second.\n */\nexport function descending(a, b) {\n return a < b ? 1 : a > b ? -1 : 0;\n}\n\n/**\n * {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution} can use a function\n * of this type to determine which nearest resolution to use.\n *\n * This function takes a `{number}` representing a value between two array entries,\n * a `{number}` representing the value of the nearest higher entry and\n * a `{number}` representing the value of the nearest lower entry\n * as arguments and returns a `{number}`. If a negative number or zero is returned\n * the lower value will be used, if a positive number is returned the higher value\n * will be used.\n * @typedef {function(number, number, number): number} NearestDirectionFunction\n * @api\n */\n\n/**\n * @param {Array} arr Array in descending order.\n * @param {number} target Target.\n * @param {number|NearestDirectionFunction} direction\n * 0 means return the nearest,\n * > 0 means return the largest nearest,\n * < 0 means return the smallest nearest.\n * @return {number} Index.\n */\nexport function linearFindNearest(arr, target, direction) {\n if (arr[0] <= target) {\n return 0;\n }\n\n const n = arr.length;\n if (target <= arr[n - 1]) {\n return n - 1;\n }\n\n if (typeof direction === 'function') {\n for (let i = 1; i < n; ++i) {\n const candidate = arr[i];\n if (candidate === target) {\n return i;\n }\n if (candidate < target) {\n if (direction(target, arr[i - 1], candidate) > 0) {\n return i - 1;\n }\n return i;\n }\n }\n return n - 1;\n }\n\n if (direction > 0) {\n for (let i = 1; i < n; ++i) {\n if (arr[i] < target) {\n return i - 1;\n }\n }\n return n - 1;\n }\n\n if (direction < 0) {\n for (let i = 1; i < n; ++i) {\n if (arr[i] <= target) {\n return i;\n }\n }\n return n - 1;\n }\n\n for (let i = 1; i < n; ++i) {\n if (arr[i] == target) {\n return i;\n }\n if (arr[i] < target) {\n if (arr[i - 1] - target < target - arr[i]) {\n return i - 1;\n }\n return i;\n }\n }\n return n - 1;\n}\n\n/**\n * @param {Array<*>} arr Array.\n * @param {number} begin Begin index.\n * @param {number} end End index.\n */\nexport function reverseSubArray(arr, begin, end) {\n while (begin < end) {\n const tmp = arr[begin];\n arr[begin] = arr[end];\n arr[end] = tmp;\n ++begin;\n --end;\n }\n}\n\n/**\n * @param {Array} arr The array to modify.\n * @param {!Array|VALUE} data The elements or arrays of elements to add to arr.\n * @template VALUE\n */\nexport function extend(arr, data) {\n const extension = Array.isArray(data) ? data : [data];\n const length = extension.length;\n for (let i = 0; i < length; i++) {\n arr[arr.length] = extension[i];\n }\n}\n\n/**\n * @param {Array} arr The array to modify.\n * @param {VALUE} obj The element to remove.\n * @template VALUE\n * @return {boolean} If the element was removed.\n */\nexport function remove(arr, obj) {\n const i = arr.indexOf(obj);\n const found = i > -1;\n if (found) {\n arr.splice(i, 1);\n }\n return found;\n}\n\n/**\n * @param {Array|Uint8ClampedArray} arr1 The first array to compare.\n * @param {Array|Uint8ClampedArray} arr2 The second array to compare.\n * @return {boolean} Whether the two arrays are equal.\n */\nexport function equals(arr1, arr2) {\n const len1 = arr1.length;\n if (len1 !== arr2.length) {\n return false;\n }\n for (let i = 0; i < len1; i++) {\n if (arr1[i] !== arr2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Sort the passed array such that the relative order of equal elements is preserved.\n * See https://en.wikipedia.org/wiki/Sorting_algorithm#Stability for details.\n * @param {Array<*>} arr The array to sort (modifies original).\n * @param {!function(*, *): number} compareFnc Comparison function.\n * @api\n */\nexport function stableSort(arr, compareFnc) {\n const length = arr.length;\n const tmp = Array(arr.length);\n let i;\n for (i = 0; i < length; i++) {\n tmp[i] = {index: i, value: arr[i]};\n }\n tmp.sort(function (a, b) {\n return compareFnc(a.value, b.value) || a.index - b.index;\n });\n for (i = 0; i < arr.length; i++) {\n arr[i] = tmp[i].value;\n }\n}\n\n/**\n * @param {Array<*>} arr The array to test.\n * @param {Function} [func] Comparison function.\n * @param {boolean} [strict] Strictly sorted (default false).\n * @return {boolean} Return index.\n */\nexport function isSorted(arr, func, strict) {\n const compare = func || ascending;\n return arr.every(function (currentVal, index) {\n if (index === 0) {\n return true;\n }\n const res = compare(arr[index - 1], currentVal);\n return !(res > 0 || (strict && res === 0));\n });\n}\n","/**\n * @module ol/functions\n */\n\nimport {equals as arrayEquals} from './array.js';\n\n/**\n * Always returns true.\n * @return {boolean} true.\n */\nexport function TRUE() {\n return true;\n}\n\n/**\n * Always returns false.\n * @return {boolean} false.\n */\nexport function FALSE() {\n return false;\n}\n\n/**\n * A reusable function, used e.g. as a default for callbacks.\n *\n * @return {void} Nothing.\n */\nexport function VOID() {}\n\n/**\n * Wrap a function in another function that remembers the last return. If the\n * returned function is called twice in a row with the same arguments and the same\n * this object, it will return the value from the first call in the second call.\n *\n * @param {function(...any): ReturnType} fn The function to memoize.\n * @return {function(...any): ReturnType} The memoized function.\n * @template ReturnType\n */\nexport function memoizeOne(fn) {\n let called = false;\n\n /** @type {ReturnType} */\n let lastResult;\n\n /** @type {Array} */\n let lastArgs;\n\n let lastThis;\n\n return function () {\n const nextArgs = Array.prototype.slice.call(arguments);\n if (!called || this !== lastThis || !arrayEquals(nextArgs, lastArgs)) {\n called = true;\n lastThis = this;\n lastArgs = nextArgs;\n lastResult = fn.apply(this, arguments);\n }\n return lastResult;\n };\n}\n\n/**\n * @template T\n * @param {function(): (T | Promise)} getter A function that returns a value or a promise for a value.\n * @return {Promise} A promise for the value.\n */\nexport function toPromise(getter) {\n function promiseGetter() {\n let value;\n try {\n value = getter();\n } catch (err) {\n return Promise.reject(err);\n }\n if (value instanceof Promise) {\n return value;\n }\n return Promise.resolve(value);\n }\n return promiseGetter();\n}\n","/**\n * @module ol/obj\n */\n\n/**\n * Removes all properties from an object.\n * @param {Object} object The object to clear.\n */\nexport function clear(object) {\n for (const property in object) {\n delete object[property];\n }\n}\n\n/**\n * Determine if an object has any properties.\n * @param {Object} object The object to check.\n * @return {boolean} The object is empty.\n */\nexport function isEmpty(object) {\n let property;\n for (property in object) {\n return false;\n }\n return !property;\n}\n","/**\n * @module ol/events/Target\n */\nimport Disposable from '../Disposable.js';\nimport Event from './Event.js';\nimport {VOID} from '../functions.js';\nimport {clear} from '../obj.js';\n\n/**\n * @typedef {EventTarget|Target} EventTargetLike\n */\n\n/**\n * @classdesc\n * A simplified implementation of the W3C DOM Level 2 EventTarget interface.\n * See https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget.\n *\n * There are two important simplifications compared to the specification:\n *\n * 1. The handling of `useCapture` in `addEventListener` and\n * `removeEventListener`. There is no real capture model.\n * 2. The handling of `stopPropagation` and `preventDefault` on `dispatchEvent`.\n * There is no event target hierarchy. When a listener calls\n * `stopPropagation` or `preventDefault` on an event object, it means that no\n * more listeners after this one will be called. Same as when the listener\n * returns false.\n */\nclass Target extends Disposable {\n /**\n * @param {*} [target] Default event target for dispatched events.\n */\n constructor(target) {\n super();\n\n /**\n * @private\n * @type {*}\n */\n this.eventTarget_ = target;\n\n /**\n * @private\n * @type {Object}\n */\n this.pendingRemovals_ = null;\n\n /**\n * @private\n * @type {Object}\n */\n this.dispatching_ = null;\n\n /**\n * @private\n * @type {Object>}\n */\n this.listeners_ = null;\n }\n\n /**\n * @param {string} type Type.\n * @param {import(\"../events.js\").Listener} listener Listener.\n */\n addEventListener(type, listener) {\n if (!type || !listener) {\n return;\n }\n const listeners = this.listeners_ || (this.listeners_ = {});\n const listenersForType = listeners[type] || (listeners[type] = []);\n if (!listenersForType.includes(listener)) {\n listenersForType.push(listener);\n }\n }\n\n /**\n * Dispatches an event and calls all listeners listening for events\n * of this type. The event parameter can either be a string or an\n * Object with a `type` property.\n *\n * @param {import(\"./Event.js\").default|string} event Event object.\n * @return {boolean|undefined} `false` if anyone called preventDefault on the\n * event object or if any of the listeners returned false.\n * @api\n */\n dispatchEvent(event) {\n const isString = typeof event === 'string';\n const type = isString ? event : event.type;\n const listeners = this.listeners_ && this.listeners_[type];\n if (!listeners) {\n return;\n }\n\n const evt = isString ? new Event(event) : /** @type {Event} */ (event);\n if (!evt.target) {\n evt.target = this.eventTarget_ || this;\n }\n const dispatching = this.dispatching_ || (this.dispatching_ = {});\n const pendingRemovals =\n this.pendingRemovals_ || (this.pendingRemovals_ = {});\n if (!(type in dispatching)) {\n dispatching[type] = 0;\n pendingRemovals[type] = 0;\n }\n ++dispatching[type];\n let propagate;\n for (let i = 0, ii = listeners.length; i < ii; ++i) {\n if ('handleEvent' in listeners[i]) {\n propagate = /** @type {import(\"../events.js\").ListenerObject} */ (\n listeners[i]\n ).handleEvent(evt);\n } else {\n propagate = /** @type {import(\"../events.js\").ListenerFunction} */ (\n listeners[i]\n ).call(this, evt);\n }\n if (propagate === false || evt.propagationStopped) {\n propagate = false;\n break;\n }\n }\n if (--dispatching[type] === 0) {\n let pr = pendingRemovals[type];\n delete pendingRemovals[type];\n while (pr--) {\n this.removeEventListener(type, VOID);\n }\n delete dispatching[type];\n }\n return propagate;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n this.listeners_ && clear(this.listeners_);\n }\n\n /**\n * Get the listeners for a specified event type. Listeners are returned in the\n * order that they will be called in.\n *\n * @param {string} type Type.\n * @return {Array|undefined} Listeners.\n */\n getListeners(type) {\n return (this.listeners_ && this.listeners_[type]) || undefined;\n }\n\n /**\n * @param {string} [type] Type. If not provided,\n * `true` will be returned if this event target has any listeners.\n * @return {boolean} Has listeners.\n */\n hasListener(type) {\n if (!this.listeners_) {\n return false;\n }\n return type\n ? type in this.listeners_\n : Object.keys(this.listeners_).length > 0;\n }\n\n /**\n * @param {string} type Type.\n * @param {import(\"../events.js\").Listener} listener Listener.\n */\n removeEventListener(type, listener) {\n const listeners = this.listeners_ && this.listeners_[type];\n if (listeners) {\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n if (this.pendingRemovals_ && type in this.pendingRemovals_) {\n // make listener a no-op, and remove later in #dispatchEvent()\n listeners[index] = VOID;\n ++this.pendingRemovals_[type];\n } else {\n listeners.splice(index, 1);\n if (listeners.length === 0) {\n delete this.listeners_[type];\n }\n }\n }\n }\n }\n}\n\nexport default Target;\n","/**\n * @module ol/events/EventType\n */\n\n/**\n * @enum {string}\n * @const\n */\nexport default {\n /**\n * Generic change event. Triggered when the revision counter is increased.\n * @event module:ol/events/Event~BaseEvent#change\n * @api\n */\n CHANGE: 'change',\n\n /**\n * Generic error event. Triggered when an error occurs.\n * @event module:ol/events/Event~BaseEvent#error\n * @api\n */\n ERROR: 'error',\n\n BLUR: 'blur',\n CLEAR: 'clear',\n CONTEXTMENU: 'contextmenu',\n CLICK: 'click',\n DBLCLICK: 'dblclick',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DROP: 'drop',\n FOCUS: 'focus',\n KEYDOWN: 'keydown',\n KEYPRESS: 'keypress',\n LOAD: 'load',\n RESIZE: 'resize',\n TOUCHMOVE: 'touchmove',\n WHEEL: 'wheel',\n};\n","/**\n * @module ol/events\n */\nimport {clear} from './obj.js';\n\n/**\n * Key to use with {@link module:ol/Observable.unByKey}.\n * @typedef {Object} EventsKey\n * @property {ListenerFunction} listener Listener.\n * @property {import(\"./events/Target.js\").EventTargetLike} target Target.\n * @property {string} type Type.\n * @api\n */\n\n/**\n * Listener function. This function is called with an event object as argument.\n * When the function returns `false`, event propagation will stop.\n *\n * @typedef {function((Event|import(\"./events/Event.js\").default)): (void|boolean)} ListenerFunction\n * @api\n */\n\n/**\n * @typedef {Object} ListenerObject\n * @property {ListenerFunction} handleEvent HandleEvent listener function.\n */\n\n/**\n * @typedef {ListenerFunction|ListenerObject} Listener\n */\n\n/**\n * Registers an event listener on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * This function efficiently binds a `listener` to a `this` object, and returns\n * a key for use with {@link module:ol/events.unlistenByKey}.\n *\n * @param {import(\"./events/Target.js\").EventTargetLike} target Event target.\n * @param {string} type Event type.\n * @param {ListenerFunction} listener Listener.\n * @param {Object} [thisArg] Object referenced by the `this` keyword in the\n * listener. Default is the `target`.\n * @param {boolean} [once] If true, add the listener as one-off listener.\n * @return {EventsKey} Unique key for the listener.\n */\nexport function listen(target, type, listener, thisArg, once) {\n if (thisArg && thisArg !== target) {\n listener = listener.bind(thisArg);\n }\n if (once) {\n const originalListener = listener;\n listener = function () {\n target.removeEventListener(type, listener);\n originalListener.apply(this, arguments);\n };\n }\n const eventsKey = {\n target: target,\n type: type,\n listener: listener,\n };\n target.addEventListener(type, listener);\n return eventsKey;\n}\n\n/**\n * Registers a one-off event listener on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * This function efficiently binds a `listener` as self-unregistering listener\n * to a `this` object, and returns a key for use with\n * {@link module:ol/events.unlistenByKey} in case the listener needs to be\n * unregistered before it is called.\n *\n * When {@link module:ol/events.listen} is called with the same arguments after this\n * function, the self-unregistering listener will be turned into a permanent\n * listener.\n *\n * @param {import(\"./events/Target.js\").EventTargetLike} target Event target.\n * @param {string} type Event type.\n * @param {ListenerFunction} listener Listener.\n * @param {Object} [thisArg] Object referenced by the `this` keyword in the\n * listener. Default is the `target`.\n * @return {EventsKey} Key for unlistenByKey.\n */\nexport function listenOnce(target, type, listener, thisArg) {\n return listen(target, type, listener, thisArg, true);\n}\n\n/**\n * Unregisters event listeners on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * The argument passed to this function is the key returned from\n * {@link module:ol/events.listen} or {@link module:ol/events.listenOnce}.\n *\n * @param {EventsKey} key The key.\n */\nexport function unlistenByKey(key) {\n if (key && key.target) {\n key.target.removeEventListener(key.type, key.listener);\n clear(key);\n }\n}\n","/**\n * @module ol/Observable\n */\nimport EventTarget from './events/Target.js';\nimport EventType from './events/EventType.js';\nimport {listen, listenOnce, unlistenByKey} from './events.js';\n\n/***\n * @template {string} Type\n * @template {Event|import(\"./events/Event.js\").default} EventClass\n * @template Return\n * @typedef {(type: Type, listener: (event: EventClass) => ?) => Return} OnSignature\n */\n\n/***\n * @template {string} Type\n * @template Return\n * @typedef {(type: Type[], listener: (event: Event|import(\"./events/Event\").default) => ?) => Return extends void ? void : Return[]} CombinedOnSignature\n */\n\n/**\n * @typedef {'change'|'error'} EventTypes\n */\n\n/***\n * @template Return\n * @typedef {OnSignature & CombinedOnSignature} ObservableOnSignature\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * An event target providing convenient methods for listener registration\n * and unregistration. A generic `change` event is always available through\n * {@link module:ol/Observable~Observable#changed}.\n *\n * @fires import(\"./events/Event.js\").default\n * @api\n */\nclass Observable extends EventTarget {\n constructor() {\n super();\n\n this.on =\n /** @type {ObservableOnSignature} */ (\n this.onInternal\n );\n\n this.once =\n /** @type {ObservableOnSignature} */ (\n this.onceInternal\n );\n\n this.un = /** @type {ObservableOnSignature} */ (this.unInternal);\n\n /**\n * @private\n * @type {number}\n */\n this.revision_ = 0;\n }\n\n /**\n * Increases the revision counter and dispatches a 'change' event.\n * @api\n */\n changed() {\n ++this.revision_;\n this.dispatchEvent(EventType.CHANGE);\n }\n\n /**\n * Get the version number for this object. Each time the object is modified,\n * its version number will be incremented.\n * @return {number} Revision.\n * @api\n */\n getRevision() {\n return this.revision_;\n }\n\n /**\n * @param {string|Array} type Type.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener Listener.\n * @return {import(\"./events.js\").EventsKey|Array} Event key.\n * @protected\n */\n onInternal(type, listener) {\n if (Array.isArray(type)) {\n const len = type.length;\n const keys = new Array(len);\n for (let i = 0; i < len; ++i) {\n keys[i] = listen(this, type[i], listener);\n }\n return keys;\n }\n return listen(this, /** @type {string} */ (type), listener);\n }\n\n /**\n * @param {string|Array} type Type.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener Listener.\n * @return {import(\"./events.js\").EventsKey|Array} Event key.\n * @protected\n */\n onceInternal(type, listener) {\n let key;\n if (Array.isArray(type)) {\n const len = type.length;\n key = new Array(len);\n for (let i = 0; i < len; ++i) {\n key[i] = listenOnce(this, type[i], listener);\n }\n } else {\n key = listenOnce(this, /** @type {string} */ (type), listener);\n }\n /** @type {Object} */ (listener).ol_key = key;\n return key;\n }\n\n /**\n * Unlisten for a certain type of event.\n * @param {string|Array} type Type.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener Listener.\n * @protected\n */\n unInternal(type, listener) {\n const key = /** @type {Object} */ (listener).ol_key;\n if (key) {\n unByKey(key);\n } else if (Array.isArray(type)) {\n for (let i = 0, ii = type.length; i < ii; ++i) {\n this.removeEventListener(type[i], listener);\n }\n } else {\n this.removeEventListener(type, listener);\n }\n }\n}\n\n/**\n * Listen for a certain type of event.\n * @function\n * @param {string|Array} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener The listener function.\n * @return {import(\"./events.js\").EventsKey|Array} Unique key for the listener. If\n * called with an array of event types as the first argument, the return\n * will be an array of keys.\n * @api\n */\nObservable.prototype.on;\n\n/**\n * Listen once for a certain type of event.\n * @function\n * @param {string|Array} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener The listener function.\n * @return {import(\"./events.js\").EventsKey|Array} Unique key for the listener. If\n * called with an array of event types as the first argument, the return\n * will be an array of keys.\n * @api\n */\nObservable.prototype.once;\n\n/**\n * Unlisten for a certain type of event.\n * @function\n * @param {string|Array} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener The listener function.\n * @api\n */\nObservable.prototype.un;\n\n/**\n * Removes an event listener using the key returned by `on()` or `once()`.\n * @param {import(\"./events.js\").EventsKey|Array} key The key returned by `on()`\n * or `once()` (or an array of keys).\n * @api\n */\nexport function unByKey(key) {\n if (Array.isArray(key)) {\n for (let i = 0, ii = key.length; i < ii; ++i) {\n unlistenByKey(key[i]);\n }\n } else {\n unlistenByKey(/** @type {import(\"./events.js\").EventsKey} */ (key));\n }\n}\n\nexport default Observable;\n","/**\n * @module ol/util\n */\n\n/**\n * @return {never} Any return.\n */\nexport function abstract() {\n throw new Error('Unimplemented abstract method.');\n}\n\n/**\n * Counter for getUid.\n * @type {number}\n * @private\n */\nlet uidCounter_ = 0;\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. Unique IDs are generated\n * as a strictly increasing sequence. Adapted from goog.getUid.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {string} The unique ID for the object.\n * @api\n */\nexport function getUid(obj) {\n return obj.ol_uid || (obj.ol_uid = String(++uidCounter_));\n}\n\n/**\n * OpenLayers version.\n * @type {string}\n */\nexport const VERSION = '8.1.0';\n","/**\n * @module ol/Object\n */\nimport Event from './events/Event.js';\nimport ObjectEventType from './ObjectEventType.js';\nimport Observable from './Observable.js';\nimport {getUid} from './util.js';\nimport {isEmpty} from './obj.js';\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/Object~BaseObject} instances are instances of this type.\n */\nexport class ObjectEvent extends Event {\n /**\n * @param {string} type The event type.\n * @param {string} key The property name.\n * @param {*} oldValue The old value for `key`.\n */\n constructor(type, key, oldValue) {\n super(type);\n\n /**\n * The name of the property whose value is changing.\n * @type {string}\n * @api\n */\n this.key = key;\n\n /**\n * The old value. To get the new value use `e.target.get(e.key)` where\n * `e` is the event object.\n * @type {*}\n * @api\n */\n this.oldValue = oldValue;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} ObjectOnSignature\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Most non-trivial classes inherit from this.\n *\n * This extends {@link module:ol/Observable~Observable} with observable\n * properties, where each property is observable as well as the object as a\n * whole.\n *\n * Classes that inherit from this have pre-defined properties, to which you can\n * add your owns. The pre-defined properties are listed in this documentation as\n * 'Observable Properties', and have their own accessors; for example,\n * {@link module:ol/Map~Map} has a `target` property, accessed with\n * `getTarget()` and changed with `setTarget()`. Not all properties are however\n * settable. There are also general-purpose accessors `get()` and `set()`. For\n * example, `get('target')` is equivalent to `getTarget()`.\n *\n * The `set` accessors trigger a change event, and you can monitor this by\n * registering a listener. For example, {@link module:ol/View~View} has a\n * `center` property, so `view.on('change:center', function(evt) {...});` would\n * call the function whenever the value of the center property changes. Within\n * the function, `evt.target` would be the view, so `evt.target.getCenter()`\n * would return the new center.\n *\n * You can add your own observable properties with\n * `object.set('prop', 'value')`, and retrieve that with `object.get('prop')`.\n * You can listen for changes on that property value with\n * `object.on('change:prop', listener)`. You can get a list of all\n * properties with {@link module:ol/Object~BaseObject#getProperties}.\n *\n * Note that the observable properties are separate from standard JS properties.\n * You can, for example, give your map object a title with\n * `map.title='New title'` and with `map.set('title', 'Another title')`. The\n * first will be a `hasOwnProperty`; the second will appear in\n * `getProperties()`. Only the second is observable.\n *\n * Properties can be deleted by using the unset method. E.g.\n * object.unset('foo').\n *\n * @fires ObjectEvent\n * @api\n */\nclass BaseObject extends Observable {\n /**\n * @param {Object} [values] An object with key-value pairs.\n */\n constructor(values) {\n super();\n\n /***\n * @type {ObjectOnSignature}\n */\n this.on;\n\n /***\n * @type {ObjectOnSignature}\n */\n this.once;\n\n /***\n * @type {ObjectOnSignature}\n */\n this.un;\n\n // Call {@link module:ol/util.getUid} to ensure that the order of objects' ids is\n // the same as the order in which they were created. This also helps to\n // ensure that object properties are always added in the same order, which\n // helps many JavaScript engines generate faster code.\n getUid(this);\n\n /**\n * @private\n * @type {Object}\n */\n this.values_ = null;\n\n if (values !== undefined) {\n this.setProperties(values);\n }\n }\n\n /**\n * Gets a value.\n * @param {string} key Key name.\n * @return {*} Value.\n * @api\n */\n get(key) {\n let value;\n if (this.values_ && this.values_.hasOwnProperty(key)) {\n value = this.values_[key];\n }\n return value;\n }\n\n /**\n * Get a list of object property names.\n * @return {Array} List of property names.\n * @api\n */\n getKeys() {\n return (this.values_ && Object.keys(this.values_)) || [];\n }\n\n /**\n * Get an object of all property names and values.\n * @return {Object} Object.\n * @api\n */\n getProperties() {\n return (this.values_ && Object.assign({}, this.values_)) || {};\n }\n\n /**\n * Get an object of all property names and values.\n * @return {Object?} Object.\n */\n getPropertiesInternal() {\n return this.values_;\n }\n\n /**\n * @return {boolean} The object has properties.\n */\n hasProperties() {\n return !!this.values_;\n }\n\n /**\n * @param {string} key Key name.\n * @param {*} oldValue Old value.\n */\n notify(key, oldValue) {\n let eventType;\n eventType = `change:${key}`;\n if (this.hasListener(eventType)) {\n this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));\n }\n eventType = ObjectEventType.PROPERTYCHANGE;\n if (this.hasListener(eventType)) {\n this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));\n }\n }\n\n /**\n * @param {string} key Key name.\n * @param {import(\"./events.js\").Listener} listener Listener.\n */\n addChangeListener(key, listener) {\n this.addEventListener(`change:${key}`, listener);\n }\n\n /**\n * @param {string} key Key name.\n * @param {import(\"./events.js\").Listener} listener Listener.\n */\n removeChangeListener(key, listener) {\n this.removeEventListener(`change:${key}`, listener);\n }\n\n /**\n * Sets a value.\n * @param {string} key Key name.\n * @param {*} value Value.\n * @param {boolean} [silent] Update without triggering an event.\n * @api\n */\n set(key, value, silent) {\n const values = this.values_ || (this.values_ = {});\n if (silent) {\n values[key] = value;\n } else {\n const oldValue = values[key];\n values[key] = value;\n if (oldValue !== value) {\n this.notify(key, oldValue);\n }\n }\n }\n\n /**\n * Sets a collection of key-value pairs. Note that this changes any existing\n * properties and adds new ones (it does not remove any existing properties).\n * @param {Object} values Values.\n * @param {boolean} [silent] Update without triggering an event.\n * @api\n */\n setProperties(values, silent) {\n for (const key in values) {\n this.set(key, values[key], silent);\n }\n }\n\n /**\n * Apply any properties from another object without triggering events.\n * @param {BaseObject} source The source object.\n * @protected\n */\n applyProperties(source) {\n if (!source.values_) {\n return;\n }\n Object.assign(this.values_ || (this.values_ = {}), source.values_);\n }\n\n /**\n * Unsets a property.\n * @param {string} key Key name.\n * @param {boolean} [silent] Unset without triggering an event.\n * @api\n */\n unset(key, silent) {\n if (this.values_ && key in this.values_) {\n const oldValue = this.values_[key];\n delete this.values_[key];\n if (isEmpty(this.values_)) {\n this.values_ = null;\n }\n if (!silent) {\n this.notify(key, oldValue);\n }\n }\n }\n}\n\nexport default BaseObject;\n","/**\n * @module ol/CollectionEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered when an item is added to the collection.\n * @event module:ol/Collection.CollectionEvent#add\n * @api\n */\n ADD: 'add',\n /**\n * Triggered when an item is removed from the collection.\n * @event module:ol/Collection.CollectionEvent#remove\n * @api\n */\n REMOVE: 'remove',\n};\n","/**\n * @module ol/Collection\n */\nimport BaseObject from './Object.js';\nimport CollectionEventType from './CollectionEventType.js';\nimport Event from './events/Event.js';\n\n/**\n * @enum {string}\n * @private\n */\nconst Property = {\n LENGTH: 'length',\n};\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/Collection~Collection} instances are instances of this\n * type.\n * @template T\n */\nexport class CollectionEvent extends Event {\n /**\n * @param {import(\"./CollectionEventType.js\").default} type Type.\n * @param {T} element Element.\n * @param {number} index The index of the added or removed element.\n */\n constructor(type, element, index) {\n super(type);\n\n /**\n * The element that is added to or removed from the collection.\n * @type {T}\n * @api\n */\n this.element = element;\n\n /**\n * The index of the added or removed element.\n * @type {number}\n * @api\n */\n this.index = index;\n }\n}\n\n/***\n * @template T\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature<'add'|'remove', CollectionEvent, Return> &\n * import(\"./Observable\").CombinedOnSignature} CollectionOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {boolean} [unique=false] Disallow the same item from being added to\n * the collection twice.\n */\n\n/**\n * @classdesc\n * An expanded version of standard JS Array, adding convenience methods for\n * manipulation. Add and remove changes to the Collection trigger a Collection\n * event. Note that this does not cover changes to the objects _within_ the\n * Collection; they trigger events on the appropriate object, not on the\n * Collection as a whole.\n *\n * @fires CollectionEvent\n *\n * @template T\n * @api\n */\nclass Collection extends BaseObject {\n /**\n * @param {Array} [array] Array.\n * @param {Options} [options] Collection options.\n */\n constructor(array, options) {\n super();\n\n /***\n * @type {CollectionOnSignature}\n */\n this.on;\n\n /***\n * @type {CollectionOnSignature}\n */\n this.once;\n\n /***\n * @type {CollectionOnSignature}\n */\n this.un;\n\n options = options || {};\n\n /**\n * @private\n * @type {boolean}\n */\n this.unique_ = !!options.unique;\n\n /**\n * @private\n * @type {!Array}\n */\n this.array_ = array ? array : [];\n\n if (this.unique_) {\n for (let i = 0, ii = this.array_.length; i < ii; ++i) {\n this.assertUnique_(this.array_[i], i);\n }\n }\n\n this.updateLength_();\n }\n\n /**\n * Remove all elements from the collection.\n * @api\n */\n clear() {\n while (this.getLength() > 0) {\n this.pop();\n }\n }\n\n /**\n * Add elements to the collection. This pushes each item in the provided array\n * to the end of the collection.\n * @param {!Array} arr Array.\n * @return {Collection} This collection.\n * @api\n */\n extend(arr) {\n for (let i = 0, ii = arr.length; i < ii; ++i) {\n this.push(arr[i]);\n }\n return this;\n }\n\n /**\n * Iterate over each element, calling the provided callback.\n * @param {function(T, number, Array): *} f The function to call\n * for every element. This function takes 3 arguments (the element, the\n * index and the array). The return value is ignored.\n * @api\n */\n forEach(f) {\n const array = this.array_;\n for (let i = 0, ii = array.length; i < ii; ++i) {\n f(array[i], i, array);\n }\n }\n\n /**\n * Get a reference to the underlying Array object. Warning: if the array\n * is mutated, no events will be dispatched by the collection, and the\n * collection's \"length\" property won't be in sync with the actual length\n * of the array.\n * @return {!Array} Array.\n * @api\n */\n getArray() {\n return this.array_;\n }\n\n /**\n * Get the element at the provided index.\n * @param {number} index Index.\n * @return {T} Element.\n * @api\n */\n item(index) {\n return this.array_[index];\n }\n\n /**\n * Get the length of this collection.\n * @return {number} The length of the array.\n * @observable\n * @api\n */\n getLength() {\n return this.get(Property.LENGTH);\n }\n\n /**\n * Insert an element at the provided index.\n * @param {number} index Index.\n * @param {T} elem Element.\n * @api\n */\n insertAt(index, elem) {\n if (index < 0 || index > this.getLength()) {\n throw new Error('Index out of bounds: ' + index);\n }\n if (this.unique_) {\n this.assertUnique_(elem);\n }\n this.array_.splice(index, 0, elem);\n this.updateLength_();\n this.dispatchEvent(\n new CollectionEvent(CollectionEventType.ADD, elem, index)\n );\n }\n\n /**\n * Remove the last element of the collection and return it.\n * Return `undefined` if the collection is empty.\n * @return {T|undefined} Element.\n * @api\n */\n pop() {\n return this.removeAt(this.getLength() - 1);\n }\n\n /**\n * Insert the provided element at the end of the collection.\n * @param {T} elem Element.\n * @return {number} New length of the collection.\n * @api\n */\n push(elem) {\n if (this.unique_) {\n this.assertUnique_(elem);\n }\n const n = this.getLength();\n this.insertAt(n, elem);\n return this.getLength();\n }\n\n /**\n * Remove the first occurrence of an element from the collection.\n * @param {T} elem Element.\n * @return {T|undefined} The removed element or undefined if none found.\n * @api\n */\n remove(elem) {\n const arr = this.array_;\n for (let i = 0, ii = arr.length; i < ii; ++i) {\n if (arr[i] === elem) {\n return this.removeAt(i);\n }\n }\n return undefined;\n }\n\n /**\n * Remove the element at the provided index and return it.\n * Return `undefined` if the collection does not contain this index.\n * @param {number} index Index.\n * @return {T|undefined} Value.\n * @api\n */\n removeAt(index) {\n if (index < 0 || index >= this.getLength()) {\n return undefined;\n }\n const prev = this.array_[index];\n this.array_.splice(index, 1);\n this.updateLength_();\n this.dispatchEvent(\n /** @type {CollectionEvent} */ (\n new CollectionEvent(CollectionEventType.REMOVE, prev, index)\n )\n );\n return prev;\n }\n\n /**\n * Set the element at the provided index.\n * @param {number} index Index.\n * @param {T} elem Element.\n * @api\n */\n setAt(index, elem) {\n const n = this.getLength();\n if (index >= n) {\n this.insertAt(index, elem);\n return;\n }\n if (index < 0) {\n throw new Error('Index out of bounds: ' + index);\n }\n if (this.unique_) {\n this.assertUnique_(elem, index);\n }\n const prev = this.array_[index];\n this.array_[index] = elem;\n this.dispatchEvent(\n /** @type {CollectionEvent} */ (\n new CollectionEvent(CollectionEventType.REMOVE, prev, index)\n )\n );\n this.dispatchEvent(\n /** @type {CollectionEvent} */ (\n new CollectionEvent(CollectionEventType.ADD, elem, index)\n )\n );\n }\n\n /**\n * @private\n */\n updateLength_() {\n this.set(Property.LENGTH, this.array_.length);\n }\n\n /**\n * @private\n * @param {T} elem Element.\n * @param {number} [except] Optional index to ignore.\n */\n assertUnique_(elem, except) {\n for (let i = 0, ii = this.array_.length; i < ii; ++i) {\n if (this.array_[i] === elem && i !== except) {\n throw new Error('Duplicate item added to a unique collection');\n }\n }\n }\n}\n\nexport default Collection;\n","/**\n * @module ol/has\n */\n\nconst ua =\n typeof navigator !== 'undefined' && typeof navigator.userAgent !== 'undefined'\n ? navigator.userAgent.toLowerCase()\n : '';\n\n/**\n * User agent string says we are dealing with Firefox as browser.\n * @type {boolean}\n */\nexport const FIREFOX = ua.includes('firefox');\n\n/**\n * User agent string says we are dealing with Safari as browser.\n * @type {boolean}\n */\nexport const SAFARI = ua.includes('safari') && !ua.includes('chrom');\n\n/**\n * https://bugs.webkit.org/show_bug.cgi?id=237906\n * @type {boolean}\n */\nexport const SAFARI_BUG_237906 =\n SAFARI &&\n (ua.includes('version/15.4') ||\n /cpu (os|iphone os) 15_4 like mac os x/.test(ua));\n\n/**\n * User agent string says we are dealing with a WebKit engine.\n * @type {boolean}\n */\nexport const WEBKIT = ua.includes('webkit') && !ua.includes('edge');\n\n/**\n * User agent string says we are dealing with a Mac as platform.\n * @type {boolean}\n */\nexport const MAC = ua.includes('macintosh');\n\n/**\n * The ratio between physical pixels and device-independent pixels\n * (dips) on the device (`window.devicePixelRatio`).\n * @const\n * @type {number}\n * @api\n */\nexport const DEVICE_PIXEL_RATIO =\n typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n\n/**\n * The execution context is a worker with OffscreenCanvas available.\n * @const\n * @type {boolean}\n */\nexport const WORKER_OFFSCREEN_CANVAS =\n typeof WorkerGlobalScope !== 'undefined' &&\n typeof OffscreenCanvas !== 'undefined' &&\n self instanceof WorkerGlobalScope; //eslint-disable-line\n\n/**\n * Image.prototype.decode() is supported.\n * @type {boolean}\n */\nexport const IMAGE_DECODE =\n typeof Image !== 'undefined' && Image.prototype.decode;\n\n/**\n * createImageBitmap() is supported.\n * @type {boolean}\n */\nexport const CREATE_IMAGE_BITMAP = typeof createImageBitmap === 'function';\n\n/**\n * @type {boolean}\n */\nexport const PASSIVE_EVENT_LISTENERS = (function () {\n let passive = false;\n try {\n const options = Object.defineProperty({}, 'passive', {\n get: function () {\n passive = true;\n },\n });\n\n window.addEventListener('_', null, options);\n window.removeEventListener('_', null, options);\n } catch (error) {\n // passive not supported\n }\n return passive;\n})();\n","/**\n * @module ol/asserts\n */\n\n/**\n * @param {*} assertion Assertion we expected to be truthy.\n * @param {string} errorMessage Error message.\n */\nexport function assert(assertion, errorMessage) {\n if (!assertion) {\n throw new Error(errorMessage);\n }\n}\n","/**\n * @module ol/transform\n */\nimport {WORKER_OFFSCREEN_CANVAS} from './has.js';\nimport {assert} from './asserts.js';\n\n/**\n * An array representing an affine 2d transformation for use with\n * {@link module:ol/transform} functions. The array has 6 elements.\n * @typedef {!Array} Transform\n * @api\n */\n\n/**\n * Collection of affine 2d transformation functions. The functions work on an\n * array of 6 elements. The element order is compatible with the [SVGMatrix\n * interface](https://developer.mozilla.org/en-US/docs/Web/API/SVGMatrix) and is\n * a subset (elements a to f) of a 3×3 matrix:\n * ```\n * [ a c e ]\n * [ b d f ]\n * [ 0 0 1 ]\n * ```\n */\n\n/**\n * @private\n * @type {Transform}\n */\nconst tmp_ = new Array(6);\n\n/**\n * Create an identity transform.\n * @return {!Transform} Identity transform.\n */\nexport function create() {\n return [1, 0, 0, 1, 0, 0];\n}\n\n/**\n * Resets the given transform to an identity transform.\n * @param {!Transform} transform Transform.\n * @return {!Transform} Transform.\n */\nexport function reset(transform) {\n return set(transform, 1, 0, 0, 1, 0, 0);\n}\n\n/**\n * Multiply the underlying matrices of two transforms and return the result in\n * the first transform.\n * @param {!Transform} transform1 Transform parameters of matrix 1.\n * @param {!Transform} transform2 Transform parameters of matrix 2.\n * @return {!Transform} transform1 multiplied with transform2.\n */\nexport function multiply(transform1, transform2) {\n const a1 = transform1[0];\n const b1 = transform1[1];\n const c1 = transform1[2];\n const d1 = transform1[3];\n const e1 = transform1[4];\n const f1 = transform1[5];\n const a2 = transform2[0];\n const b2 = transform2[1];\n const c2 = transform2[2];\n const d2 = transform2[3];\n const e2 = transform2[4];\n const f2 = transform2[5];\n\n transform1[0] = a1 * a2 + c1 * b2;\n transform1[1] = b1 * a2 + d1 * b2;\n transform1[2] = a1 * c2 + c1 * d2;\n transform1[3] = b1 * c2 + d1 * d2;\n transform1[4] = a1 * e2 + c1 * f2 + e1;\n transform1[5] = b1 * e2 + d1 * f2 + f1;\n\n return transform1;\n}\n\n/**\n * Set the transform components a-f on a given transform.\n * @param {!Transform} transform Transform.\n * @param {number} a The a component of the transform.\n * @param {number} b The b component of the transform.\n * @param {number} c The c component of the transform.\n * @param {number} d The d component of the transform.\n * @param {number} e The e component of the transform.\n * @param {number} f The f component of the transform.\n * @return {!Transform} Matrix with transform applied.\n */\nexport function set(transform, a, b, c, d, e, f) {\n transform[0] = a;\n transform[1] = b;\n transform[2] = c;\n transform[3] = d;\n transform[4] = e;\n transform[5] = f;\n return transform;\n}\n\n/**\n * Set transform on one matrix from another matrix.\n * @param {!Transform} transform1 Matrix to set transform to.\n * @param {!Transform} transform2 Matrix to set transform from.\n * @return {!Transform} transform1 with transform from transform2 applied.\n */\nexport function setFromArray(transform1, transform2) {\n transform1[0] = transform2[0];\n transform1[1] = transform2[1];\n transform1[2] = transform2[2];\n transform1[3] = transform2[3];\n transform1[4] = transform2[4];\n transform1[5] = transform2[5];\n return transform1;\n}\n\n/**\n * Transforms the given coordinate with the given transform returning the\n * resulting, transformed coordinate. The coordinate will be modified in-place.\n *\n * @param {Transform} transform The transformation.\n * @param {import(\"./coordinate.js\").Coordinate|import(\"./pixel.js\").Pixel} coordinate The coordinate to transform.\n * @return {import(\"./coordinate.js\").Coordinate|import(\"./pixel.js\").Pixel} return coordinate so that operations can be\n * chained together.\n */\nexport function apply(transform, coordinate) {\n const x = coordinate[0];\n const y = coordinate[1];\n coordinate[0] = transform[0] * x + transform[2] * y + transform[4];\n coordinate[1] = transform[1] * x + transform[3] * y + transform[5];\n return coordinate;\n}\n\n/**\n * Applies rotation to the given transform.\n * @param {!Transform} transform Transform.\n * @param {number} angle Angle in radians.\n * @return {!Transform} The rotated transform.\n */\nexport function rotate(transform, angle) {\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n return multiply(transform, set(tmp_, cos, sin, -sin, cos, 0, 0));\n}\n\n/**\n * Applies scale to a given transform.\n * @param {!Transform} transform Transform.\n * @param {number} x Scale factor x.\n * @param {number} y Scale factor y.\n * @return {!Transform} The scaled transform.\n */\nexport function scale(transform, x, y) {\n return multiply(transform, set(tmp_, x, 0, 0, y, 0, 0));\n}\n\n/**\n * Creates a scale transform.\n * @param {!Transform} target Transform to overwrite.\n * @param {number} x Scale factor x.\n * @param {number} y Scale factor y.\n * @return {!Transform} The scale transform.\n */\nexport function makeScale(target, x, y) {\n return set(target, x, 0, 0, y, 0, 0);\n}\n\n/**\n * Applies translation to the given transform.\n * @param {!Transform} transform Transform.\n * @param {number} dx Translation x.\n * @param {number} dy Translation y.\n * @return {!Transform} The translated transform.\n */\nexport function translate(transform, dx, dy) {\n return multiply(transform, set(tmp_, 1, 0, 0, 1, dx, dy));\n}\n\n/**\n * Creates a composite transform given an initial translation, scale, rotation, and\n * final translation (in that order only, not commutative).\n * @param {!Transform} transform The transform (will be modified in place).\n * @param {number} dx1 Initial translation x.\n * @param {number} dy1 Initial translation y.\n * @param {number} sx Scale factor x.\n * @param {number} sy Scale factor y.\n * @param {number} angle Rotation (in counter-clockwise radians).\n * @param {number} dx2 Final translation x.\n * @param {number} dy2 Final translation y.\n * @return {!Transform} The composite transform.\n */\nexport function compose(transform, dx1, dy1, sx, sy, angle, dx2, dy2) {\n const sin = Math.sin(angle);\n const cos = Math.cos(angle);\n transform[0] = sx * cos;\n transform[1] = sy * sin;\n transform[2] = -sx * sin;\n transform[3] = sy * cos;\n transform[4] = dx2 * sx * cos - dy2 * sx * sin + dx1;\n transform[5] = dx2 * sy * sin + dy2 * sy * cos + dy1;\n return transform;\n}\n\n/**\n * Creates a composite transform given an initial translation, scale, rotation, and\n * final translation (in that order only, not commutative). The resulting transform\n * string can be applied as `transform` property of an HTMLElement's style.\n * @param {number} dx1 Initial translation x.\n * @param {number} dy1 Initial translation y.\n * @param {number} sx Scale factor x.\n * @param {number} sy Scale factor y.\n * @param {number} angle Rotation (in counter-clockwise radians).\n * @param {number} dx2 Final translation x.\n * @param {number} dy2 Final translation y.\n * @return {string} The composite css transform.\n * @api\n */\nexport function composeCssTransform(dx1, dy1, sx, sy, angle, dx2, dy2) {\n return toString(compose(create(), dx1, dy1, sx, sy, angle, dx2, dy2));\n}\n\n/**\n * Invert the given transform.\n * @param {!Transform} source The source transform to invert.\n * @return {!Transform} The inverted (source) transform.\n */\nexport function invert(source) {\n return makeInverse(source, source);\n}\n\n/**\n * Invert the given transform.\n * @param {!Transform} target Transform to be set as the inverse of\n * the source transform.\n * @param {!Transform} source The source transform to invert.\n * @return {!Transform} The inverted (target) transform.\n */\nexport function makeInverse(target, source) {\n const det = determinant(source);\n assert(det !== 0, 'Transformation matrix cannot be inverted');\n\n const a = source[0];\n const b = source[1];\n const c = source[2];\n const d = source[3];\n const e = source[4];\n const f = source[5];\n\n target[0] = d / det;\n target[1] = -b / det;\n target[2] = -c / det;\n target[3] = a / det;\n target[4] = (c * f - d * e) / det;\n target[5] = -(a * f - b * e) / det;\n\n return target;\n}\n\n/**\n * Returns the determinant of the given matrix.\n * @param {!Transform} mat Matrix.\n * @return {number} Determinant.\n */\nexport function determinant(mat) {\n return mat[0] * mat[3] - mat[1] * mat[2];\n}\n\n/**\n * @type {HTMLElement}\n * @private\n */\nlet transformStringDiv;\n\n/**\n * A rounded string version of the transform. This can be used\n * for CSS transforms.\n * @param {!Transform} mat Matrix.\n * @return {string} The transform as a string.\n */\nexport function toString(mat) {\n const transformString = 'matrix(' + mat.join(', ') + ')';\n if (WORKER_OFFSCREEN_CANVAS) {\n return transformString;\n }\n const node =\n transformStringDiv || (transformStringDiv = document.createElement('div'));\n node.style.transform = transformString;\n return node.style.transform;\n}\n","/**\n * @module ol/extent/Relationship\n */\n\n/**\n * Relationship to an extent.\n * @enum {number}\n */\nexport default {\n UNKNOWN: 0,\n INTERSECTING: 1,\n ABOVE: 2,\n RIGHT: 4,\n BELOW: 8,\n LEFT: 16,\n};\n","/**\n * @module ol/extent\n */\nimport Relationship from './extent/Relationship.js';\n\n/**\n * An array of numbers representing an extent: `[minx, miny, maxx, maxy]`.\n * @typedef {Array} Extent\n * @api\n */\n\n/**\n * Extent corner.\n * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} Corner\n */\n\n/**\n * Build an extent that includes all given coordinates.\n *\n * @param {Array} coordinates Coordinates.\n * @return {Extent} Bounding extent.\n * @api\n */\nexport function boundingExtent(coordinates) {\n const extent = createEmpty();\n for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n extendCoordinate(extent, coordinates[i]);\n }\n return extent;\n}\n\n/**\n * @param {Array} xs Xs.\n * @param {Array} ys Ys.\n * @param {Extent} [dest] Destination extent.\n * @private\n * @return {Extent} Extent.\n */\nfunction _boundingExtentXYs(xs, ys, dest) {\n const minX = Math.min.apply(null, xs);\n const minY = Math.min.apply(null, ys);\n const maxX = Math.max.apply(null, xs);\n const maxY = Math.max.apply(null, ys);\n return createOrUpdate(minX, minY, maxX, maxY, dest);\n}\n\n/**\n * Return extent increased by the provided value.\n * @param {Extent} extent Extent.\n * @param {number} value The amount by which the extent should be buffered.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n * @api\n */\nexport function buffer(extent, value, dest) {\n if (dest) {\n dest[0] = extent[0] - value;\n dest[1] = extent[1] - value;\n dest[2] = extent[2] + value;\n dest[3] = extent[3] + value;\n return dest;\n }\n return [\n extent[0] - value,\n extent[1] - value,\n extent[2] + value,\n extent[3] + value,\n ];\n}\n\n/**\n * Creates a clone of an extent.\n *\n * @param {Extent} extent Extent to clone.\n * @param {Extent} [dest] Extent.\n * @return {Extent} The clone.\n */\nexport function clone(extent, dest) {\n if (dest) {\n dest[0] = extent[0];\n dest[1] = extent[1];\n dest[2] = extent[2];\n dest[3] = extent[3];\n return dest;\n }\n return extent.slice();\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {number} Closest squared distance.\n */\nexport function closestSquaredDistanceXY(extent, x, y) {\n let dx, dy;\n if (x < extent[0]) {\n dx = extent[0] - x;\n } else if (extent[2] < x) {\n dx = x - extent[2];\n } else {\n dx = 0;\n }\n if (y < extent[1]) {\n dy = extent[1] - y;\n } else if (extent[3] < y) {\n dy = y - extent[3];\n } else {\n dy = 0;\n }\n return dx * dx + dy * dy;\n}\n\n/**\n * Check if the passed coordinate is contained or on the edge of the extent.\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {boolean} The coordinate is contained in the extent.\n * @api\n */\nexport function containsCoordinate(extent, coordinate) {\n return containsXY(extent, coordinate[0], coordinate[1]);\n}\n\n/**\n * Check if one extent contains another.\n *\n * An extent is deemed contained if it lies completely within the other extent,\n * including if they share one or more edges.\n *\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {boolean} The second extent is contained by or on the edge of the\n * first.\n * @api\n */\nexport function containsExtent(extent1, extent2) {\n return (\n extent1[0] <= extent2[0] &&\n extent2[2] <= extent1[2] &&\n extent1[1] <= extent2[1] &&\n extent2[3] <= extent1[3]\n );\n}\n\n/**\n * Check if the passed coordinate is contained or on the edge of the extent.\n *\n * @param {Extent} extent Extent.\n * @param {number} x X coordinate.\n * @param {number} y Y coordinate.\n * @return {boolean} The x, y values are contained in the extent.\n * @api\n */\nexport function containsXY(extent, x, y) {\n return extent[0] <= x && x <= extent[2] && extent[1] <= y && y <= extent[3];\n}\n\n/**\n * Get the relationship between a coordinate and extent.\n * @param {Extent} extent The extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate The coordinate.\n * @return {import(\"./extent/Relationship.js\").default} The relationship (bitwise compare with\n * import(\"./extent/Relationship.js\").Relationship).\n */\nexport function coordinateRelationship(extent, coordinate) {\n const minX = extent[0];\n const minY = extent[1];\n const maxX = extent[2];\n const maxY = extent[3];\n const x = coordinate[0];\n const y = coordinate[1];\n let relationship = Relationship.UNKNOWN;\n if (x < minX) {\n relationship = relationship | Relationship.LEFT;\n } else if (x > maxX) {\n relationship = relationship | Relationship.RIGHT;\n }\n if (y < minY) {\n relationship = relationship | Relationship.BELOW;\n } else if (y > maxY) {\n relationship = relationship | Relationship.ABOVE;\n }\n if (relationship === Relationship.UNKNOWN) {\n relationship = Relationship.INTERSECTING;\n }\n return relationship;\n}\n\n/**\n * Create an empty extent.\n * @return {Extent} Empty extent.\n * @api\n */\nexport function createEmpty() {\n return [Infinity, Infinity, -Infinity, -Infinity];\n}\n\n/**\n * Create a new extent or update the provided extent.\n * @param {number} minX Minimum X.\n * @param {number} minY Minimum Y.\n * @param {number} maxX Maximum X.\n * @param {number} maxY Maximum Y.\n * @param {Extent} [dest] Destination extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdate(minX, minY, maxX, maxY, dest) {\n if (dest) {\n dest[0] = minX;\n dest[1] = minY;\n dest[2] = maxX;\n dest[3] = maxY;\n return dest;\n }\n return [minX, minY, maxX, maxY];\n}\n\n/**\n * Create a new empty extent or make the provided one empty.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateEmpty(dest) {\n return createOrUpdate(Infinity, Infinity, -Infinity, -Infinity, dest);\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromCoordinate(coordinate, dest) {\n const x = coordinate[0];\n const y = coordinate[1];\n return createOrUpdate(x, y, x, y, dest);\n}\n\n/**\n * @param {Array} coordinates Coordinates.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromCoordinates(coordinates, dest) {\n const extent = createOrUpdateEmpty(dest);\n return extendCoordinates(extent, coordinates);\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromFlatCoordinates(\n flatCoordinates,\n offset,\n end,\n stride,\n dest\n) {\n const extent = createOrUpdateEmpty(dest);\n return extendFlatCoordinates(extent, flatCoordinates, offset, end, stride);\n}\n\n/**\n * @param {Array>} rings Rings.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromRings(rings, dest) {\n const extent = createOrUpdateEmpty(dest);\n return extendRings(extent, rings);\n}\n\n/**\n * Determine if two extents are equivalent.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {boolean} The two extents are equivalent.\n * @api\n */\nexport function equals(extent1, extent2) {\n return (\n extent1[0] == extent2[0] &&\n extent1[2] == extent2[2] &&\n extent1[1] == extent2[1] &&\n extent1[3] == extent2[3]\n );\n}\n\n/**\n * Determine if two extents are approximately equivalent.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @param {number} tolerance Tolerance in extent coordinate units.\n * @return {boolean} The two extents differ by less than the tolerance.\n */\nexport function approximatelyEquals(extent1, extent2, tolerance) {\n return (\n Math.abs(extent1[0] - extent2[0]) < tolerance &&\n Math.abs(extent1[2] - extent2[2]) < tolerance &&\n Math.abs(extent1[1] - extent2[1]) < tolerance &&\n Math.abs(extent1[3] - extent2[3]) < tolerance\n );\n}\n\n/**\n * Modify an extent to include another extent.\n * @param {Extent} extent1 The extent to be modified.\n * @param {Extent} extent2 The extent that will be included in the first.\n * @return {Extent} A reference to the first (extended) extent.\n * @api\n */\nexport function extend(extent1, extent2) {\n if (extent2[0] < extent1[0]) {\n extent1[0] = extent2[0];\n }\n if (extent2[2] > extent1[2]) {\n extent1[2] = extent2[2];\n }\n if (extent2[1] < extent1[1]) {\n extent1[1] = extent2[1];\n }\n if (extent2[3] > extent1[3]) {\n extent1[3] = extent2[3];\n }\n return extent1;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n */\nexport function extendCoordinate(extent, coordinate) {\n if (coordinate[0] < extent[0]) {\n extent[0] = coordinate[0];\n }\n if (coordinate[0] > extent[2]) {\n extent[2] = coordinate[0];\n }\n if (coordinate[1] < extent[1]) {\n extent[1] = coordinate[1];\n }\n if (coordinate[1] > extent[3]) {\n extent[3] = coordinate[1];\n }\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array} coordinates Coordinates.\n * @return {Extent} Extent.\n */\nexport function extendCoordinates(extent, coordinates) {\n for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n extendCoordinate(extent, coordinates[i]);\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {Extent} Extent.\n */\nexport function extendFlatCoordinates(\n extent,\n flatCoordinates,\n offset,\n end,\n stride\n) {\n for (; offset < end; offset += stride) {\n extendXY(extent, flatCoordinates[offset], flatCoordinates[offset + 1]);\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array>} rings Rings.\n * @return {Extent} Extent.\n */\nexport function extendRings(extent, rings) {\n for (let i = 0, ii = rings.length; i < ii; ++i) {\n extendCoordinates(extent, rings[i]);\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} x X.\n * @param {number} y Y.\n */\nexport function extendXY(extent, x, y) {\n extent[0] = Math.min(extent[0], x);\n extent[1] = Math.min(extent[1], y);\n extent[2] = Math.max(extent[2], x);\n extent[3] = Math.max(extent[3], y);\n}\n\n/**\n * This function calls `callback` for each corner of the extent. If the\n * callback returns a truthy value the function returns that value\n * immediately. Otherwise the function returns `false`.\n * @param {Extent} extent Extent.\n * @param {function(import(\"./coordinate.js\").Coordinate): S} callback Callback.\n * @return {S|boolean} Value.\n * @template S\n */\nexport function forEachCorner(extent, callback) {\n let val;\n val = callback(getBottomLeft(extent));\n if (val) {\n return val;\n }\n val = callback(getBottomRight(extent));\n if (val) {\n return val;\n }\n val = callback(getTopRight(extent));\n if (val) {\n return val;\n }\n val = callback(getTopLeft(extent));\n if (val) {\n return val;\n }\n return false;\n}\n\n/**\n * Get the size of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Area.\n * @api\n */\nexport function getArea(extent) {\n let area = 0;\n if (!isEmpty(extent)) {\n area = getWidth(extent) * getHeight(extent);\n }\n return area;\n}\n\n/**\n * Get the bottom left coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Bottom left coordinate.\n * @api\n */\nexport function getBottomLeft(extent) {\n return [extent[0], extent[1]];\n}\n\n/**\n * Get the bottom right coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Bottom right coordinate.\n * @api\n */\nexport function getBottomRight(extent) {\n return [extent[2], extent[1]];\n}\n\n/**\n * Get the center coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Center.\n * @api\n */\nexport function getCenter(extent) {\n return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];\n}\n\n/**\n * Get a corner coordinate of an extent.\n * @param {Extent} extent Extent.\n * @param {Corner} corner Corner.\n * @return {import(\"./coordinate.js\").Coordinate} Corner coordinate.\n */\nexport function getCorner(extent, corner) {\n let coordinate;\n if (corner === 'bottom-left') {\n coordinate = getBottomLeft(extent);\n } else if (corner === 'bottom-right') {\n coordinate = getBottomRight(extent);\n } else if (corner === 'top-left') {\n coordinate = getTopLeft(extent);\n } else if (corner === 'top-right') {\n coordinate = getTopRight(extent);\n } else {\n throw new Error('Invalid corner');\n }\n return coordinate;\n}\n\n/**\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {number} Enlarged area.\n */\nexport function getEnlargedArea(extent1, extent2) {\n const minX = Math.min(extent1[0], extent2[0]);\n const minY = Math.min(extent1[1], extent2[1]);\n const maxX = Math.max(extent1[2], extent2[2]);\n const maxY = Math.max(extent1[3], extent2[3]);\n return (maxX - minX) * (maxY - minY);\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @param {Extent} [dest] Destination extent.\n * @return {Extent} Extent.\n */\nexport function getForViewAndSize(center, resolution, rotation, size, dest) {\n const [x0, y0, x1, y1, x2, y2, x3, y3] = getRotatedViewport(\n center,\n resolution,\n rotation,\n size\n );\n return createOrUpdate(\n Math.min(x0, x1, x2, x3),\n Math.min(y0, y1, y2, y3),\n Math.max(x0, x1, x2, x3),\n Math.max(y0, y1, y2, y3),\n dest\n );\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @return {Array} Linear ring representing the viewport.\n */\nexport function getRotatedViewport(center, resolution, rotation, size) {\n const dx = (resolution * size[0]) / 2;\n const dy = (resolution * size[1]) / 2;\n const cosRotation = Math.cos(rotation);\n const sinRotation = Math.sin(rotation);\n const xCos = dx * cosRotation;\n const xSin = dx * sinRotation;\n const yCos = dy * cosRotation;\n const ySin = dy * sinRotation;\n const x = center[0];\n const y = center[1];\n return [\n x - xCos + ySin,\n y - xSin - yCos,\n x - xCos - ySin,\n y - xSin + yCos,\n x + xCos - ySin,\n y + xSin + yCos,\n x + xCos + ySin,\n y + xSin - yCos,\n x - xCos + ySin,\n y - xSin - yCos,\n ];\n}\n\n/**\n * Get the height of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Height.\n * @api\n */\nexport function getHeight(extent) {\n return extent[3] - extent[1];\n}\n\n/**\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {number} Intersection area.\n */\nexport function getIntersectionArea(extent1, extent2) {\n const intersection = getIntersection(extent1, extent2);\n return getArea(intersection);\n}\n\n/**\n * Get the intersection of two extents.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @param {Extent} [dest] Optional extent to populate with intersection.\n * @return {Extent} Intersecting extent.\n * @api\n */\nexport function getIntersection(extent1, extent2, dest) {\n const intersection = dest ? dest : createEmpty();\n if (intersects(extent1, extent2)) {\n if (extent1[0] > extent2[0]) {\n intersection[0] = extent1[0];\n } else {\n intersection[0] = extent2[0];\n }\n if (extent1[1] > extent2[1]) {\n intersection[1] = extent1[1];\n } else {\n intersection[1] = extent2[1];\n }\n if (extent1[2] < extent2[2]) {\n intersection[2] = extent1[2];\n } else {\n intersection[2] = extent2[2];\n }\n if (extent1[3] < extent2[3]) {\n intersection[3] = extent1[3];\n } else {\n intersection[3] = extent2[3];\n }\n } else {\n createOrUpdateEmpty(intersection);\n }\n return intersection;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @return {number} Margin.\n */\nexport function getMargin(extent) {\n return getWidth(extent) + getHeight(extent);\n}\n\n/**\n * Get the size (width, height) of an extent.\n * @param {Extent} extent The extent.\n * @return {import(\"./size.js\").Size} The extent size.\n * @api\n */\nexport function getSize(extent) {\n return [extent[2] - extent[0], extent[3] - extent[1]];\n}\n\n/**\n * Get the top left coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Top left coordinate.\n * @api\n */\nexport function getTopLeft(extent) {\n return [extent[0], extent[3]];\n}\n\n/**\n * Get the top right coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Top right coordinate.\n * @api\n */\nexport function getTopRight(extent) {\n return [extent[2], extent[3]];\n}\n\n/**\n * Get the width of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Width.\n * @api\n */\nexport function getWidth(extent) {\n return extent[2] - extent[0];\n}\n\n/**\n * Determine if one extent intersects another.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent.\n * @return {boolean} The two extents intersect.\n * @api\n */\nexport function intersects(extent1, extent2) {\n return (\n extent1[0] <= extent2[2] &&\n extent1[2] >= extent2[0] &&\n extent1[1] <= extent2[3] &&\n extent1[3] >= extent2[1]\n );\n}\n\n/**\n * Determine if an extent is empty.\n * @param {Extent} extent Extent.\n * @return {boolean} Is empty.\n * @api\n */\nexport function isEmpty(extent) {\n return extent[2] < extent[0] || extent[3] < extent[1];\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function returnOrUpdate(extent, dest) {\n if (dest) {\n dest[0] = extent[0];\n dest[1] = extent[1];\n dest[2] = extent[2];\n dest[3] = extent[3];\n return dest;\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} value Value.\n */\nexport function scaleFromCenter(extent, value) {\n const deltaX = ((extent[2] - extent[0]) / 2) * (value - 1);\n const deltaY = ((extent[3] - extent[1]) / 2) * (value - 1);\n extent[0] -= deltaX;\n extent[2] += deltaX;\n extent[1] -= deltaY;\n extent[3] += deltaY;\n}\n\n/**\n * Determine if the segment between two coordinates intersects (crosses,\n * touches, or is contained by) the provided extent.\n * @param {Extent} extent The extent.\n * @param {import(\"./coordinate.js\").Coordinate} start Segment start coordinate.\n * @param {import(\"./coordinate.js\").Coordinate} end Segment end coordinate.\n * @return {boolean} The segment intersects the extent.\n */\nexport function intersectsSegment(extent, start, end) {\n let intersects = false;\n const startRel = coordinateRelationship(extent, start);\n const endRel = coordinateRelationship(extent, end);\n if (\n startRel === Relationship.INTERSECTING ||\n endRel === Relationship.INTERSECTING\n ) {\n intersects = true;\n } else {\n const minX = extent[0];\n const minY = extent[1];\n const maxX = extent[2];\n const maxY = extent[3];\n const startX = start[0];\n const startY = start[1];\n const endX = end[0];\n const endY = end[1];\n const slope = (endY - startY) / (endX - startX);\n let x, y;\n if (!!(endRel & Relationship.ABOVE) && !(startRel & Relationship.ABOVE)) {\n // potentially intersects top\n x = endX - (endY - maxY) / slope;\n intersects = x >= minX && x <= maxX;\n }\n if (\n !intersects &&\n !!(endRel & Relationship.RIGHT) &&\n !(startRel & Relationship.RIGHT)\n ) {\n // potentially intersects right\n y = endY - (endX - maxX) * slope;\n intersects = y >= minY && y <= maxY;\n }\n if (\n !intersects &&\n !!(endRel & Relationship.BELOW) &&\n !(startRel & Relationship.BELOW)\n ) {\n // potentially intersects bottom\n x = endX - (endY - minY) / slope;\n intersects = x >= minX && x <= maxX;\n }\n if (\n !intersects &&\n !!(endRel & Relationship.LEFT) &&\n !(startRel & Relationship.LEFT)\n ) {\n // potentially intersects left\n y = endY - (endX - minX) * slope;\n intersects = y >= minY && y <= maxY;\n }\n }\n return intersects;\n}\n\n/**\n * Apply a transform function to the extent.\n * @param {Extent} extent Extent.\n * @param {import(\"./proj.js\").TransformFunction} transformFn Transform function.\n * Called with `[minX, minY, maxX, maxY]` extent coordinates.\n * @param {Extent} [dest] Destination extent.\n * @param {number} [stops] Number of stops per side used for the transform.\n * By default only the corners are used.\n * @return {Extent} Extent.\n * @api\n */\nexport function applyTransform(extent, transformFn, dest, stops) {\n if (isEmpty(extent)) {\n return createOrUpdateEmpty(dest);\n }\n let coordinates = [];\n if (stops > 1) {\n const width = extent[2] - extent[0];\n const height = extent[3] - extent[1];\n for (let i = 0; i < stops; ++i) {\n coordinates.push(\n extent[0] + (width * i) / stops,\n extent[1],\n extent[2],\n extent[1] + (height * i) / stops,\n extent[2] - (width * i) / stops,\n extent[3],\n extent[0],\n extent[3] - (height * i) / stops\n );\n }\n } else {\n coordinates = [\n extent[0],\n extent[1],\n extent[2],\n extent[1],\n extent[2],\n extent[3],\n extent[0],\n extent[3],\n ];\n }\n transformFn(coordinates, coordinates, 2);\n const xs = [];\n const ys = [];\n for (let i = 0, l = coordinates.length; i < l; i += 2) {\n xs.push(coordinates[i]);\n ys.push(coordinates[i + 1]);\n }\n return _boundingExtentXYs(xs, ys, dest);\n}\n\n/**\n * Modifies the provided extent in-place to be within the real world\n * extent.\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./proj/Projection.js\").default} projection Projection\n * @return {Extent} The extent within the real world extent.\n */\nexport function wrapX(extent, projection) {\n const projectionExtent = projection.getExtent();\n const center = getCenter(extent);\n if (\n projection.canWrapX() &&\n (center[0] < projectionExtent[0] || center[0] >= projectionExtent[2])\n ) {\n const worldWidth = getWidth(projectionExtent);\n const worldsAway = Math.floor(\n (center[0] - projectionExtent[0]) / worldWidth\n );\n const offset = worldsAway * worldWidth;\n extent[0] -= offset;\n extent[2] -= offset;\n }\n return extent;\n}\n\n/**\n * Fits the extent to the real world\n *\n * If the extent does not cross the anti meridian, this will return the extent in an array\n * If the extent crosses the anti meridian, the extent will be sliced, so each part fits within the\n * real world\n *\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./proj/Projection.js\").default} projection Projection\n * @return {Array} The extent within the real world extent.\n */\nexport function wrapAndSliceX(extent, projection) {\n if (projection.canWrapX()) {\n const projectionExtent = projection.getExtent();\n\n if (!isFinite(extent[0]) || !isFinite(extent[2])) {\n return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];\n }\n\n wrapX(extent, projection);\n const worldWidth = getWidth(projectionExtent);\n\n if (getWidth(extent) > worldWidth) {\n // the extent wraps around on itself\n return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];\n }\n if (extent[0] < projectionExtent[0]) {\n // the extent crosses the anti meridian, so it needs to be sliced\n return [\n [extent[0] + worldWidth, extent[1], projectionExtent[2], extent[3]],\n [projectionExtent[0], extent[1], extent[2], extent[3]],\n ];\n }\n if (extent[2] > projectionExtent[2]) {\n // the extent crosses the anti meridian, so it needs to be sliced\n return [\n [extent[0], extent[1], projectionExtent[2], extent[3]],\n [projectionExtent[0], extent[1], extent[2] - worldWidth, extent[3]],\n ];\n }\n }\n\n return [extent];\n}\n","/**\n * @module ol/math\n */\n\n/**\n * Takes a number and clamps it to within the provided bounds.\n * @param {number} value The input number.\n * @param {number} min The minimum value to return.\n * @param {number} max The maximum value to return.\n * @return {number} The input number if it is within bounds, or the nearest\n * number within the bounds.\n */\nexport function clamp(value, min, max) {\n return Math.min(Math.max(value, min), max);\n}\n\n/**\n * Returns the square of the closest distance between the point (x, y) and the\n * line segment (x1, y1) to (x2, y2).\n * @param {number} x X.\n * @param {number} y Y.\n * @param {number} x1 X1.\n * @param {number} y1 Y1.\n * @param {number} x2 X2.\n * @param {number} y2 Y2.\n * @return {number} Squared distance.\n */\nexport function squaredSegmentDistance(x, y, x1, y1, x2, y2) {\n const dx = x2 - x1;\n const dy = y2 - y1;\n if (dx !== 0 || dy !== 0) {\n const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);\n if (t > 1) {\n x1 = x2;\n y1 = y2;\n } else if (t > 0) {\n x1 += dx * t;\n y1 += dy * t;\n }\n }\n return squaredDistance(x, y, x1, y1);\n}\n\n/**\n * Returns the square of the distance between the points (x1, y1) and (x2, y2).\n * @param {number} x1 X1.\n * @param {number} y1 Y1.\n * @param {number} x2 X2.\n * @param {number} y2 Y2.\n * @return {number} Squared distance.\n */\nexport function squaredDistance(x1, y1, x2, y2) {\n const dx = x2 - x1;\n const dy = y2 - y1;\n return dx * dx + dy * dy;\n}\n\n/**\n * Solves system of linear equations using Gaussian elimination method.\n *\n * @param {Array>} mat Augmented matrix (n x n + 1 column)\n * in row-major order.\n * @return {Array} The resulting vector.\n */\nexport function solveLinearSystem(mat) {\n const n = mat.length;\n\n for (let i = 0; i < n; i++) {\n // Find max in the i-th column (ignoring i - 1 first rows)\n let maxRow = i;\n let maxEl = Math.abs(mat[i][i]);\n for (let r = i + 1; r < n; r++) {\n const absValue = Math.abs(mat[r][i]);\n if (absValue > maxEl) {\n maxEl = absValue;\n maxRow = r;\n }\n }\n\n if (maxEl === 0) {\n return null; // matrix is singular\n }\n\n // Swap max row with i-th (current) row\n const tmp = mat[maxRow];\n mat[maxRow] = mat[i];\n mat[i] = tmp;\n\n // Subtract the i-th row to make all the remaining rows 0 in the i-th column\n for (let j = i + 1; j < n; j++) {\n const coef = -mat[j][i] / mat[i][i];\n for (let k = i; k < n + 1; k++) {\n if (i == k) {\n mat[j][k] = 0;\n } else {\n mat[j][k] += coef * mat[i][k];\n }\n }\n }\n }\n\n // Solve Ax=b for upper triangular matrix A (mat)\n const x = new Array(n);\n for (let l = n - 1; l >= 0; l--) {\n x[l] = mat[l][n] / mat[l][l];\n for (let m = l - 1; m >= 0; m--) {\n mat[m][n] -= mat[m][l] * x[l];\n }\n }\n return x;\n}\n\n/**\n * Converts radians to to degrees.\n *\n * @param {number} angleInRadians Angle in radians.\n * @return {number} Angle in degrees.\n */\nexport function toDegrees(angleInRadians) {\n return (angleInRadians * 180) / Math.PI;\n}\n\n/**\n * Converts degrees to radians.\n *\n * @param {number} angleInDegrees Angle in degrees.\n * @return {number} Angle in radians.\n */\nexport function toRadians(angleInDegrees) {\n return (angleInDegrees * Math.PI) / 180;\n}\n\n/**\n * Returns the modulo of a / b, depending on the sign of b.\n *\n * @param {number} a Dividend.\n * @param {number} b Divisor.\n * @return {number} Modulo.\n */\nexport function modulo(a, b) {\n const r = a % b;\n return r * b < 0 ? r + b : r;\n}\n\n/**\n * Calculates the linearly interpolated value of x between a and b.\n *\n * @param {number} a Number\n * @param {number} b Number\n * @param {number} x Value to be interpolated.\n * @return {number} Interpolated value.\n */\nexport function lerp(a, b, x) {\n return a + x * (b - a);\n}\n\n/**\n * Returns a number with a limited number of decimal digits.\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The input number with a limited number of decimal digits.\n */\nexport function toFixed(n, decimals) {\n const factor = Math.pow(10, decimals);\n return Math.round(n * factor) / factor;\n}\n\n/**\n * Rounds a number to the nearest integer value considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The nearest integer.\n */\nexport function round(n, decimals) {\n return Math.round(toFixed(n, decimals));\n}\n\n/**\n * Rounds a number to the next smaller integer considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The next smaller integer.\n */\nexport function floor(n, decimals) {\n return Math.floor(toFixed(n, decimals));\n}\n\n/**\n * Rounds a number to the next bigger integer considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The next bigger integer.\n */\nexport function ceil(n, decimals) {\n return Math.ceil(toFixed(n, decimals));\n}\n","/**\n * @module ol/color\n */\nimport {clamp} from './math.js';\n\n/**\n * A color represented as a short array [red, green, blue, alpha].\n * red, green, and blue should be integers in the range 0..255 inclusive.\n * alpha should be a float in the range 0..1 inclusive. If no alpha value is\n * given then `1` will be used.\n * @typedef {Array} Color\n * @api\n */\n\n/**\n * This RegExp matches # followed by 3, 4, 6, or 8 hex digits.\n * @const\n * @type {RegExp}\n * @private\n */\nconst HEX_COLOR_RE_ = /^#([a-f0-9]{3}|[a-f0-9]{4}(?:[a-f0-9]{2}){0,2})$/i;\n\n/**\n * Regular expression for matching potential named color style strings.\n * @const\n * @type {RegExp}\n * @private\n */\nconst NAMED_COLOR_RE_ = /^([a-z]*)$|^hsla?\\(.*\\)$/i;\n\n/**\n * Return the color as an rgba string.\n * @param {Color|string} color Color.\n * @return {string} Rgba string.\n * @api\n */\nexport function asString(color) {\n if (typeof color === 'string') {\n return color;\n }\n return toString(color);\n}\n\n/**\n * Return named color as an rgba string.\n * @param {string} color Named color.\n * @return {string} Rgb string.\n */\nfunction fromNamed(color) {\n const el = document.createElement('div');\n el.style.color = color;\n if (el.style.color !== '') {\n document.body.appendChild(el);\n const rgb = getComputedStyle(el).color;\n document.body.removeChild(el);\n return rgb;\n }\n return '';\n}\n\n/**\n * @param {string} s String.\n * @return {Color} Color.\n */\nexport const fromString = (function () {\n // We maintain a small cache of parsed strings. To provide cheap LRU-like\n // semantics, whenever the cache grows too large we simply delete an\n // arbitrary 25% of the entries.\n\n /**\n * @const\n * @type {number}\n */\n const MAX_CACHE_SIZE = 1024;\n\n /**\n * @type {Object}\n */\n const cache = {};\n\n /**\n * @type {number}\n */\n let cacheSize = 0;\n\n return (\n /**\n * @param {string} s String.\n * @return {Color} Color.\n */\n function (s) {\n let color;\n if (cache.hasOwnProperty(s)) {\n color = cache[s];\n } else {\n if (cacheSize >= MAX_CACHE_SIZE) {\n let i = 0;\n for (const key in cache) {\n if ((i++ & 3) === 0) {\n delete cache[key];\n --cacheSize;\n }\n }\n }\n color = fromStringInternal_(s);\n cache[s] = color;\n ++cacheSize;\n }\n return color;\n }\n );\n})();\n\n/**\n * Return the color as an array. This function maintains a cache of calculated\n * arrays which means the result should not be modified.\n * @param {Color|string} color Color.\n * @return {Color} Color.\n * @api\n */\nexport function asArray(color) {\n if (Array.isArray(color)) {\n return color;\n }\n return fromString(color);\n}\n\n/**\n * @param {string} s String.\n * @private\n * @return {Color} Color.\n */\nfunction fromStringInternal_(s) {\n let r, g, b, a, color;\n\n if (NAMED_COLOR_RE_.exec(s)) {\n s = fromNamed(s);\n }\n\n if (HEX_COLOR_RE_.exec(s)) {\n // hex\n const n = s.length - 1; // number of hex digits\n let d; // number of digits per channel\n if (n <= 4) {\n d = 1;\n } else {\n d = 2;\n }\n const hasAlpha = n === 4 || n === 8;\n r = parseInt(s.substr(1 + 0 * d, d), 16);\n g = parseInt(s.substr(1 + 1 * d, d), 16);\n b = parseInt(s.substr(1 + 2 * d, d), 16);\n if (hasAlpha) {\n a = parseInt(s.substr(1 + 3 * d, d), 16);\n } else {\n a = 255;\n }\n if (d == 1) {\n r = (r << 4) + r;\n g = (g << 4) + g;\n b = (b << 4) + b;\n if (hasAlpha) {\n a = (a << 4) + a;\n }\n }\n color = [r, g, b, a / 255];\n } else if (s.startsWith('rgba(')) {\n // rgba()\n color = s.slice(5, -1).split(',').map(Number);\n normalize(color);\n } else if (s.startsWith('rgb(')) {\n // rgb()\n color = s.slice(4, -1).split(',').map(Number);\n color.push(1);\n normalize(color);\n } else {\n throw new Error('Invalid color');\n }\n return color;\n}\n\n/**\n * TODO this function is only used in the test, we probably shouldn't export it\n * @param {Color} color Color.\n * @return {Color} Clamped color.\n */\nexport function normalize(color) {\n color[0] = clamp((color[0] + 0.5) | 0, 0, 255);\n color[1] = clamp((color[1] + 0.5) | 0, 0, 255);\n color[2] = clamp((color[2] + 0.5) | 0, 0, 255);\n color[3] = clamp(color[3], 0, 1);\n return color;\n}\n\n/**\n * @param {Color} color Color.\n * @return {string} String.\n */\nexport function toString(color) {\n let r = color[0];\n if (r != (r | 0)) {\n r = (r + 0.5) | 0;\n }\n let g = color[1];\n if (g != (g | 0)) {\n g = (g + 0.5) | 0;\n }\n let b = color[2];\n if (b != (b | 0)) {\n b = (b + 0.5) | 0;\n }\n const a = color[3] === undefined ? 1 : Math.round(color[3] * 100) / 100;\n return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n}\n\n/**\n * @param {string} s String.\n * @return {boolean} Whether the string is actually a valid color\n */\nexport function isStringColor(s) {\n if (NAMED_COLOR_RE_.test(s)) {\n s = fromNamed(s);\n }\n return HEX_COLOR_RE_.test(s) || s.startsWith('rgba(') || s.startsWith('rgb(');\n}\n","/**\n * @module ol/style/IconImageCache\n */\nimport {asString} from '../color.js';\n\n/**\n * @classdesc\n * Singleton class. Available through {@link module:ol/style/IconImageCache.shared}.\n */\nclass IconImageCache {\n constructor() {\n /**\n * @type {!Object}\n * @private\n */\n this.cache_ = {};\n\n /**\n * @type {number}\n * @private\n */\n this.cacheSize_ = 0;\n\n /**\n * @type {number}\n * @private\n */\n this.maxCacheSize_ = 32;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n clear() {\n this.cache_ = {};\n this.cacheSize_ = 0;\n }\n\n /**\n * @return {boolean} Can expire cache.\n */\n canExpireCache() {\n return this.cacheSize_ > this.maxCacheSize_;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n expire() {\n if (this.canExpireCache()) {\n let i = 0;\n for (const key in this.cache_) {\n const iconImage = this.cache_[key];\n if ((i++ & 3) === 0 && !iconImage.hasListener()) {\n delete this.cache_[key];\n --this.cacheSize_;\n }\n }\n }\n }\n\n /**\n * @param {string} src Src.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../color.js\").Color} color Color.\n * @return {import(\"./IconImage.js\").default} Icon image.\n */\n get(src, crossOrigin, color) {\n const key = getKey(src, crossOrigin, color);\n return key in this.cache_ ? this.cache_[key] : null;\n }\n\n /**\n * @param {string} src Src.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../color.js\").Color} color Color.\n * @param {import(\"./IconImage.js\").default} iconImage Icon image.\n */\n set(src, crossOrigin, color, iconImage) {\n const key = getKey(src, crossOrigin, color);\n this.cache_[key] = iconImage;\n ++this.cacheSize_;\n }\n\n /**\n * Set the cache size of the icon cache. Default is `32`. Change this value when\n * your map uses more than 32 different icon images and you are not caching icon\n * styles on the application level.\n * @param {number} maxCacheSize Cache max size.\n * @api\n */\n setSize(maxCacheSize) {\n this.maxCacheSize_ = maxCacheSize;\n this.expire();\n }\n}\n\n/**\n * @param {string} src Src.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../color.js\").Color} color Color.\n * @return {string} Cache key.\n */\nfunction getKey(src, crossOrigin, color) {\n const colorString = color ? asString(color) : 'null';\n return crossOrigin + ':' + src + ':' + colorString;\n}\n\nexport default IconImageCache;\n\n/**\n * The {@link module:ol/style/IconImageCache~IconImageCache} for\n * {@link module:ol/style/Icon~Icon} images.\n * @api\n */\nexport const shared = new IconImageCache();\n","/**\n * @module ol/layer/Property\n */\n\n/**\n * @enum {string}\n */\nexport default {\n OPACITY: 'opacity',\n VISIBLE: 'visible',\n EXTENT: 'extent',\n Z_INDEX: 'zIndex',\n MAX_RESOLUTION: 'maxResolution',\n MIN_RESOLUTION: 'minResolution',\n MAX_ZOOM: 'maxZoom',\n MIN_ZOOM: 'minZoom',\n SOURCE: 'source',\n MAP: 'map',\n};\n","/**\n * @module ol/layer/Base\n */\nimport BaseObject from '../Object.js';\nimport LayerProperty from './Property.js';\nimport {abstract} from '../util.js';\nimport {assert} from '../asserts.js';\nimport {clamp} from '../math.js';\n\n/**\n * A css color, or a function called with a view resolution returning a css color.\n *\n * @typedef {string|function(number):string} BackgroundColor\n * @api\n */\n\n/**\n * @typedef {import(\"../ObjectEventType\").Types|'change:extent'|'change:maxResolution'|'change:maxZoom'|\n * 'change:minResolution'|'change:minZoom'|'change:opacity'|'change:visible'|'change:zIndex'} BaseLayerObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} BaseLayerOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number | undefined} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {BackgroundColor} [background] Background color for the layer. If not specified, no background\n * will be rendered.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Note that with {@link module:ol/layer/Base~BaseLayer} and all its subclasses, any property set in\n * the options is set as a {@link module:ol/Object~BaseObject} property on the layer object, so\n * is observable, and has get/set accessors.\n *\n * @api\n */\nclass BaseLayer extends BaseObject {\n /**\n * @param {Options} options Layer options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {BaseLayerOnSignature}\n */\n this.on;\n\n /***\n * @type {BaseLayerOnSignature}\n */\n this.once;\n\n /***\n * @type {BaseLayerOnSignature}\n */\n this.un;\n\n /**\n * @type {BackgroundColor|false}\n * @private\n */\n this.background_ = options.background;\n\n /**\n * @type {Object}\n */\n const properties = Object.assign({}, options);\n if (typeof options.properties === 'object') {\n delete properties.properties;\n Object.assign(properties, options.properties);\n }\n\n properties[LayerProperty.OPACITY] =\n options.opacity !== undefined ? options.opacity : 1;\n assert(\n typeof properties[LayerProperty.OPACITY] === 'number',\n 'Layer opacity must be a number'\n );\n\n properties[LayerProperty.VISIBLE] =\n options.visible !== undefined ? options.visible : true;\n properties[LayerProperty.Z_INDEX] = options.zIndex;\n properties[LayerProperty.MAX_RESOLUTION] =\n options.maxResolution !== undefined ? options.maxResolution : Infinity;\n properties[LayerProperty.MIN_RESOLUTION] =\n options.minResolution !== undefined ? options.minResolution : 0;\n properties[LayerProperty.MIN_ZOOM] =\n options.minZoom !== undefined ? options.minZoom : -Infinity;\n properties[LayerProperty.MAX_ZOOM] =\n options.maxZoom !== undefined ? options.maxZoom : Infinity;\n\n /**\n * @type {string}\n * @private\n */\n this.className_ =\n properties.className !== undefined ? properties.className : 'ol-layer';\n delete properties.className;\n\n this.setProperties(properties);\n\n /**\n * @type {import(\"./Layer.js\").State}\n * @private\n */\n this.state_ = null;\n }\n\n /**\n * Get the background for this layer.\n * @return {BackgroundColor|false} Layer background.\n */\n getBackground() {\n return this.background_;\n }\n\n /**\n * @return {string} CSS class name.\n */\n getClassName() {\n return this.className_;\n }\n\n /**\n * This method is not meant to be called by layers or layer renderers because the state\n * is incorrect if the layer is included in a layer group.\n *\n * @param {boolean} [managed] Layer is managed.\n * @return {import(\"./Layer.js\").State} Layer state.\n */\n getLayerState(managed) {\n /** @type {import(\"./Layer.js\").State} */\n const state =\n this.state_ ||\n /** @type {?} */ ({\n layer: this,\n managed: managed === undefined ? true : managed,\n });\n const zIndex = this.getZIndex();\n state.opacity = clamp(Math.round(this.getOpacity() * 100) / 100, 0, 1);\n state.visible = this.getVisible();\n state.extent = this.getExtent();\n state.zIndex = zIndex === undefined && !state.managed ? Infinity : zIndex;\n state.maxResolution = this.getMaxResolution();\n state.minResolution = Math.max(this.getMinResolution(), 0);\n state.minZoom = this.getMinZoom();\n state.maxZoom = this.getMaxZoom();\n this.state_ = state;\n\n return state;\n }\n\n /**\n * @abstract\n * @param {Array} [array] Array of layers (to be\n * modified in place).\n * @return {Array} Array of layers.\n */\n getLayersArray(array) {\n return abstract();\n }\n\n /**\n * @abstract\n * @param {Array} [states] Optional list of layer\n * states (to be modified in place).\n * @return {Array} List of layer states.\n */\n getLayerStatesArray(states) {\n return abstract();\n }\n\n /**\n * Return the {@link module:ol/extent~Extent extent} of the layer or `undefined` if it\n * will be visible regardless of extent.\n * @return {import(\"../extent.js\").Extent|undefined} The layer extent.\n * @observable\n * @api\n */\n getExtent() {\n return /** @type {import(\"../extent.js\").Extent|undefined} */ (\n this.get(LayerProperty.EXTENT)\n );\n }\n\n /**\n * Return the maximum resolution of the layer. Returns Infinity if\n * the layer has no maximum resolution set.\n * @return {number} The maximum resolution of the layer.\n * @observable\n * @api\n */\n getMaxResolution() {\n return /** @type {number} */ (this.get(LayerProperty.MAX_RESOLUTION));\n }\n\n /**\n * Return the minimum resolution of the layer. Returns 0 if\n * the layer has no minimum resolution set.\n * @return {number} The minimum resolution of the layer.\n * @observable\n * @api\n */\n getMinResolution() {\n return /** @type {number} */ (this.get(LayerProperty.MIN_RESOLUTION));\n }\n\n /**\n * Return the minimum zoom level of the layer. Returns -Infinity if\n * the layer has no minimum zoom set.\n * @return {number} The minimum zoom level of the layer.\n * @observable\n * @api\n */\n getMinZoom() {\n return /** @type {number} */ (this.get(LayerProperty.MIN_ZOOM));\n }\n\n /**\n * Return the maximum zoom level of the layer. Returns Infinity if\n * the layer has no maximum zoom set.\n * @return {number} The maximum zoom level of the layer.\n * @observable\n * @api\n */\n getMaxZoom() {\n return /** @type {number} */ (this.get(LayerProperty.MAX_ZOOM));\n }\n\n /**\n * Return the opacity of the layer (between 0 and 1).\n * @return {number} The opacity of the layer.\n * @observable\n * @api\n */\n getOpacity() {\n return /** @type {number} */ (this.get(LayerProperty.OPACITY));\n }\n\n /**\n * @abstract\n * @return {import(\"../source/Source.js\").State} Source state.\n */\n getSourceState() {\n return abstract();\n }\n\n /**\n * Return the value of this layer's `visible` property. To find out whether the layer\n * is visible on a map, use `isVisible()` instead.\n * @return {boolean} The value of the `visible` property of the layer.\n * @observable\n * @api\n */\n getVisible() {\n return /** @type {boolean} */ (this.get(LayerProperty.VISIBLE));\n }\n\n /**\n * Return the Z-index of the layer, which is used to order layers before\n * rendering. Returns undefined if the layer is unmanaged.\n * @return {number|undefined} The Z-index of the layer.\n * @observable\n * @api\n */\n getZIndex() {\n return /** @type {number|undefined} */ (this.get(LayerProperty.Z_INDEX));\n }\n\n /**\n * Sets the background color.\n * @param {BackgroundColor} [background] Background color.\n */\n setBackground(background) {\n this.background_ = background;\n this.changed();\n }\n\n /**\n * Set the extent at which the layer is visible. If `undefined`, the layer\n * will be visible at all extents.\n * @param {import(\"../extent.js\").Extent|undefined} extent The extent of the layer.\n * @observable\n * @api\n */\n setExtent(extent) {\n this.set(LayerProperty.EXTENT, extent);\n }\n\n /**\n * Set the maximum resolution at which the layer is visible.\n * @param {number} maxResolution The maximum resolution of the layer.\n * @observable\n * @api\n */\n setMaxResolution(maxResolution) {\n this.set(LayerProperty.MAX_RESOLUTION, maxResolution);\n }\n\n /**\n * Set the minimum resolution at which the layer is visible.\n * @param {number} minResolution The minimum resolution of the layer.\n * @observable\n * @api\n */\n setMinResolution(minResolution) {\n this.set(LayerProperty.MIN_RESOLUTION, minResolution);\n }\n\n /**\n * Set the maximum zoom (exclusive) at which the layer is visible.\n * Note that the zoom levels for layer visibility are based on the\n * view zoom level, which may be different from a tile source zoom level.\n * @param {number} maxZoom The maximum zoom of the layer.\n * @observable\n * @api\n */\n setMaxZoom(maxZoom) {\n this.set(LayerProperty.MAX_ZOOM, maxZoom);\n }\n\n /**\n * Set the minimum zoom (inclusive) at which the layer is visible.\n * Note that the zoom levels for layer visibility are based on the\n * view zoom level, which may be different from a tile source zoom level.\n * @param {number} minZoom The minimum zoom of the layer.\n * @observable\n * @api\n */\n setMinZoom(minZoom) {\n this.set(LayerProperty.MIN_ZOOM, minZoom);\n }\n\n /**\n * Set the opacity of the layer, allowed values range from 0 to 1.\n * @param {number} opacity The opacity of the layer.\n * @observable\n * @api\n */\n setOpacity(opacity) {\n assert(typeof opacity === 'number', 'Layer opacity must be a number');\n this.set(LayerProperty.OPACITY, opacity);\n }\n\n /**\n * Set the visibility of the layer (`true` or `false`).\n * @param {boolean} visible The visibility of the layer.\n * @observable\n * @api\n */\n setVisible(visible) {\n this.set(LayerProperty.VISIBLE, visible);\n }\n\n /**\n * Set Z-index of the layer, which is used to order layers before rendering.\n * The default Z-index is 0.\n * @param {number} zindex The z-index of the layer.\n * @observable\n * @api\n */\n setZIndex(zindex) {\n this.set(LayerProperty.Z_INDEX, zindex);\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n if (this.state_) {\n this.state_.layer = null;\n this.state_ = null;\n }\n super.disposeInternal();\n }\n}\n\nexport default BaseLayer;\n","/**\n * @module ol/render/EventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered before a layer is rendered.\n * @event module:ol/render/Event~RenderEvent#prerender\n * @api\n */\n PRERENDER: 'prerender',\n\n /**\n * Triggered after a layer is rendered.\n * @event module:ol/render/Event~RenderEvent#postrender\n * @api\n */\n POSTRENDER: 'postrender',\n\n /**\n * Triggered before layers are composed. When dispatched by the map, the event object will not have\n * a `context` set. When dispatched by a layer, the event object will have a `context` set. Only\n * WebGL layers currently dispatch this event.\n * @event module:ol/render/Event~RenderEvent#precompose\n * @api\n */\n PRECOMPOSE: 'precompose',\n\n /**\n * Triggered after layers are composed. When dispatched by the map, the event object will not have\n * a `context` set. When dispatched by a layer, the event object will have a `context` set. Only\n * WebGL layers currently dispatch this event.\n * @event module:ol/render/Event~RenderEvent#postcompose\n * @api\n */\n POSTCOMPOSE: 'postcompose',\n\n /**\n * Triggered when rendering is complete, i.e. all sources and tiles have\n * finished loading for the current viewport, and all tiles are faded in.\n * The event object will not have a `context` set.\n * @event module:ol/render/Event~RenderEvent#rendercomplete\n * @api\n */\n RENDERCOMPLETE: 'rendercomplete',\n};\n\n/**\n * @typedef {'postrender'|'precompose'|'postcompose'|'rendercomplete'} MapRenderEventTypes\n */\n\n/**\n * @typedef {'postrender'|'prerender'} LayerRenderEventTypes\n */\n","/**\n * @module ol/ViewHint\n */\n\n/**\n * @enum {number}\n */\nexport default {\n ANIMATING: 0,\n INTERACTING: 1,\n};\n","/**\n * @module ol/ViewProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n CENTER: 'center',\n RESOLUTION: 'resolution',\n ROTATION: 'rotation',\n};\n","/**\n * @module ol/tilegrid/common\n */\n\n/**\n * Default maximum zoom for default tile grids.\n * @type {number}\n */\nexport const DEFAULT_MAX_ZOOM = 42;\n\n/**\n * Default tile size.\n * @type {number}\n */\nexport const DEFAULT_TILE_SIZE = 256;\n","/**\n * @module ol/proj/Units\n */\n\n/**\n * @typedef {'radians' | 'degrees' | 'ft' | 'm' | 'pixels' | 'tile-pixels' | 'us-ft'} Units\n * Projection units.\n */\n\n/**\n * See http://duff.ess.washington.edu/data/raster/drg/docs/geotiff.txt\n * @type {Object}\n */\nconst unitByCode = {\n '9001': 'm',\n '9002': 'ft',\n '9003': 'us-ft',\n '9101': 'radians',\n '9102': 'degrees',\n};\n\n/**\n * @param {number} code Unit code.\n * @return {Units} Units.\n */\nexport function fromCode(code) {\n return unitByCode[code];\n}\n\n/**\n * @typedef {Object} MetersPerUnitLookup\n * @property {number} radians Radians\n * @property {number} degrees Degrees\n * @property {number} ft Feet\n * @property {number} m Meters\n * @property {number} us-ft US feet\n */\n\n/**\n * Meters per unit lookup table.\n * @const\n * @type {MetersPerUnitLookup}\n * @api\n */\nexport const METERS_PER_UNIT = {\n // use the radius of the Normal sphere\n 'radians': 6370997 / (2 * Math.PI),\n 'degrees': (2 * Math.PI * 6370997) / 360,\n 'ft': 0.3048,\n 'm': 1,\n 'us-ft': 1200 / 3937,\n};\n","/**\n * @module ol/proj/Projection\n */\nimport {METERS_PER_UNIT} from './Units.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} code The SRS identifier code, e.g. `EPSG:4326`.\n * @property {import(\"./Units.js\").Units} [units] Units. Required unless a\n * proj4 projection is defined for `code`.\n * @property {import(\"../extent.js\").Extent} [extent] The validity extent for the SRS.\n * @property {string} [axisOrientation='enu'] The axis orientation as specified in Proj4.\n * @property {boolean} [global=false] Whether the projection is valid for the whole globe.\n * @property {number} [metersPerUnit] The meters per unit for the SRS.\n * If not provided, the `units` are used to get the meters per unit from the {@link METERS_PER_UNIT}\n * lookup table.\n * @property {import(\"../extent.js\").Extent} [worldExtent] The world extent for the SRS.\n * @property {function(number, import(\"../coordinate.js\").Coordinate):number} [getPointResolution]\n * Function to determine resolution at a point. The function is called with a\n * `number` view resolution and a {@link module:ol/coordinate~Coordinate} as arguments, and returns\n * the `number` resolution in projection units at the passed coordinate. If this is `undefined`,\n * the default {@link module:ol/proj.getPointResolution} function will be used.\n */\n\n/**\n * @classdesc\n * Projection definition class. One of these is created for each projection\n * supported in the application and stored in the {@link module:ol/proj} namespace.\n * You can use these in applications, but this is not required, as API params\n * and options use {@link module:ol/proj~ProjectionLike} which means the simple string\n * code will suffice.\n *\n * You can use {@link module:ol/proj.get} to retrieve the object for a particular\n * projection.\n *\n * The library includes definitions for `EPSG:4326` and `EPSG:3857`, together\n * with the following aliases:\n * * `EPSG:4326`: CRS:84, urn:ogc:def:crs:EPSG:6.6:4326,\n * urn:ogc:def:crs:OGC:1.3:CRS84, urn:ogc:def:crs:OGC:2:84,\n * http://www.opengis.net/gml/srs/epsg.xml#4326,\n * urn:x-ogc:def:crs:EPSG:4326\n * * `EPSG:3857`: EPSG:102100, EPSG:102113, EPSG:900913,\n * urn:ogc:def:crs:EPSG:6.18:3:3857,\n * http://www.opengis.net/gml/srs/epsg.xml#3857\n *\n * If you use [proj4js](https://github.com/proj4js/proj4js), aliases can\n * be added using `proj4.defs()`. After all required projection definitions are\n * added, call the {@link module:ol/proj/proj4.register} function.\n *\n * @api\n */\nclass Projection {\n /**\n * @param {Options} options Projection options.\n */\n constructor(options) {\n /**\n * @private\n * @type {string}\n */\n this.code_ = options.code;\n\n /**\n * Units of projected coordinates. When set to `TILE_PIXELS`, a\n * `this.extent_` and `this.worldExtent_` must be configured properly for each\n * tile.\n * @private\n * @type {import(\"./Units.js\").Units}\n */\n this.units_ = /** @type {import(\"./Units.js\").Units} */ (options.units);\n\n /**\n * Validity extent of the projection in projected coordinates. For projections\n * with `TILE_PIXELS` units, this is the extent of the tile in\n * tile pixel space.\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.extent_ = options.extent !== undefined ? options.extent : null;\n\n /**\n * Extent of the world in EPSG:4326. For projections with\n * `TILE_PIXELS` units, this is the extent of the tile in\n * projected coordinate space.\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.worldExtent_ =\n options.worldExtent !== undefined ? options.worldExtent : null;\n\n /**\n * @private\n * @type {string}\n */\n this.axisOrientation_ =\n options.axisOrientation !== undefined ? options.axisOrientation : 'enu';\n\n /**\n * @private\n * @type {boolean}\n */\n this.global_ = options.global !== undefined ? options.global : false;\n\n /**\n * @private\n * @type {boolean}\n */\n this.canWrapX_ = !!(this.global_ && this.extent_);\n\n /**\n * @private\n * @type {function(number, import(\"../coordinate.js\").Coordinate):number|undefined}\n */\n this.getPointResolutionFunc_ = options.getPointResolution;\n\n /**\n * @private\n * @type {import(\"../tilegrid/TileGrid.js\").default}\n */\n this.defaultTileGrid_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.metersPerUnit_ = options.metersPerUnit;\n }\n\n /**\n * @return {boolean} The projection is suitable for wrapping the x-axis\n */\n canWrapX() {\n return this.canWrapX_;\n }\n\n /**\n * Get the code for this projection, e.g. 'EPSG:4326'.\n * @return {string} Code.\n * @api\n */\n getCode() {\n return this.code_;\n }\n\n /**\n * Get the validity extent for this projection.\n * @return {import(\"../extent.js\").Extent} Extent.\n * @api\n */\n getExtent() {\n return this.extent_;\n }\n\n /**\n * Get the units of this projection.\n * @return {import(\"./Units.js\").Units} Units.\n * @api\n */\n getUnits() {\n return this.units_;\n }\n\n /**\n * Get the amount of meters per unit of this projection. If the projection is\n * not configured with `metersPerUnit` or a units identifier, the return is\n * `undefined`.\n * @return {number|undefined} Meters.\n * @api\n */\n getMetersPerUnit() {\n return this.metersPerUnit_ || METERS_PER_UNIT[this.units_];\n }\n\n /**\n * Get the world extent for this projection.\n * @return {import(\"../extent.js\").Extent} Extent.\n * @api\n */\n getWorldExtent() {\n return this.worldExtent_;\n }\n\n /**\n * Get the axis orientation of this projection.\n * Example values are:\n * enu - the default easting, northing, elevation.\n * neu - northing, easting, up - useful for \"lat/long\" geographic coordinates,\n * or south orientated transverse mercator.\n * wnu - westing, northing, up - some planetary coordinate systems have\n * \"west positive\" coordinate systems\n * @return {string} Axis orientation.\n * @api\n */\n getAxisOrientation() {\n return this.axisOrientation_;\n }\n\n /**\n * Is this projection a global projection which spans the whole world?\n * @return {boolean} Whether the projection is global.\n * @api\n */\n isGlobal() {\n return this.global_;\n }\n\n /**\n * Set if the projection is a global projection which spans the whole world\n * @param {boolean} global Whether the projection is global.\n * @api\n */\n setGlobal(global) {\n this.global_ = global;\n this.canWrapX_ = !!(global && this.extent_);\n }\n\n /**\n * @return {import(\"../tilegrid/TileGrid.js\").default} The default tile grid.\n */\n getDefaultTileGrid() {\n return this.defaultTileGrid_;\n }\n\n /**\n * @param {import(\"../tilegrid/TileGrid.js\").default} tileGrid The default tile grid.\n */\n setDefaultTileGrid(tileGrid) {\n this.defaultTileGrid_ = tileGrid;\n }\n\n /**\n * Set the validity extent for this projection.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @api\n */\n setExtent(extent) {\n this.extent_ = extent;\n this.canWrapX_ = !!(this.global_ && extent);\n }\n\n /**\n * Set the world extent for this projection.\n * @param {import(\"../extent.js\").Extent} worldExtent World extent\n * [minlon, minlat, maxlon, maxlat].\n * @api\n */\n setWorldExtent(worldExtent) {\n this.worldExtent_ = worldExtent;\n }\n\n /**\n * Set the getPointResolution function (see {@link module:ol/proj.getPointResolution}\n * for this projection.\n * @param {function(number, import(\"../coordinate.js\").Coordinate):number} func Function\n * @api\n */\n setGetPointResolution(func) {\n this.getPointResolutionFunc_ = func;\n }\n\n /**\n * Get the custom point resolution function for this projection (if set).\n * @return {function(number, import(\"../coordinate.js\").Coordinate):number|undefined} The custom point\n * resolution function (if set).\n */\n getPointResolutionFunc() {\n return this.getPointResolutionFunc_;\n }\n}\n\nexport default Projection;\n","/**\n * @module ol/proj/epsg3857\n */\nimport Projection from './Projection.js';\n\n/**\n * Radius of WGS84 sphere\n *\n * @const\n * @type {number}\n */\nexport const RADIUS = 6378137;\n\n/**\n * @const\n * @type {number}\n */\nexport const HALF_SIZE = Math.PI * RADIUS;\n\n/**\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const EXTENT = [-HALF_SIZE, -HALF_SIZE, HALF_SIZE, HALF_SIZE];\n\n/**\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const WORLD_EXTENT = [-180, -85, 180, 85];\n\n/**\n * Maximum safe value in y direction\n * @const\n * @type {number}\n */\nexport const MAX_SAFE_Y = RADIUS * Math.log(Math.tan(Math.PI / 2));\n\n/**\n * @classdesc\n * Projection object for web/spherical Mercator (EPSG:3857).\n */\nclass EPSG3857Projection extends Projection {\n /**\n * @param {string} code Code.\n */\n constructor(code) {\n super({\n code: code,\n units: 'm',\n extent: EXTENT,\n global: true,\n worldExtent: WORLD_EXTENT,\n getPointResolution: function (resolution, point) {\n return resolution / Math.cosh(point[1] / RADIUS);\n },\n });\n }\n}\n\n/**\n * Projections equal to EPSG:3857.\n *\n * @const\n * @type {Array}\n */\nexport const PROJECTIONS = [\n new EPSG3857Projection('EPSG:3857'),\n new EPSG3857Projection('EPSG:102100'),\n new EPSG3857Projection('EPSG:102113'),\n new EPSG3857Projection('EPSG:900913'),\n new EPSG3857Projection('http://www.opengis.net/def/crs/EPSG/0/3857'),\n new EPSG3857Projection('http://www.opengis.net/gml/srs/epsg.xml#3857'),\n];\n\n/**\n * Transformation from EPSG:4326 to EPSG:3857.\n *\n * @param {Array} input Input array of coordinate values.\n * @param {Array} [output] Output array of coordinate values.\n * @param {number} [dimension] Dimension (default is `2`).\n * @return {Array} Output array of coordinate values.\n */\nexport function fromEPSG4326(input, output, dimension) {\n const length = input.length;\n dimension = dimension > 1 ? dimension : 2;\n if (output === undefined) {\n if (dimension > 2) {\n // preserve values beyond second dimension\n output = input.slice();\n } else {\n output = new Array(length);\n }\n }\n for (let i = 0; i < length; i += dimension) {\n output[i] = (HALF_SIZE * input[i]) / 180;\n let y = RADIUS * Math.log(Math.tan((Math.PI * (+input[i + 1] + 90)) / 360));\n if (y > MAX_SAFE_Y) {\n y = MAX_SAFE_Y;\n } else if (y < -MAX_SAFE_Y) {\n y = -MAX_SAFE_Y;\n }\n output[i + 1] = y;\n }\n return output;\n}\n\n/**\n * Transformation from EPSG:3857 to EPSG:4326.\n *\n * @param {Array} input Input array of coordinate values.\n * @param {Array} [output] Output array of coordinate values.\n * @param {number} [dimension] Dimension (default is `2`).\n * @return {Array} Output array of coordinate values.\n */\nexport function toEPSG4326(input, output, dimension) {\n const length = input.length;\n dimension = dimension > 1 ? dimension : 2;\n if (output === undefined) {\n if (dimension > 2) {\n // preserve values beyond second dimension\n output = input.slice();\n } else {\n output = new Array(length);\n }\n }\n for (let i = 0; i < length; i += dimension) {\n output[i] = (180 * input[i]) / HALF_SIZE;\n output[i + 1] =\n (360 * Math.atan(Math.exp(input[i + 1] / RADIUS))) / Math.PI - 90;\n }\n return output;\n}\n","/**\n * @module ol/proj/epsg4326\n */\nimport Projection from './Projection.js';\n\n/**\n * Semi-major radius of the WGS84 ellipsoid.\n *\n * @const\n * @type {number}\n */\nexport const RADIUS = 6378137;\n\n/**\n * Extent of the EPSG:4326 projection which is the whole world.\n *\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const EXTENT = [-180, -90, 180, 90];\n\n/**\n * @const\n * @type {number}\n */\nexport const METERS_PER_UNIT = (Math.PI * RADIUS) / 180;\n\n/**\n * @classdesc\n * Projection object for WGS84 geographic coordinates (EPSG:4326).\n *\n * Note that OpenLayers does not strictly comply with the EPSG definition.\n * The EPSG registry defines 4326 as a CRS for Latitude,Longitude (y,x).\n * OpenLayers treats EPSG:4326 as a pseudo-projection, with x,y coordinates.\n */\nclass EPSG4326Projection extends Projection {\n /**\n * @param {string} code Code.\n * @param {string} [axisOrientation] Axis orientation.\n */\n constructor(code, axisOrientation) {\n super({\n code: code,\n units: 'degrees',\n extent: EXTENT,\n axisOrientation: axisOrientation,\n global: true,\n metersPerUnit: METERS_PER_UNIT,\n worldExtent: EXTENT,\n });\n }\n}\n\n/**\n * Projections equal to EPSG:4326.\n *\n * @const\n * @type {Array}\n */\nexport const PROJECTIONS = [\n new EPSG4326Projection('CRS:84'),\n new EPSG4326Projection('EPSG:4326', 'neu'),\n new EPSG4326Projection('urn:ogc:def:crs:OGC:1.3:CRS84'),\n new EPSG4326Projection('urn:ogc:def:crs:OGC:2:84'),\n new EPSG4326Projection('http://www.opengis.net/def/crs/OGC/1.3/CRS84'),\n new EPSG4326Projection('http://www.opengis.net/gml/srs/epsg.xml#4326', 'neu'),\n new EPSG4326Projection('http://www.opengis.net/def/crs/EPSG/0/4326', 'neu'),\n];\n","/**\n * @module ol/proj/projections\n */\n\n/**\n * @type {Object}\n */\nlet cache = {};\n\n/**\n * Clear the projections cache.\n */\nexport function clear() {\n cache = {};\n}\n\n/**\n * Get a cached projection by code.\n * @param {string} code The code for the projection.\n * @return {import(\"./Projection.js\").default} The projection (if cached).\n */\nexport function get(code) {\n return (\n cache[code] ||\n cache[code.replace(/urn:(x-)?ogc:def:crs:EPSG:(.*:)?(\\w+)$/, 'EPSG:$3')] ||\n null\n );\n}\n\n/**\n * Add a projection to the cache.\n * @param {string} code The projection code.\n * @param {import(\"./Projection.js\").default} projection The projection to cache.\n */\nexport function add(code, projection) {\n cache[code] = projection;\n}\n","/**\n * @module ol/proj/transforms\n */\nimport {isEmpty} from '../obj.js';\n\n/**\n * @private\n * @type {!Object>}\n */\nlet transforms = {};\n\n/**\n * Clear the transform cache.\n */\nexport function clear() {\n transforms = {};\n}\n\n/**\n * Registers a conversion function to convert coordinates from the source\n * projection to the destination projection.\n *\n * @param {import(\"./Projection.js\").default} source Source.\n * @param {import(\"./Projection.js\").default} destination Destination.\n * @param {import(\"../proj.js\").TransformFunction} transformFn Transform.\n */\nexport function add(source, destination, transformFn) {\n const sourceCode = source.getCode();\n const destinationCode = destination.getCode();\n if (!(sourceCode in transforms)) {\n transforms[sourceCode] = {};\n }\n transforms[sourceCode][destinationCode] = transformFn;\n}\n\n/**\n * Unregisters the conversion function to convert coordinates from the source\n * projection to the destination projection. This method is used to clean up\n * cached transforms during testing.\n *\n * @param {import(\"./Projection.js\").default} source Source projection.\n * @param {import(\"./Projection.js\").default} destination Destination projection.\n * @return {import(\"../proj.js\").TransformFunction} transformFn The unregistered transform.\n */\nexport function remove(source, destination) {\n const sourceCode = source.getCode();\n const destinationCode = destination.getCode();\n const transform = transforms[sourceCode][destinationCode];\n delete transforms[sourceCode][destinationCode];\n if (isEmpty(transforms[sourceCode])) {\n delete transforms[sourceCode];\n }\n return transform;\n}\n\n/**\n * Get a transform given a source code and a destination code.\n * @param {string} sourceCode The code for the source projection.\n * @param {string} destinationCode The code for the destination projection.\n * @return {import(\"../proj.js\").TransformFunction|undefined} The transform function (if found).\n */\nexport function get(sourceCode, destinationCode) {\n let transform;\n if (sourceCode in transforms && destinationCode in transforms[sourceCode]) {\n transform = transforms[sourceCode][destinationCode];\n }\n return transform;\n}\n","/**\n * @module ol/coordinate\n */\nimport {getWidth} from './extent.js';\nimport {modulo, toFixed} from './math.js';\nimport {padNumber} from './string.js';\n\n/**\n * An array of numbers representing an `xy`, `xyz` or `xyzm` coordinate.\n * Example: `[16, 48]`.\n * @typedef {Array} Coordinate\n * @api\n */\n\n/**\n * A function that takes a {@link module:ol/coordinate~Coordinate} and\n * transforms it into a `{string}`.\n *\n * @typedef {function((Coordinate|undefined)): string} CoordinateFormat\n * @api\n */\n\n/**\n * Add `delta` to `coordinate`. `coordinate` is modified in place and returned\n * by the function.\n *\n * Example:\n *\n * import {add} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * add(coord, [-2, 4]);\n * // coord is now [5.85, 51.983333]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {Coordinate} delta Delta.\n * @return {Coordinate} The input coordinate adjusted by\n * the given delta.\n * @api\n */\nexport function add(coordinate, delta) {\n coordinate[0] += +delta[0];\n coordinate[1] += +delta[1];\n return coordinate;\n}\n\n/**\n * Calculates the point closest to the passed coordinate on the passed circle.\n *\n * @param {Coordinate} coordinate The coordinate.\n * @param {import(\"./geom/Circle.js\").default} circle The circle.\n * @return {Coordinate} Closest point on the circumference.\n */\nexport function closestOnCircle(coordinate, circle) {\n const r = circle.getRadius();\n const center = circle.getCenter();\n const x0 = center[0];\n const y0 = center[1];\n const x1 = coordinate[0];\n const y1 = coordinate[1];\n\n let dx = x1 - x0;\n const dy = y1 - y0;\n if (dx === 0 && dy === 0) {\n dx = 1;\n }\n const d = Math.sqrt(dx * dx + dy * dy);\n\n const x = x0 + (r * dx) / d;\n const y = y0 + (r * dy) / d;\n\n return [x, y];\n}\n\n/**\n * Calculates the point closest to the passed coordinate on the passed segment.\n * This is the foot of the perpendicular of the coordinate to the segment when\n * the foot is on the segment, or the closest segment coordinate when the foot\n * is outside the segment.\n *\n * @param {Coordinate} coordinate The coordinate.\n * @param {Array} segment The two coordinates\n * of the segment.\n * @return {Coordinate} The foot of the perpendicular of\n * the coordinate to the segment.\n */\nexport function closestOnSegment(coordinate, segment) {\n const x0 = coordinate[0];\n const y0 = coordinate[1];\n const start = segment[0];\n const end = segment[1];\n const x1 = start[0];\n const y1 = start[1];\n const x2 = end[0];\n const y2 = end[1];\n const dx = x2 - x1;\n const dy = y2 - y1;\n const along =\n dx === 0 && dy === 0\n ? 0\n : (dx * (x0 - x1) + dy * (y0 - y1)) / (dx * dx + dy * dy || 0);\n let x, y;\n if (along <= 0) {\n x = x1;\n y = y1;\n } else if (along >= 1) {\n x = x2;\n y = y2;\n } else {\n x = x1 + along * dx;\n y = y1 + along * dy;\n }\n return [x, y];\n}\n\n/**\n * Returns a {@link module:ol/coordinate~CoordinateFormat} function that can be\n * used to format\n * a {Coordinate} to a string.\n *\n * Example without specifying the fractional digits:\n *\n * import {createStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const stringifyFunc = createStringXY();\n * const out = stringifyFunc(coord);\n * // out is now '8, 48'\n *\n * Example with explicitly specifying 2 fractional digits:\n *\n * import {createStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const stringifyFunc = createStringXY(2);\n * const out = stringifyFunc(coord);\n * // out is now '7.85, 47.98'\n *\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {CoordinateFormat} Coordinate format.\n * @api\n */\nexport function createStringXY(fractionDigits) {\n return (\n /**\n * @param {Coordinate} coordinate Coordinate.\n * @return {string} String XY.\n */\n function (coordinate) {\n return toStringXY(coordinate, fractionDigits);\n }\n );\n}\n\n/**\n * @param {string} hemispheres Hemispheres.\n * @param {number} degrees Degrees.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} String.\n */\nexport function degreesToStringHDMS(hemispheres, degrees, fractionDigits) {\n const normalizedDegrees = modulo(degrees + 180, 360) - 180;\n const x = Math.abs(3600 * normalizedDegrees);\n const decimals = fractionDigits || 0;\n\n let deg = Math.floor(x / 3600);\n let min = Math.floor((x - deg * 3600) / 60);\n let sec = toFixed(x - deg * 3600 - min * 60, decimals);\n\n if (sec >= 60) {\n sec = 0;\n min += 1;\n }\n\n if (min >= 60) {\n min = 0;\n deg += 1;\n }\n\n let hdms = deg + '\\u00b0';\n if (min !== 0 || sec !== 0) {\n hdms += ' ' + padNumber(min, 2) + '\\u2032';\n }\n if (sec !== 0) {\n hdms += ' ' + padNumber(sec, 2, decimals) + '\\u2033';\n }\n if (normalizedDegrees !== 0) {\n hdms += ' ' + hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0);\n }\n\n return hdms;\n}\n\n/**\n * Transforms the given {@link module:ol/coordinate~Coordinate} to a string\n * using the given string template. The strings `{x}` and `{y}` in the template\n * will be replaced with the first and second coordinate values respectively.\n *\n * Example without specifying the fractional digits:\n *\n * import {format} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const template = 'Coordinate is ({x}|{y}).';\n * const out = format(coord, template);\n * // out is now 'Coordinate is (8|48).'\n *\n * Example explicitly specifying the fractional digits:\n *\n * import {format} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const template = 'Coordinate is ({x}|{y}).';\n * const out = format(coord, template, 2);\n * // out is now 'Coordinate is (7.85|47.98).'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {string} template A template string with `{x}` and `{y}` placeholders\n * that will be replaced by first and second coordinate values.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} Formatted coordinate.\n * @api\n */\nexport function format(coordinate, template, fractionDigits) {\n if (coordinate) {\n return template\n .replace('{x}', coordinate[0].toFixed(fractionDigits))\n .replace('{y}', coordinate[1].toFixed(fractionDigits));\n }\n return '';\n}\n\n/**\n * @param {Coordinate} coordinate1 First coordinate.\n * @param {Coordinate} coordinate2 Second coordinate.\n * @return {boolean} The two coordinates are equal.\n */\nexport function equals(coordinate1, coordinate2) {\n let equals = true;\n for (let i = coordinate1.length - 1; i >= 0; --i) {\n if (coordinate1[i] != coordinate2[i]) {\n equals = false;\n break;\n }\n }\n return equals;\n}\n\n/**\n * Rotate `coordinate` by `angle`. `coordinate` is modified in place and\n * returned by the function.\n *\n * Example:\n *\n * import {rotate} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const rotateRadians = Math.PI / 2; // 90 degrees\n * rotate(coord, rotateRadians);\n * // coord is now [-47.983333, 7.85]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} angle Angle in radian.\n * @return {Coordinate} Coordinate.\n * @api\n */\nexport function rotate(coordinate, angle) {\n const cosAngle = Math.cos(angle);\n const sinAngle = Math.sin(angle);\n const x = coordinate[0] * cosAngle - coordinate[1] * sinAngle;\n const y = coordinate[1] * cosAngle + coordinate[0] * sinAngle;\n coordinate[0] = x;\n coordinate[1] = y;\n return coordinate;\n}\n\n/**\n * Scale `coordinate` by `scale`. `coordinate` is modified in place and returned\n * by the function.\n *\n * Example:\n *\n * import {scale as scaleCoordinate} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const scale = 1.2;\n * scaleCoordinate(coord, scale);\n * // coord is now [9.42, 57.5799996]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} scale Scale factor.\n * @return {Coordinate} Coordinate.\n */\nexport function scale(coordinate, scale) {\n coordinate[0] *= scale;\n coordinate[1] *= scale;\n return coordinate;\n}\n\n/**\n * @param {Coordinate} coord1 First coordinate.\n * @param {Coordinate} coord2 Second coordinate.\n * @return {number} Squared distance between coord1 and coord2.\n */\nexport function squaredDistance(coord1, coord2) {\n const dx = coord1[0] - coord2[0];\n const dy = coord1[1] - coord2[1];\n return dx * dx + dy * dy;\n}\n\n/**\n * @param {Coordinate} coord1 First coordinate.\n * @param {Coordinate} coord2 Second coordinate.\n * @return {number} Distance between coord1 and coord2.\n */\nexport function distance(coord1, coord2) {\n return Math.sqrt(squaredDistance(coord1, coord2));\n}\n\n/**\n * Calculate the squared distance from a coordinate to a line segment.\n *\n * @param {Coordinate} coordinate Coordinate of the point.\n * @param {Array} segment Line segment (2\n * coordinates).\n * @return {number} Squared distance from the point to the line segment.\n */\nexport function squaredDistanceToSegment(coordinate, segment) {\n return squaredDistance(coordinate, closestOnSegment(coordinate, segment));\n}\n\n/**\n * Format a geographic coordinate with the hemisphere, degrees, minutes, and\n * seconds.\n *\n * Example without specifying fractional digits:\n *\n * import {toStringHDMS} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringHDMS(coord);\n * // out is now '47° 58′ 60″ N 7° 50′ 60″ E'\n *\n * Example explicitly specifying 1 fractional digit:\n *\n * import {toStringHDMS} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringHDMS(coord, 1);\n * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} Hemisphere, degrees, minutes and seconds.\n * @api\n */\nexport function toStringHDMS(coordinate, fractionDigits) {\n if (coordinate) {\n return (\n degreesToStringHDMS('NS', coordinate[1], fractionDigits) +\n ' ' +\n degreesToStringHDMS('EW', coordinate[0], fractionDigits)\n );\n }\n return '';\n}\n\n/**\n * Format a coordinate as a comma delimited string.\n *\n * Example without specifying fractional digits:\n *\n * import {toStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringXY(coord);\n * // out is now '8, 48'\n *\n * Example explicitly specifying 1 fractional digit:\n *\n * import {toStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringXY(coord, 1);\n * // out is now '7.8, 48.0'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} XY.\n * @api\n */\nexport function toStringXY(coordinate, fractionDigits) {\n return format(coordinate, '{x}, {y}', fractionDigits);\n}\n\n/**\n * Modifies the provided coordinate in-place to be within the real world\n * extent. The lower projection extent boundary is inclusive, the upper one\n * exclusive.\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {Coordinate} The coordinate within the real world extent.\n */\nexport function wrapX(coordinate, projection) {\n if (projection.canWrapX()) {\n const worldWidth = getWidth(projection.getExtent());\n const worldsAway = getWorldsAway(coordinate, projection, worldWidth);\n if (worldsAway) {\n coordinate[0] -= worldsAway * worldWidth;\n }\n }\n return coordinate;\n}\n/**\n * @param {Coordinate} coordinate Coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @param {number} [sourceExtentWidth] Width of the source extent.\n * @return {number} Offset in world widths.\n */\nexport function getWorldsAway(coordinate, projection, sourceExtentWidth) {\n const projectionExtent = projection.getExtent();\n let worldsAway = 0;\n if (\n projection.canWrapX() &&\n (coordinate[0] < projectionExtent[0] || coordinate[0] > projectionExtent[2])\n ) {\n sourceExtentWidth = sourceExtentWidth || getWidth(projectionExtent);\n worldsAway = Math.floor(\n (coordinate[0] - projectionExtent[0]) / sourceExtentWidth\n );\n }\n return worldsAway;\n}\n","/**\n * @module ol/sphere\n */\nimport {toDegrees, toRadians} from './math.js';\n\n/**\n * Object literal with options for the {@link getLength} or {@link getArea}\n * functions.\n * @typedef {Object} SphereMetricOptions\n * @property {import(\"./proj.js\").ProjectionLike} [projection='EPSG:3857']\n * Projection of the geometry. By default, the geometry is assumed to be in\n * Web Mercator.\n * @property {number} [radius=6371008.8] Sphere radius. By default, the\n * [mean Earth radius](https://en.wikipedia.org/wiki/Earth_radius#Mean_radius)\n * for the WGS84 ellipsoid is used.\n */\n\n/**\n * The mean Earth radius (1/3 * (2a + b)) for the WGS84 ellipsoid.\n * https://en.wikipedia.org/wiki/Earth_radius#Mean_radius\n * @type {number}\n */\nexport const DEFAULT_RADIUS = 6371008.8;\n\n/**\n * Get the great circle distance (in meters) between two geographic coordinates.\n * @param {Array} c1 Starting coordinate.\n * @param {Array} c2 Ending coordinate.\n * @param {number} [radius] The sphere radius to use. Defaults to the Earth's\n * mean radius using the WGS84 ellipsoid.\n * @return {number} The great circle distance between the points (in meters).\n * @api\n */\nexport function getDistance(c1, c2, radius) {\n radius = radius || DEFAULT_RADIUS;\n const lat1 = toRadians(c1[1]);\n const lat2 = toRadians(c2[1]);\n const deltaLatBy2 = (lat2 - lat1) / 2;\n const deltaLonBy2 = toRadians(c2[0] - c1[0]) / 2;\n const a =\n Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) +\n Math.sin(deltaLonBy2) *\n Math.sin(deltaLonBy2) *\n Math.cos(lat1) *\n Math.cos(lat2);\n return 2 * radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n}\n\n/**\n * Get the cumulative great circle length of linestring coordinates (geographic).\n * @param {Array} coordinates Linestring coordinates.\n * @param {number} radius The sphere radius to use.\n * @return {number} The length (in meters).\n */\nfunction getLengthInternal(coordinates, radius) {\n let length = 0;\n for (let i = 0, ii = coordinates.length; i < ii - 1; ++i) {\n length += getDistance(coordinates[i], coordinates[i + 1], radius);\n }\n return length;\n}\n\n/**\n * Get the spherical length of a geometry. This length is the sum of the\n * great circle distances between coordinates. For polygons, the length is\n * the sum of all rings. For points, the length is zero. For multi-part\n * geometries, the length is the sum of the length of each part.\n * @param {import(\"./geom/Geometry.js\").default} geometry A geometry.\n * @param {SphereMetricOptions} [options] Options for the\n * length calculation. By default, geometries are assumed to be in 'EPSG:3857'.\n * You can change this by providing a `projection` option.\n * @return {number} The spherical length (in meters).\n * @api\n */\nexport function getLength(geometry, options) {\n options = options || {};\n const radius = options.radius || DEFAULT_RADIUS;\n const projection = options.projection || 'EPSG:3857';\n const type = geometry.getType();\n if (type !== 'GeometryCollection') {\n geometry = geometry.clone().transform(projection, 'EPSG:4326');\n }\n let length = 0;\n let coordinates, coords, i, ii, j, jj;\n switch (type) {\n case 'Point':\n case 'MultiPoint': {\n break;\n }\n case 'LineString':\n case 'LinearRing': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n length = getLengthInternal(coordinates, radius);\n break;\n }\n case 'MultiLineString':\n case 'Polygon': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n for (i = 0, ii = coordinates.length; i < ii; ++i) {\n length += getLengthInternal(coordinates[i], radius);\n }\n break;\n }\n case 'MultiPolygon': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n for (i = 0, ii = coordinates.length; i < ii; ++i) {\n coords = coordinates[i];\n for (j = 0, jj = coords.length; j < jj; ++j) {\n length += getLengthInternal(coords[j], radius);\n }\n }\n break;\n }\n case 'GeometryCollection': {\n const geometries =\n /** @type {import(\"./geom/GeometryCollection.js\").default} */ (\n geometry\n ).getGeometries();\n for (i = 0, ii = geometries.length; i < ii; ++i) {\n length += getLength(geometries[i], options);\n }\n break;\n }\n default: {\n throw new Error('Unsupported geometry type: ' + type);\n }\n }\n return length;\n}\n\n/**\n * Returns the spherical area for a list of coordinates.\n *\n * [Reference](https://trs.jpl.nasa.gov/handle/2014/40409)\n * Robert. G. Chamberlain and William H. Duquette, \"Some Algorithms for\n * Polygons on a Sphere\", JPL Publication 07-03, Jet Propulsion\n * Laboratory, Pasadena, CA, June 2007\n *\n * @param {Array} coordinates List of coordinates of a linear\n * ring. If the ring is oriented clockwise, the area will be positive,\n * otherwise it will be negative.\n * @param {number} radius The sphere radius.\n * @return {number} Area (in square meters).\n */\nfunction getAreaInternal(coordinates, radius) {\n let area = 0;\n const len = coordinates.length;\n let x1 = coordinates[len - 1][0];\n let y1 = coordinates[len - 1][1];\n for (let i = 0; i < len; i++) {\n const x2 = coordinates[i][0];\n const y2 = coordinates[i][1];\n area +=\n toRadians(x2 - x1) *\n (2 + Math.sin(toRadians(y1)) + Math.sin(toRadians(y2)));\n x1 = x2;\n y1 = y2;\n }\n return (area * radius * radius) / 2.0;\n}\n\n/**\n * Get the spherical area of a geometry. This is the area (in meters) assuming\n * that polygon edges are segments of great circles on a sphere.\n * @param {import(\"./geom/Geometry.js\").default} geometry A geometry.\n * @param {SphereMetricOptions} [options] Options for the area\n * calculation. By default, geometries are assumed to be in 'EPSG:3857'.\n * You can change this by providing a `projection` option.\n * @return {number} The spherical area (in square meters).\n * @api\n */\nexport function getArea(geometry, options) {\n options = options || {};\n const radius = options.radius || DEFAULT_RADIUS;\n const projection = options.projection || 'EPSG:3857';\n const type = geometry.getType();\n if (type !== 'GeometryCollection') {\n geometry = geometry.clone().transform(projection, 'EPSG:4326');\n }\n let area = 0;\n let coordinates, coords, i, ii, j, jj;\n switch (type) {\n case 'Point':\n case 'MultiPoint':\n case 'LineString':\n case 'MultiLineString':\n case 'LinearRing': {\n break;\n }\n case 'Polygon': {\n coordinates = /** @type {import(\"./geom/Polygon.js\").default} */ (\n geometry\n ).getCoordinates();\n area = Math.abs(getAreaInternal(coordinates[0], radius));\n for (i = 1, ii = coordinates.length; i < ii; ++i) {\n area -= Math.abs(getAreaInternal(coordinates[i], radius));\n }\n break;\n }\n case 'MultiPolygon': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n for (i = 0, ii = coordinates.length; i < ii; ++i) {\n coords = coordinates[i];\n area += Math.abs(getAreaInternal(coords[0], radius));\n for (j = 1, jj = coords.length; j < jj; ++j) {\n area -= Math.abs(getAreaInternal(coords[j], radius));\n }\n }\n break;\n }\n case 'GeometryCollection': {\n const geometries =\n /** @type {import(\"./geom/GeometryCollection.js\").default} */ (\n geometry\n ).getGeometries();\n for (i = 0, ii = geometries.length; i < ii; ++i) {\n area += getArea(geometries[i], options);\n }\n break;\n }\n default: {\n throw new Error('Unsupported geometry type: ' + type);\n }\n }\n return area;\n}\n\n/**\n * Returns the coordinate at the given distance and bearing from `c1`.\n *\n * @param {import(\"./coordinate.js\").Coordinate} c1 The origin point (`[lon, lat]` in degrees).\n * @param {number} distance The great-circle distance between the origin\n * point and the target point.\n * @param {number} bearing The bearing (in radians).\n * @param {number} [radius] The sphere radius to use. Defaults to the Earth's\n * mean radius using the WGS84 ellipsoid.\n * @return {import(\"./coordinate.js\").Coordinate} The target point.\n */\nexport function offset(c1, distance, bearing, radius) {\n radius = radius || DEFAULT_RADIUS;\n const lat1 = toRadians(c1[1]);\n const lon1 = toRadians(c1[0]);\n const dByR = distance / radius;\n const lat = Math.asin(\n Math.sin(lat1) * Math.cos(dByR) +\n Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing)\n );\n const lon =\n lon1 +\n Math.atan2(\n Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),\n Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat)\n );\n return [toDegrees(lon), toDegrees(lat)];\n}\n","/**\n * @module ol/console\n */\n\n/**\n * @typedef {'info'|'warn'|'error'|'none'} Level\n */\n\n/**\n * @type {Object}\n */\nconst levels = {\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n};\n\n/**\n * @type {number}\n */\nlet level = levels.info;\n\n/**\n * Set the logging level. By default, the level is set to 'info' and all\n * messages will be logged. Set to 'warn' to only display warnings and errors.\n * Set to 'error' to only display errors. Set to 'none' to silence all messages.\n *\n * @param {Level} l The new level.\n */\nexport function setLevel(l) {\n level = levels[l];\n}\n\nexport function log(...args) {\n if (level > levels.info) {\n return;\n }\n console.log(...args); // eslint-disable-line no-console\n}\n\nexport function warn(...args) {\n if (level > levels.warn) {\n return;\n }\n console.warn(...args); // eslint-disable-line no-console\n}\n\nexport function error(...args) {\n if (level > levels.error) {\n return;\n }\n console.error(...args); // eslint-disable-line no-console\n}\n","/**\n * @module ol/proj\n */\n\n/**\n * The ol/proj module stores:\n * * a list of {@link module:ol/proj/Projection~Projection}\n * objects, one for each projection supported by the application\n * * a list of transform functions needed to convert coordinates in one projection\n * into another.\n *\n * The static functions are the methods used to maintain these.\n * Each transform function can handle not only simple coordinate pairs, but also\n * large arrays of coordinates such as vector geometries.\n *\n * When loaded, the library adds projection objects for EPSG:4326 (WGS84\n * geographic coordinates) and EPSG:3857 (Web or Spherical Mercator, as used\n * for example by Bing Maps or OpenStreetMap), together with the relevant\n * transform functions.\n *\n * Additional transforms may be added by using the http://proj4js.org/\n * library (version 2.2 or later). You can use the full build supplied by\n * Proj4js, or create a custom build to support those projections you need; see\n * the Proj4js website for how to do this. You also need the Proj4js definitions\n * for the required projections. These definitions can be obtained from\n * https://epsg.io/, and are a JS function, so can be loaded in a script\n * tag (as in the examples) or pasted into your application.\n *\n * After all required projection definitions are added to proj4's registry (by\n * using `proj4.defs()`), simply call `register(proj4)` from the `ol/proj/proj4`\n * package. Existing transforms are not changed by this function. See\n * examples/wms-image-custom-proj for an example of this.\n *\n * Additional projection definitions can be registered with `proj4.defs()` any\n * time. Just make sure to call `register(proj4)` again; for example, with user-supplied data where you don't\n * know in advance what projections are needed, you can initially load minimal\n * support and then load whichever are requested.\n *\n * Note that Proj4js does not support projection extents. If you want to add\n * one for creating default tile grids, you can add it after the Projection\n * object has been created with `setExtent`, for example,\n * `get('EPSG:1234').setExtent(extent)`.\n *\n * In addition to Proj4js support, any transform functions can be added with\n * {@link module:ol/proj.addCoordinateTransforms}. To use this, you must first create\n * a {@link module:ol/proj/Projection~Projection} object for the new projection and add it with\n * {@link module:ol/proj.addProjection}. You can then add the forward and inverse\n * functions with {@link module:ol/proj.addCoordinateTransforms}. See\n * examples/wms-custom-proj for an example of this.\n *\n * Note that if no transforms are needed and you only need to define the\n * projection, just add a {@link module:ol/proj/Projection~Projection} with\n * {@link module:ol/proj.addProjection}. See examples/wms-no-proj for an example of\n * this.\n */\nimport Projection from './proj/Projection.js';\nimport {\n PROJECTIONS as EPSG3857_PROJECTIONS,\n fromEPSG4326,\n toEPSG4326,\n} from './proj/epsg3857.js';\nimport {PROJECTIONS as EPSG4326_PROJECTIONS} from './proj/epsg4326.js';\nimport {METERS_PER_UNIT} from './proj/Units.js';\nimport {\n add as addProj,\n clear as clearProj,\n get as getProj,\n} from './proj/projections.js';\nimport {\n add as addTransformFunc,\n clear as clearTransformFuncs,\n get as getTransformFunc,\n} from './proj/transforms.js';\nimport {applyTransform, getWidth} from './extent.js';\nimport {clamp, modulo} from './math.js';\nimport {equals, getWorldsAway} from './coordinate.js';\nimport {getDistance} from './sphere.js';\nimport {warn} from './console.js';\n\n/**\n * A projection as {@link module:ol/proj/Projection~Projection}, SRS identifier\n * string or undefined.\n * @typedef {Projection|string|undefined} ProjectionLike\n * @api\n */\n\n/**\n * A transform function accepts an array of input coordinate values, an optional\n * output array, and an optional dimension (default should be 2). The function\n * transforms the input coordinate values, populates the output array, and\n * returns the output array.\n *\n * @typedef {function(Array, Array=, number=): Array} TransformFunction\n * @api\n */\n\nexport {METERS_PER_UNIT};\n\nexport {Projection};\n\nlet showCoordinateWarning = true;\n\n/**\n * @param {boolean} [disable = true] Disable console info about `useGeographic()`\n */\nexport function disableCoordinateWarning(disable) {\n const hide = disable === undefined ? true : disable;\n showCoordinateWarning = !hide;\n}\n\n/**\n * @param {Array} input Input coordinate array.\n * @param {Array} [output] Output array of coordinate values.\n * @return {Array} Output coordinate array (new array, same coordinate\n * values).\n */\nexport function cloneTransform(input, output) {\n if (output !== undefined) {\n for (let i = 0, ii = input.length; i < ii; ++i) {\n output[i] = input[i];\n }\n output = output;\n } else {\n output = input.slice();\n }\n return output;\n}\n\n/**\n * @param {Array} input Input coordinate array.\n * @param {Array} [output] Output array of coordinate values.\n * @return {Array} Input coordinate array (same array as input).\n */\nexport function identityTransform(input, output) {\n if (output !== undefined && input !== output) {\n for (let i = 0, ii = input.length; i < ii; ++i) {\n output[i] = input[i];\n }\n input = output;\n }\n return input;\n}\n\n/**\n * Add a Projection object to the list of supported projections that can be\n * looked up by their code.\n *\n * @param {Projection} projection Projection instance.\n * @api\n */\nexport function addProjection(projection) {\n addProj(projection.getCode(), projection);\n addTransformFunc(projection, projection, cloneTransform);\n}\n\n/**\n * @param {Array} projections Projections.\n */\nexport function addProjections(projections) {\n projections.forEach(addProjection);\n}\n\n/**\n * Fetches a Projection object for the code specified.\n *\n * @param {ProjectionLike} projectionLike Either a code string which is\n * a combination of authority and identifier such as \"EPSG:4326\", or an\n * existing projection object, or undefined.\n * @return {Projection|null} Projection object, or null if not in list.\n * @api\n */\nexport function get(projectionLike) {\n return typeof projectionLike === 'string'\n ? getProj(/** @type {string} */ (projectionLike))\n : /** @type {Projection} */ (projectionLike) || null;\n}\n\n/**\n * Get the resolution of the point in degrees or distance units.\n * For projections with degrees as the unit this will simply return the\n * provided resolution. For other projections the point resolution is\n * by default estimated by transforming the `point` pixel to EPSG:4326,\n * measuring its width and height on the normal sphere,\n * and taking the average of the width and height.\n * A custom function can be provided for a specific projection, either\n * by setting the `getPointResolution` option in the\n * {@link module:ol/proj/Projection~Projection} constructor or by using\n * {@link module:ol/proj/Projection~Projection#setGetPointResolution} to change an existing\n * projection object.\n * @param {ProjectionLike} projection The projection.\n * @param {number} resolution Nominal resolution in projection units.\n * @param {import(\"./coordinate.js\").Coordinate} point Point to find adjusted resolution at.\n * @param {import(\"./proj/Units.js\").Units} [units] Units to get the point resolution in.\n * Default is the projection's units.\n * @return {number} Point resolution.\n * @api\n */\nexport function getPointResolution(projection, resolution, point, units) {\n projection = get(projection);\n let pointResolution;\n const getter = projection.getPointResolutionFunc();\n if (getter) {\n pointResolution = getter(resolution, point);\n if (units && units !== projection.getUnits()) {\n const metersPerUnit = projection.getMetersPerUnit();\n if (metersPerUnit) {\n pointResolution =\n (pointResolution * metersPerUnit) / METERS_PER_UNIT[units];\n }\n }\n } else {\n const projUnits = projection.getUnits();\n if ((projUnits == 'degrees' && !units) || units == 'degrees') {\n pointResolution = resolution;\n } else {\n // Estimate point resolution by transforming the center pixel to EPSG:4326,\n // measuring its width and height on the normal sphere, and taking the\n // average of the width and height.\n const toEPSG4326 = getTransformFromProjections(\n projection,\n get('EPSG:4326')\n );\n if (toEPSG4326 === identityTransform && projUnits !== 'degrees') {\n // no transform is available\n pointResolution = resolution * projection.getMetersPerUnit();\n } else {\n let vertices = [\n point[0] - resolution / 2,\n point[1],\n point[0] + resolution / 2,\n point[1],\n point[0],\n point[1] - resolution / 2,\n point[0],\n point[1] + resolution / 2,\n ];\n vertices = toEPSG4326(vertices, vertices, 2);\n const width = getDistance(vertices.slice(0, 2), vertices.slice(2, 4));\n const height = getDistance(vertices.slice(4, 6), vertices.slice(6, 8));\n pointResolution = (width + height) / 2;\n }\n const metersPerUnit = units\n ? METERS_PER_UNIT[units]\n : projection.getMetersPerUnit();\n if (metersPerUnit !== undefined) {\n pointResolution /= metersPerUnit;\n }\n }\n }\n return pointResolution;\n}\n\n/**\n * Registers transformation functions that don't alter coordinates. Those allow\n * to transform between projections with equal meaning.\n *\n * @param {Array} projections Projections.\n * @api\n */\nexport function addEquivalentProjections(projections) {\n addProjections(projections);\n projections.forEach(function (source) {\n projections.forEach(function (destination) {\n if (source !== destination) {\n addTransformFunc(source, destination, cloneTransform);\n }\n });\n });\n}\n\n/**\n * Registers transformation functions to convert coordinates in any projection\n * in projection1 to any projection in projection2.\n *\n * @param {Array} projections1 Projections with equal\n * meaning.\n * @param {Array} projections2 Projections with equal\n * meaning.\n * @param {TransformFunction} forwardTransform Transformation from any\n * projection in projection1 to any projection in projection2.\n * @param {TransformFunction} inverseTransform Transform from any projection\n * in projection2 to any projection in projection1..\n */\nexport function addEquivalentTransforms(\n projections1,\n projections2,\n forwardTransform,\n inverseTransform\n) {\n projections1.forEach(function (projection1) {\n projections2.forEach(function (projection2) {\n addTransformFunc(projection1, projection2, forwardTransform);\n addTransformFunc(projection2, projection1, inverseTransform);\n });\n });\n}\n\n/**\n * Clear all cached projections and transforms.\n */\nexport function clearAllProjections() {\n clearProj();\n clearTransformFuncs();\n}\n\n/**\n * @param {Projection|string|undefined} projection Projection.\n * @param {string} defaultCode Default code.\n * @return {Projection} Projection.\n */\nexport function createProjection(projection, defaultCode) {\n if (!projection) {\n return get(defaultCode);\n }\n if (typeof projection === 'string') {\n return get(projection);\n }\n return /** @type {Projection} */ (projection);\n}\n\n/**\n * Creates a {@link module:ol/proj~TransformFunction} from a simple 2D coordinate transform\n * function.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} coordTransform Coordinate\n * transform.\n * @return {TransformFunction} Transform function.\n */\nexport function createTransformFromCoordinateTransform(coordTransform) {\n return (\n /**\n * @param {Array} input Input.\n * @param {Array} [output] Output.\n * @param {number} [dimension] Dimension.\n * @return {Array} Output.\n */\n function (input, output, dimension) {\n const length = input.length;\n dimension = dimension !== undefined ? dimension : 2;\n output = output !== undefined ? output : new Array(length);\n for (let i = 0; i < length; i += dimension) {\n const point = coordTransform(input.slice(i, i + dimension));\n const pointLength = point.length;\n for (let j = 0, jj = dimension; j < jj; ++j) {\n output[i + j] = j >= pointLength ? input[i + j] : point[j];\n }\n }\n return output;\n }\n );\n}\n\n/**\n * Registers coordinate transform functions to convert coordinates between the\n * source projection and the destination projection.\n * The forward and inverse functions convert coordinate pairs; this function\n * converts these into the functions used internally which also handle\n * extents and coordinate arrays.\n *\n * @param {ProjectionLike} source Source projection.\n * @param {ProjectionLike} destination Destination projection.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} forward The forward transform\n * function (that is, from the source projection to the destination\n * projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns\n * the transformed {@link module:ol/coordinate~Coordinate}.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} inverse The inverse transform\n * function (that is, from the destination projection to the source\n * projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns\n * the transformed {@link module:ol/coordinate~Coordinate}. If the transform function can only\n * transform less dimensions than the input coordinate, it is supposeed to return a coordinate\n * with only the length it can transform. The other dimensions will be taken unchanged from the\n * source.\n * @api\n */\nexport function addCoordinateTransforms(source, destination, forward, inverse) {\n const sourceProj = get(source);\n const destProj = get(destination);\n addTransformFunc(\n sourceProj,\n destProj,\n createTransformFromCoordinateTransform(forward)\n );\n addTransformFunc(\n destProj,\n sourceProj,\n createTransformFromCoordinateTransform(inverse)\n );\n}\n\n/**\n * Transforms a coordinate from longitude/latitude to a different projection.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate as longitude and latitude, i.e.\n * an array with longitude as 1st and latitude as 2nd element.\n * @param {ProjectionLike} [projection] Target projection. The\n * default is Web Mercator, i.e. 'EPSG:3857'.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate projected to the target projection.\n * @api\n */\nexport function fromLonLat(coordinate, projection) {\n disableCoordinateWarning();\n return transform(\n coordinate,\n 'EPSG:4326',\n projection !== undefined ? projection : 'EPSG:3857'\n );\n}\n\n/**\n * Transforms a coordinate to longitude/latitude.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Projected coordinate.\n * @param {ProjectionLike} [projection] Projection of the coordinate.\n * The default is Web Mercator, i.e. 'EPSG:3857'.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate as longitude and latitude, i.e. an array\n * with longitude as 1st and latitude as 2nd element.\n * @api\n */\nexport function toLonLat(coordinate, projection) {\n const lonLat = transform(\n coordinate,\n projection !== undefined ? projection : 'EPSG:3857',\n 'EPSG:4326'\n );\n const lon = lonLat[0];\n if (lon < -180 || lon > 180) {\n lonLat[0] = modulo(lon + 180, 360) - 180;\n }\n return lonLat;\n}\n\n/**\n * Checks if two projections are the same, that is every coordinate in one\n * projection does represent the same geographic point as the same coordinate in\n * the other projection.\n *\n * @param {Projection} projection1 Projection 1.\n * @param {Projection} projection2 Projection 2.\n * @return {boolean} Equivalent.\n * @api\n */\nexport function equivalent(projection1, projection2) {\n if (projection1 === projection2) {\n return true;\n }\n const equalUnits = projection1.getUnits() === projection2.getUnits();\n if (projection1.getCode() === projection2.getCode()) {\n return equalUnits;\n }\n const transformFunc = getTransformFromProjections(projection1, projection2);\n return transformFunc === cloneTransform && equalUnits;\n}\n\n/**\n * Searches in the list of transform functions for the function for converting\n * coordinates from the source projection to the destination projection.\n *\n * @param {Projection} sourceProjection Source Projection object.\n * @param {Projection} destinationProjection Destination Projection\n * object.\n * @return {TransformFunction} Transform function.\n */\nexport function getTransformFromProjections(\n sourceProjection,\n destinationProjection\n) {\n const sourceCode = sourceProjection.getCode();\n const destinationCode = destinationProjection.getCode();\n let transformFunc = getTransformFunc(sourceCode, destinationCode);\n if (!transformFunc) {\n transformFunc = identityTransform;\n }\n return transformFunc;\n}\n\n/**\n * Given the projection-like objects, searches for a transformation\n * function to convert a coordinates array from the source projection to the\n * destination projection.\n *\n * @param {ProjectionLike} source Source.\n * @param {ProjectionLike} destination Destination.\n * @return {TransformFunction} Transform function.\n * @api\n */\nexport function getTransform(source, destination) {\n const sourceProjection = get(source);\n const destinationProjection = get(destination);\n return getTransformFromProjections(sourceProjection, destinationProjection);\n}\n\n/**\n * Transforms a coordinate from source projection to destination projection.\n * This returns a new coordinate (and does not modify the original).\n *\n * See {@link module:ol/proj.transformExtent} for extent transformation.\n * See the transform method of {@link module:ol/geom/Geometry~Geometry} and its\n * subclasses for geometry transforms.\n *\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {ProjectionLike} source Source projection-like.\n * @param {ProjectionLike} destination Destination projection-like.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n * @api\n */\nexport function transform(coordinate, source, destination) {\n const transformFunc = getTransform(source, destination);\n return transformFunc(coordinate, undefined, coordinate.length);\n}\n\n/**\n * Transforms an extent from source projection to destination projection. This\n * returns a new extent (and does not modify the original).\n *\n * @param {import(\"./extent.js\").Extent} extent The extent to transform.\n * @param {ProjectionLike} source Source projection-like.\n * @param {ProjectionLike} destination Destination projection-like.\n * @param {number} [stops] Number of stops per side used for the transform.\n * By default only the corners are used.\n * @return {import(\"./extent.js\").Extent} The transformed extent.\n * @api\n */\nexport function transformExtent(extent, source, destination, stops) {\n const transformFunc = getTransform(source, destination);\n return applyTransform(extent, transformFunc, undefined, stops);\n}\n\n/**\n * Transforms the given point to the destination projection.\n *\n * @param {import(\"./coordinate.js\").Coordinate} point Point.\n * @param {Projection} sourceProjection Source projection.\n * @param {Projection} destinationProjection Destination projection.\n * @return {import(\"./coordinate.js\").Coordinate} Point.\n */\nexport function transformWithProjections(\n point,\n sourceProjection,\n destinationProjection\n) {\n const transformFunc = getTransformFromProjections(\n sourceProjection,\n destinationProjection\n );\n return transformFunc(point);\n}\n\n/**\n * @type {Projection|null}\n */\nlet userProjection = null;\n\n/**\n * Set the projection for coordinates supplied from and returned by API methods.\n * This includes all API methods except for those interacting with tile grids,\n * plus {@link import(\"./Map.js\").FrameState} and {@link import(\"./View.js\").State}.\n * @param {ProjectionLike} projection The user projection.\n * @api\n */\nexport function setUserProjection(projection) {\n userProjection = get(projection);\n}\n\n/**\n * Clear the user projection if set.\n * @api\n */\nexport function clearUserProjection() {\n userProjection = null;\n}\n\n/**\n * Get the projection for coordinates supplied from and returned by API methods.\n * @return {Projection|null} The user projection (or null if not set).\n * @api\n */\nexport function getUserProjection() {\n return userProjection;\n}\n\n/**\n * Use geographic coordinates (WGS-84 datum) in API methods.\n * This includes all API methods except for those interacting with tile grids,\n * plus {@link import(\"./Map.js\").FrameState} and {@link import(\"./View.js\").State}.\n * @api\n */\nexport function useGeographic() {\n setUserProjection('EPSG:4326');\n}\n\n/**\n * Return a coordinate transformed into the user projection. If no user projection\n * is set, the original coordinate is returned.\n * @param {Array} coordinate Input coordinate.\n * @param {ProjectionLike} sourceProjection The input coordinate projection.\n * @return {Array} The input coordinate in the user projection.\n */\nexport function toUserCoordinate(coordinate, sourceProjection) {\n if (!userProjection) {\n return coordinate;\n }\n return transform(coordinate, sourceProjection, userProjection);\n}\n\n/**\n * Return a coordinate transformed from the user projection. If no user projection\n * is set, the original coordinate is returned.\n * @param {Array} coordinate Input coordinate.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {Array} The input coordinate transformed.\n */\nexport function fromUserCoordinate(coordinate, destProjection) {\n if (!userProjection) {\n if (\n showCoordinateWarning &&\n !equals(coordinate, [0, 0]) &&\n coordinate[0] >= -180 &&\n coordinate[0] <= 180 &&\n coordinate[1] >= -90 &&\n coordinate[1] <= 90\n ) {\n showCoordinateWarning = false;\n warn(\n 'Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.'\n );\n }\n return coordinate;\n }\n return transform(coordinate, userProjection, destProjection);\n}\n\n/**\n * Return an extent transformed into the user projection. If no user projection\n * is set, the original extent is returned.\n * @param {import(\"./extent.js\").Extent} extent Input extent.\n * @param {ProjectionLike} sourceProjection The input extent projection.\n * @return {import(\"./extent.js\").Extent} The input extent in the user projection.\n */\nexport function toUserExtent(extent, sourceProjection) {\n if (!userProjection) {\n return extent;\n }\n return transformExtent(extent, sourceProjection, userProjection);\n}\n\n/**\n * Return an extent transformed from the user projection. If no user projection\n * is set, the original extent is returned.\n * @param {import(\"./extent.js\").Extent} extent Input extent.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {import(\"./extent.js\").Extent} The input extent transformed.\n */\nexport function fromUserExtent(extent, destProjection) {\n if (!userProjection) {\n return extent;\n }\n return transformExtent(extent, userProjection, destProjection);\n}\n\n/**\n * Return the resolution in user projection units per pixel. If no user projection\n * is set, or source or user projection are missing units, the original resolution\n * is returned.\n * @param {number} resolution Resolution in input projection units per pixel.\n * @param {ProjectionLike} sourceProjection The input projection.\n * @return {number} Resolution in user projection units per pixel.\n */\nexport function toUserResolution(resolution, sourceProjection) {\n if (!userProjection) {\n return resolution;\n }\n const sourceUnits = get(sourceProjection).getUnits();\n const userUnits = userProjection.getUnits();\n return sourceUnits && userUnits\n ? (resolution * METERS_PER_UNIT[sourceUnits]) / METERS_PER_UNIT[userUnits]\n : resolution;\n}\n\n/**\n * Return the resolution in user projection units per pixel. If no user projection\n * is set, or source or user projection are missing units, the original resolution\n * is returned.\n * @param {number} resolution Resolution in user projection units per pixel.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {number} Resolution in destination projection units per pixel.\n */\nexport function fromUserResolution(resolution, destProjection) {\n if (!userProjection) {\n return resolution;\n }\n const sourceUnits = get(destProjection).getUnits();\n const userUnits = userProjection.getUnits();\n return sourceUnits && userUnits\n ? (resolution * METERS_PER_UNIT[userUnits]) / METERS_PER_UNIT[sourceUnits]\n : resolution;\n}\n\n/**\n * Creates a safe coordinate transform function from a coordinate transform function.\n * \"Safe\" means that it can handle wrapping of x-coordinates for global projections,\n * and that coordinates exceeding the source projection validity extent's range will be\n * clamped to the validity range.\n * @param {Projection} sourceProj Source projection.\n * @param {Projection} destProj Destination projection.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} transform Transform function (source to destination).\n * @return {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} Safe transform function (source to destination).\n */\nexport function createSafeCoordinateTransform(sourceProj, destProj, transform) {\n return function (coord) {\n let transformed, worldsAway;\n if (sourceProj.canWrapX()) {\n const sourceExtent = sourceProj.getExtent();\n const sourceExtentWidth = getWidth(sourceExtent);\n coord = coord.slice(0);\n worldsAway = getWorldsAway(coord, sourceProj, sourceExtentWidth);\n if (worldsAway) {\n // Move x to the real world\n coord[0] = coord[0] - worldsAway * sourceExtentWidth;\n }\n coord[0] = clamp(coord[0], sourceExtent[0], sourceExtent[2]);\n coord[1] = clamp(coord[1], sourceExtent[1], sourceExtent[3]);\n transformed = transform(coord);\n } else {\n transformed = transform(coord);\n }\n if (worldsAway && destProj.canWrapX()) {\n // Move transformed coordinate back to the offset world\n transformed[0] += worldsAway * getWidth(destProj.getExtent());\n }\n return transformed;\n };\n}\n\n/**\n * Add transforms to and from EPSG:4326 and EPSG:3857. This function is called\n * by when this module is executed and should only need to be called again after\n * `clearAllProjections()` is called (e.g. in tests).\n */\nexport function addCommon() {\n // Add transformations that don't alter coordinates to convert within set of\n // projections with equal meaning.\n addEquivalentProjections(EPSG3857_PROJECTIONS);\n addEquivalentProjections(EPSG4326_PROJECTIONS);\n // Add transformations to convert EPSG:4326 like coordinates to EPSG:3857 like\n // coordinates and back.\n addEquivalentTransforms(\n EPSG4326_PROJECTIONS,\n EPSG3857_PROJECTIONS,\n fromEPSG4326,\n toEPSG4326\n );\n}\n\naddCommon();\n","/**\n * @module ol/centerconstraint\n */\nimport {clamp} from './math.js';\n\n/**\n * @typedef {function((import(\"./coordinate.js\").Coordinate|undefined), number, import(\"./size.js\").Size, boolean=, Array=): (import(\"./coordinate.js\").Coordinate|undefined)} Type\n */\n\n/**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {boolean} onlyCenter If true, the constraint will only apply to the view center.\n * @param {boolean} smooth If true, the view will be able to go slightly out of the given extent\n * (only during interaction and animation).\n * @return {Type} The constraint.\n */\nexport function createExtent(extent, onlyCenter, smooth) {\n return (\n /**\n * @param {import(\"./coordinate.js\").Coordinate|undefined} center Center.\n * @param {number|undefined} resolution Resolution.\n * @param {import(\"./size.js\").Size} size Viewport size; unused if `onlyCenter` was specified.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @param {Array} [centerShift] Shift between map center and viewport center.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center.\n */\n function (center, resolution, size, isMoving, centerShift) {\n if (!center) {\n return undefined;\n }\n if (!resolution && !onlyCenter) {\n return center;\n }\n const viewWidth = onlyCenter ? 0 : size[0] * resolution;\n const viewHeight = onlyCenter ? 0 : size[1] * resolution;\n const shiftX = centerShift ? centerShift[0] : 0;\n const shiftY = centerShift ? centerShift[1] : 0;\n let minX = extent[0] + viewWidth / 2 + shiftX;\n let maxX = extent[2] - viewWidth / 2 + shiftX;\n let minY = extent[1] + viewHeight / 2 + shiftY;\n let maxY = extent[3] - viewHeight / 2 + shiftY;\n\n // note: when zooming out of bounds, min and max values for x and y may\n // end up inverted (min > max); this has to be accounted for\n if (minX > maxX) {\n minX = (maxX + minX) / 2;\n maxX = minX;\n }\n if (minY > maxY) {\n minY = (maxY + minY) / 2;\n maxY = minY;\n }\n\n let x = clamp(center[0], minX, maxX);\n let y = clamp(center[1], minY, maxY);\n\n // during an interaction, allow some overscroll\n if (isMoving && smooth && resolution) {\n const ratio = 30 * resolution;\n x +=\n -ratio * Math.log(1 + Math.max(0, minX - center[0]) / ratio) +\n ratio * Math.log(1 + Math.max(0, center[0] - maxX) / ratio);\n y +=\n -ratio * Math.log(1 + Math.max(0, minY - center[1]) / ratio) +\n ratio * Math.log(1 + Math.max(0, center[1] - maxY) / ratio);\n }\n\n return [x, y];\n }\n );\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} [center] Center.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center.\n */\nexport function none(center) {\n return center;\n}\n","/**\n * @module ol/resolutionconstraint\n */\nimport {clamp} from './math.js';\nimport {getHeight, getWidth} from './extent.js';\nimport {linearFindNearest} from './array.js';\n\n/**\n * @typedef {function((number|undefined), number, import(\"./size.js\").Size, boolean=): (number|undefined)} Type\n */\n\n/**\n * Returns a modified resolution taking into account the viewport size and maximum\n * allowed extent.\n * @param {number} resolution Resolution\n * @param {import(\"./extent.js\").Extent} maxExtent Maximum allowed extent.\n * @param {import(\"./size.js\").Size} viewportSize Viewport size.\n * @param {boolean} showFullExtent Whether to show the full extent.\n * @return {number} Capped resolution.\n */\nfunction getViewportClampedResolution(\n resolution,\n maxExtent,\n viewportSize,\n showFullExtent\n) {\n const xResolution = getWidth(maxExtent) / viewportSize[0];\n const yResolution = getHeight(maxExtent) / viewportSize[1];\n\n if (showFullExtent) {\n return Math.min(resolution, Math.max(xResolution, yResolution));\n }\n return Math.min(resolution, Math.min(xResolution, yResolution));\n}\n\n/**\n * Returns a modified resolution to be between maxResolution and minResolution while\n * still allowing the value to be slightly out of bounds.\n * Note: the computation is based on the logarithm function (ln):\n * - at 1, ln(x) is 0\n * - above 1, ln(x) keeps increasing but at a much slower pace than x\n * The final result is clamped to prevent getting too far away from bounds.\n * @param {number} resolution Resolution.\n * @param {number} maxResolution Max resolution.\n * @param {number} minResolution Min resolution.\n * @return {number} Smoothed resolution.\n */\nfunction getSmoothClampedResolution(resolution, maxResolution, minResolution) {\n let result = Math.min(resolution, maxResolution);\n const ratio = 50;\n\n result *=\n Math.log(1 + ratio * Math.max(0, resolution / maxResolution - 1)) / ratio +\n 1;\n if (minResolution) {\n result = Math.max(result, minResolution);\n result /=\n Math.log(1 + ratio * Math.max(0, minResolution / resolution - 1)) /\n ratio +\n 1;\n }\n return clamp(result, minResolution / 2, maxResolution * 2);\n}\n\n/**\n * @param {Array} resolutions Resolutions.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createSnapToResolutions(\n resolutions,\n smooth,\n maxExtent,\n showFullExtent\n) {\n smooth = smooth !== undefined ? smooth : true;\n return (\n /**\n * @param {number|undefined} resolution Resolution.\n * @param {number} direction Direction.\n * @param {import(\"./size.js\").Size} size Viewport size.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Resolution.\n */\n function (resolution, direction, size, isMoving) {\n if (resolution !== undefined) {\n const maxResolution = resolutions[0];\n const minResolution = resolutions[resolutions.length - 1];\n const cappedMaxRes = maxExtent\n ? getViewportClampedResolution(\n maxResolution,\n maxExtent,\n size,\n showFullExtent\n )\n : maxResolution;\n\n // during interacting or animating, allow intermediary values\n if (isMoving) {\n if (!smooth) {\n return clamp(resolution, minResolution, cappedMaxRes);\n }\n return getSmoothClampedResolution(\n resolution,\n cappedMaxRes,\n minResolution\n );\n }\n\n const capped = Math.min(cappedMaxRes, resolution);\n const z = Math.floor(linearFindNearest(resolutions, capped, direction));\n if (resolutions[z] > cappedMaxRes && z < resolutions.length - 1) {\n return resolutions[z + 1];\n }\n return resolutions[z];\n }\n return undefined;\n }\n );\n}\n\n/**\n * @param {number} power Power.\n * @param {number} maxResolution Maximum resolution.\n * @param {number} [minResolution] Minimum resolution.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createSnapToPower(\n power,\n maxResolution,\n minResolution,\n smooth,\n maxExtent,\n showFullExtent\n) {\n smooth = smooth !== undefined ? smooth : true;\n minResolution = minResolution !== undefined ? minResolution : 0;\n\n return (\n /**\n * @param {number|undefined} resolution Resolution.\n * @param {number} direction Direction.\n * @param {import(\"./size.js\").Size} size Viewport size.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Resolution.\n */\n function (resolution, direction, size, isMoving) {\n if (resolution !== undefined) {\n const cappedMaxRes = maxExtent\n ? getViewportClampedResolution(\n maxResolution,\n maxExtent,\n size,\n showFullExtent\n )\n : maxResolution;\n\n // during interacting or animating, allow intermediary values\n if (isMoving) {\n if (!smooth) {\n return clamp(resolution, minResolution, cappedMaxRes);\n }\n return getSmoothClampedResolution(\n resolution,\n cappedMaxRes,\n minResolution\n );\n }\n\n const tolerance = 1e-9;\n const minZoomLevel = Math.ceil(\n Math.log(maxResolution / cappedMaxRes) / Math.log(power) - tolerance\n );\n const offset = -direction * (0.5 - tolerance) + 0.5;\n const capped = Math.min(cappedMaxRes, resolution);\n const cappedZoomLevel = Math.floor(\n Math.log(maxResolution / capped) / Math.log(power) + offset\n );\n const zoomLevel = Math.max(minZoomLevel, cappedZoomLevel);\n const newResolution = maxResolution / Math.pow(power, zoomLevel);\n return clamp(newResolution, minResolution, cappedMaxRes);\n }\n return undefined;\n }\n );\n}\n\n/**\n * @param {number} maxResolution Max resolution.\n * @param {number} minResolution Min resolution.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createMinMaxResolution(\n maxResolution,\n minResolution,\n smooth,\n maxExtent,\n showFullExtent\n) {\n smooth = smooth !== undefined ? smooth : true;\n\n return (\n /**\n * @param {number|undefined} resolution Resolution.\n * @param {number} direction Direction.\n * @param {import(\"./size.js\").Size} size Viewport size.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Resolution.\n */\n function (resolution, direction, size, isMoving) {\n if (resolution !== undefined) {\n const cappedMaxRes = maxExtent\n ? getViewportClampedResolution(\n maxResolution,\n maxExtent,\n size,\n showFullExtent\n )\n : maxResolution;\n\n if (!smooth || !isMoving) {\n return clamp(resolution, minResolution, cappedMaxRes);\n }\n return getSmoothClampedResolution(\n resolution,\n cappedMaxRes,\n minResolution\n );\n }\n return undefined;\n }\n );\n}\n","/**\n * @module ol/rotationconstraint\n */\nimport {toRadians} from './math.js';\n\n/**\n * @typedef {function((number|undefined), boolean=): (number|undefined)} Type\n */\n\n/**\n * @param {number|undefined} rotation Rotation.\n * @return {number|undefined} Rotation.\n */\nexport function disable(rotation) {\n if (rotation !== undefined) {\n return 0;\n }\n return undefined;\n}\n\n/**\n * @param {number|undefined} rotation Rotation.\n * @return {number|undefined} Rotation.\n */\nexport function none(rotation) {\n if (rotation !== undefined) {\n return rotation;\n }\n return undefined;\n}\n\n/**\n * @param {number} n N.\n * @return {Type} Rotation constraint.\n */\nexport function createSnapToN(n) {\n const theta = (2 * Math.PI) / n;\n return (\n /**\n * @param {number|undefined} rotation Rotation.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Rotation.\n */\n function (rotation, isMoving) {\n if (isMoving) {\n return rotation;\n }\n\n if (rotation !== undefined) {\n rotation = Math.floor(rotation / theta + 0.5) * theta;\n return rotation;\n }\n return undefined;\n }\n );\n}\n\n/**\n * @param {number} [tolerance] Tolerance.\n * @return {Type} Rotation constraint.\n */\nexport function createSnapToZero(tolerance) {\n tolerance = tolerance || toRadians(5);\n return (\n /**\n * @param {number|undefined} rotation Rotation.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Rotation.\n */\n function (rotation, isMoving) {\n if (isMoving) {\n return rotation;\n }\n\n if (rotation !== undefined) {\n if (Math.abs(rotation) <= tolerance) {\n return 0;\n }\n return rotation;\n }\n return undefined;\n }\n );\n}\n","/**\n * @module ol/easing\n */\n\n/**\n * Start slow and speed up.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function easeIn(t) {\n return Math.pow(t, 3);\n}\n\n/**\n * Start fast and slow down.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function easeOut(t) {\n return 1 - easeIn(1 - t);\n}\n\n/**\n * Start slow, speed up, and then slow down again.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function inAndOut(t) {\n return 3 * t * t - 2 * t * t * t;\n}\n\n/**\n * Maintain a constant speed over time.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function linear(t) {\n return t;\n}\n\n/**\n * Start slow, speed up, and at the very end slow down again. This has the\n * same general behavior as {@link module:ol/easing.inAndOut}, but the final\n * slowdown is delayed.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function upAndDown(t) {\n if (t < 0.5) {\n return inAndOut(2 * t);\n }\n return 1 - inAndOut(2 * (t - 0.5));\n}\n","/**\n * @module ol/geom/flat/transform\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../transform.js\").Transform} transform Transform.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function transform2D(\n flatCoordinates,\n offset,\n end,\n stride,\n transform,\n dest\n) {\n dest = dest ? dest : [];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n const x = flatCoordinates[j];\n const y = flatCoordinates[j + 1];\n dest[i++] = transform[0] * x + transform[2] * y + transform[4];\n dest[i++] = transform[1] * x + transform[3] * y + transform[5];\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} angle Angle.\n * @param {Array} anchor Rotation anchor point.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function rotate(\n flatCoordinates,\n offset,\n end,\n stride,\n angle,\n anchor,\n dest\n) {\n dest = dest ? dest : [];\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const anchorX = anchor[0];\n const anchorY = anchor[1];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n const deltaX = flatCoordinates[j] - anchorX;\n const deltaY = flatCoordinates[j + 1] - anchorY;\n dest[i++] = anchorX + deltaX * cos - deltaY * sin;\n dest[i++] = anchorY + deltaX * sin + deltaY * cos;\n for (let k = j + 2; k < j + stride; ++k) {\n dest[i++] = flatCoordinates[k];\n }\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n\n/**\n * Scale the coordinates.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} sx Scale factor in the x-direction.\n * @param {number} sy Scale factor in the y-direction.\n * @param {Array} anchor Scale anchor point.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function scale(\n flatCoordinates,\n offset,\n end,\n stride,\n sx,\n sy,\n anchor,\n dest\n) {\n dest = dest ? dest : [];\n const anchorX = anchor[0];\n const anchorY = anchor[1];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n const deltaX = flatCoordinates[j] - anchorX;\n const deltaY = flatCoordinates[j + 1] - anchorY;\n dest[i++] = anchorX + sx * deltaX;\n dest[i++] = anchorY + sy * deltaY;\n for (let k = j + 2; k < j + stride; ++k) {\n dest[i++] = flatCoordinates[k];\n }\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} deltaX Delta X.\n * @param {number} deltaY Delta Y.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function translate(\n flatCoordinates,\n offset,\n end,\n stride,\n deltaX,\n deltaY,\n dest\n) {\n dest = dest ? dest : [];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n dest[i++] = flatCoordinates[j] + deltaX;\n dest[i++] = flatCoordinates[j + 1] + deltaY;\n for (let k = j + 2; k < j + stride; ++k) {\n dest[i++] = flatCoordinates[k];\n }\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n","/**\n * @module ol/geom/Geometry\n */\nimport BaseObject from '../Object.js';\nimport {abstract} from '../util.js';\nimport {\n compose as composeTransform,\n create as createTransform,\n} from '../transform.js';\nimport {\n createEmpty,\n createOrUpdateEmpty,\n getHeight,\n returnOrUpdate,\n} from '../extent.js';\nimport {get as getProjection, getTransform} from '../proj.js';\nimport {memoizeOne} from '../functions.js';\nimport {transform2D} from './flat/transform.js';\n\n/**\n * @typedef {'XY' | 'XYZ' | 'XYM' | 'XYZM'} GeometryLayout\n * The coordinate layout for geometries, indicating whether a 3rd or 4th z ('Z')\n * or measure ('M') coordinate is available.\n */\n\n/**\n * @typedef {'Point' | 'LineString' | 'LinearRing' | 'Polygon' | 'MultiPoint' | 'MultiLineString' | 'MultiPolygon' | 'GeometryCollection' | 'Circle'} Type\n * The geometry type. One of `'Point'`, `'LineString'`, `'LinearRing'`,\n * `'Polygon'`, `'MultiPoint'`, `'MultiLineString'`, `'MultiPolygon'`,\n * `'GeometryCollection'`, or `'Circle'`.\n */\n\n/**\n * @type {import(\"../transform.js\").Transform}\n */\nconst tmpTransform = createTransform();\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for vector geometries.\n *\n * To get notified of changes to the geometry, register a listener for the\n * generic `change` event on your geometry instance.\n *\n * @abstract\n * @api\n */\nclass Geometry extends BaseObject {\n constructor() {\n super();\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.extent_ = createEmpty();\n\n /**\n * @private\n * @type {number}\n */\n this.extentRevision_ = -1;\n\n /**\n * @protected\n * @type {number}\n */\n this.simplifiedGeometryMaxMinSquaredTolerance = 0;\n\n /**\n * @protected\n * @type {number}\n */\n this.simplifiedGeometryRevision = 0;\n\n /**\n * Get a transformed and simplified version of the geometry.\n * @abstract\n * @param {number} revision The geometry revision.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n * @return {Geometry} Simplified geometry.\n */\n this.simplifyTransformedInternal = memoizeOne(function (\n revision,\n squaredTolerance,\n transform\n ) {\n if (!transform) {\n return this.getSimplifiedGeometry(squaredTolerance);\n }\n const clone = this.clone();\n clone.applyTransform(transform);\n return clone.getSimplifiedGeometry(squaredTolerance);\n });\n }\n\n /**\n * Get a transformed and simplified version of the geometry.\n * @abstract\n * @param {number} squaredTolerance Squared tolerance.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n * @return {Geometry} Simplified geometry.\n */\n simplifyTransformed(squaredTolerance, transform) {\n return this.simplifyTransformedInternal(\n this.getRevision(),\n squaredTolerance,\n transform\n );\n }\n\n /**\n * Make a complete copy of the geometry.\n * @abstract\n * @return {!Geometry} Clone.\n */\n clone() {\n return abstract();\n }\n\n /**\n * @abstract\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n return abstract();\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\n containsXY(x, y) {\n const coord = this.getClosestPoint([x, y]);\n return coord[0] === x && coord[1] === y;\n }\n\n /**\n * Return the closest point of the geometry to the passed point as\n * {@link module:ol/coordinate~Coordinate coordinate}.\n * @param {import(\"../coordinate.js\").Coordinate} point Point.\n * @param {import(\"../coordinate.js\").Coordinate} [closestPoint] Closest point.\n * @return {import(\"../coordinate.js\").Coordinate} Closest point.\n * @api\n */\n getClosestPoint(point, closestPoint) {\n closestPoint = closestPoint ? closestPoint : [NaN, NaN];\n this.closestPointXY(point[0], point[1], closestPoint, Infinity);\n return closestPoint;\n }\n\n /**\n * Returns true if this geometry includes the specified coordinate. If the\n * coordinate is on the boundary of the geometry, returns false.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {boolean} Contains coordinate.\n * @api\n */\n intersectsCoordinate(coordinate) {\n return this.containsXY(coordinate[0], coordinate[1]);\n }\n\n /**\n * @abstract\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @protected\n * @return {import(\"../extent.js\").Extent} extent Extent.\n */\n computeExtent(extent) {\n return abstract();\n }\n\n /**\n * Get the extent of the geometry.\n * @param {import(\"../extent.js\").Extent} [extent] Extent.\n * @return {import(\"../extent.js\").Extent} extent Extent.\n * @api\n */\n getExtent(extent) {\n if (this.extentRevision_ != this.getRevision()) {\n const extent = this.computeExtent(this.extent_);\n if (isNaN(extent[0]) || isNaN(extent[1])) {\n createOrUpdateEmpty(extent);\n }\n this.extentRevision_ = this.getRevision();\n }\n return returnOrUpdate(this.extent_, extent);\n }\n\n /**\n * Rotate the geometry around a given coordinate. This modifies the geometry\n * coordinates in place.\n * @abstract\n * @param {number} angle Rotation angle in radians.\n * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n * @api\n */\n rotate(angle, anchor) {\n abstract();\n }\n\n /**\n * Scale the geometry (with an optional origin). This modifies the geometry\n * coordinates in place.\n * @abstract\n * @param {number} sx The scaling factor in the x-direction.\n * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).\n * @param {import(\"../coordinate.js\").Coordinate} [anchor] The scale origin (defaults to the center\n * of the geometry extent).\n * @api\n */\n scale(sx, sy, anchor) {\n abstract();\n }\n\n /**\n * Create a simplified version of this geometry. For linestrings, this uses\n * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)\n * algorithm. For polygons, a quantization-based\n * simplification is used to preserve topology.\n * @param {number} tolerance The tolerance distance for simplification.\n * @return {Geometry} A new, simplified version of the original geometry.\n * @api\n */\n simplify(tolerance) {\n return this.getSimplifiedGeometry(tolerance * tolerance);\n }\n\n /**\n * Create a simplified version of this geometry using the Douglas Peucker\n * algorithm.\n * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm.\n * @abstract\n * @param {number} squaredTolerance Squared tolerance.\n * @return {Geometry} Simplified geometry.\n */\n getSimplifiedGeometry(squaredTolerance) {\n return abstract();\n }\n\n /**\n * Get the type of this geometry.\n * @abstract\n * @return {Type} Geometry type.\n */\n getType() {\n return abstract();\n }\n\n /**\n * Apply a transform function to the coordinates of the geometry.\n * The geometry is modified in place.\n * If you do not want the geometry modified in place, first `clone()` it and\n * then use this function on the clone.\n * @abstract\n * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n * Called with a flat array of geometry coordinates.\n */\n applyTransform(transformFn) {\n abstract();\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @abstract\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n */\n intersectsExtent(extent) {\n return abstract();\n }\n\n /**\n * Translate the geometry. This modifies the geometry coordinates in place. If\n * instead you want a new geometry, first `clone()` this geometry.\n * @abstract\n * @param {number} deltaX Delta X.\n * @param {number} deltaY Delta Y.\n * @api\n */\n translate(deltaX, deltaY) {\n abstract();\n }\n\n /**\n * Transform each coordinate of the geometry from one coordinate reference\n * system to another. The geometry is modified in place.\n * For example, a line will be transformed to a line and a circle to a circle.\n * If you do not want the geometry modified in place, first `clone()` it and\n * then use this function on the clone.\n *\n * @param {import(\"../proj.js\").ProjectionLike} source The current projection. Can be a\n * string identifier or a {@link module:ol/proj/Projection~Projection} object.\n * @param {import(\"../proj.js\").ProjectionLike} destination The desired projection. Can be a\n * string identifier or a {@link module:ol/proj/Projection~Projection} object.\n * @return {Geometry} This geometry. Note that original geometry is\n * modified in place.\n * @api\n */\n transform(source, destination) {\n /** @type {import(\"../proj/Projection.js\").default} */\n const sourceProj = getProjection(source);\n const transformFn =\n sourceProj.getUnits() == 'tile-pixels'\n ? function (inCoordinates, outCoordinates, stride) {\n const pixelExtent = sourceProj.getExtent();\n const projectedExtent = sourceProj.getWorldExtent();\n const scale = getHeight(projectedExtent) / getHeight(pixelExtent);\n composeTransform(\n tmpTransform,\n projectedExtent[0],\n projectedExtent[3],\n scale,\n -scale,\n 0,\n 0,\n 0\n );\n transform2D(\n inCoordinates,\n 0,\n inCoordinates.length,\n stride,\n tmpTransform,\n outCoordinates\n );\n return getTransform(sourceProj, destination)(\n inCoordinates,\n outCoordinates,\n stride\n );\n }\n : getTransform(sourceProj, destination);\n this.applyTransform(transformFn);\n return this;\n }\n}\n\nexport default Geometry;\n","/**\n * @module ol/geom/SimpleGeometry\n */\nimport Geometry from './Geometry.js';\nimport {abstract} from '../util.js';\nimport {createOrUpdateFromFlatCoordinates, getCenter} from '../extent.js';\nimport {rotate, scale, transform2D, translate} from './flat/transform.js';\n\n/**\n * @classdesc\n * Abstract base class; only used for creating subclasses; do not instantiate\n * in apps, as cannot be rendered.\n *\n * @abstract\n * @api\n */\nclass SimpleGeometry extends Geometry {\n constructor() {\n super();\n\n /**\n * @protected\n * @type {import(\"./Geometry.js\").GeometryLayout}\n */\n this.layout = 'XY';\n\n /**\n * @protected\n * @type {number}\n */\n this.stride = 2;\n\n /**\n * @protected\n * @type {Array}\n */\n this.flatCoordinates = null;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @protected\n * @return {import(\"../extent.js\").Extent} extent Extent.\n */\n computeExtent(extent) {\n return createOrUpdateFromFlatCoordinates(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n extent\n );\n }\n\n /**\n * @abstract\n * @return {Array<*> | null} Coordinates.\n */\n getCoordinates() {\n return abstract();\n }\n\n /**\n * Return the first coordinate of the geometry.\n * @return {import(\"../coordinate.js\").Coordinate} First coordinate.\n * @api\n */\n getFirstCoordinate() {\n return this.flatCoordinates.slice(0, this.stride);\n }\n\n /**\n * @return {Array} Flat coordinates.\n */\n getFlatCoordinates() {\n return this.flatCoordinates;\n }\n\n /**\n * Return the last coordinate of the geometry.\n * @return {import(\"../coordinate.js\").Coordinate} Last point.\n * @api\n */\n getLastCoordinate() {\n return this.flatCoordinates.slice(\n this.flatCoordinates.length - this.stride\n );\n }\n\n /**\n * Return the {@link import(\"./Geometry.js\").GeometryLayout layout} of the geometry.\n * @return {import(\"./Geometry.js\").GeometryLayout} Layout.\n * @api\n */\n getLayout() {\n return this.layout;\n }\n\n /**\n * Create a simplified version of this geometry using the Douglas Peucker algorithm.\n * @param {number} squaredTolerance Squared tolerance.\n * @return {SimpleGeometry} Simplified geometry.\n */\n getSimplifiedGeometry(squaredTolerance) {\n if (this.simplifiedGeometryRevision !== this.getRevision()) {\n this.simplifiedGeometryMaxMinSquaredTolerance = 0;\n this.simplifiedGeometryRevision = this.getRevision();\n }\n // If squaredTolerance is negative or if we know that simplification will not\n // have any effect then just return this.\n if (\n squaredTolerance < 0 ||\n (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&\n squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance)\n ) {\n return this;\n }\n\n const simplifiedGeometry =\n this.getSimplifiedGeometryInternal(squaredTolerance);\n const simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates();\n if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) {\n return simplifiedGeometry;\n }\n // Simplification did not actually remove any coordinates. We now know\n // that any calls to getSimplifiedGeometry with a squaredTolerance less\n // than or equal to the current squaredTolerance will also not have any\n // effect. This allows us to short circuit simplification (saving CPU\n // cycles) and prevents the cache of simplified geometries from filling\n // up with useless identical copies of this geometry (saving memory).\n this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;\n return this;\n }\n\n /**\n * @param {number} squaredTolerance Squared tolerance.\n * @return {SimpleGeometry} Simplified geometry.\n * @protected\n */\n getSimplifiedGeometryInternal(squaredTolerance) {\n return this;\n }\n\n /**\n * @return {number} Stride.\n */\n getStride() {\n return this.stride;\n }\n\n /**\n * @param {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n * @param {Array} flatCoordinates Flat coordinates.\n */\n setFlatCoordinates(layout, flatCoordinates) {\n this.stride = getStrideForLayout(layout);\n this.layout = layout;\n this.flatCoordinates = flatCoordinates;\n }\n\n /**\n * @abstract\n * @param {!Array<*>} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n */\n setCoordinates(coordinates, layout) {\n abstract();\n }\n\n /**\n * @param {import(\"./Geometry.js\").GeometryLayout|undefined} layout Layout.\n * @param {Array<*>} coordinates Coordinates.\n * @param {number} nesting Nesting.\n * @protected\n */\n setLayout(layout, coordinates, nesting) {\n /** @type {number} */\n let stride;\n if (layout) {\n stride = getStrideForLayout(layout);\n } else {\n for (let i = 0; i < nesting; ++i) {\n if (coordinates.length === 0) {\n this.layout = 'XY';\n this.stride = 2;\n return;\n }\n coordinates = /** @type {Array} */ (coordinates[0]);\n }\n stride = coordinates.length;\n layout = getLayoutForStride(stride);\n }\n this.layout = layout;\n this.stride = stride;\n }\n\n /**\n * Apply a transform function to the coordinates of the geometry.\n * The geometry is modified in place.\n * If you do not want the geometry modified in place, first `clone()` it and\n * then use this function on the clone.\n * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n * Called with a flat array of geometry coordinates.\n * @api\n */\n applyTransform(transformFn) {\n if (this.flatCoordinates) {\n transformFn(this.flatCoordinates, this.flatCoordinates, this.stride);\n this.changed();\n }\n }\n\n /**\n * Rotate the geometry around a given coordinate. This modifies the geometry\n * coordinates in place.\n * @param {number} angle Rotation angle in counter-clockwise radians.\n * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n * @api\n */\n rotate(angle, anchor) {\n const flatCoordinates = this.getFlatCoordinates();\n if (flatCoordinates) {\n const stride = this.getStride();\n rotate(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n angle,\n anchor,\n flatCoordinates\n );\n this.changed();\n }\n }\n\n /**\n * Scale the geometry (with an optional origin). This modifies the geometry\n * coordinates in place.\n * @param {number} sx The scaling factor in the x-direction.\n * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).\n * @param {import(\"../coordinate.js\").Coordinate} [anchor] The scale origin (defaults to the center\n * of the geometry extent).\n * @api\n */\n scale(sx, sy, anchor) {\n if (sy === undefined) {\n sy = sx;\n }\n if (!anchor) {\n anchor = getCenter(this.getExtent());\n }\n const flatCoordinates = this.getFlatCoordinates();\n if (flatCoordinates) {\n const stride = this.getStride();\n scale(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n sx,\n sy,\n anchor,\n flatCoordinates\n );\n this.changed();\n }\n }\n\n /**\n * Translate the geometry. This modifies the geometry coordinates in place. If\n * instead you want a new geometry, first `clone()` this geometry.\n * @param {number} deltaX Delta X.\n * @param {number} deltaY Delta Y.\n * @api\n */\n translate(deltaX, deltaY) {\n const flatCoordinates = this.getFlatCoordinates();\n if (flatCoordinates) {\n const stride = this.getStride();\n translate(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n deltaX,\n deltaY,\n flatCoordinates\n );\n this.changed();\n }\n }\n}\n\n/**\n * @param {number} stride Stride.\n * @return {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n */\nfunction getLayoutForStride(stride) {\n let layout;\n if (stride == 2) {\n layout = 'XY';\n } else if (stride == 3) {\n layout = 'XYZ';\n } else if (stride == 4) {\n layout = 'XYZM';\n }\n return /** @type {import(\"./Geometry.js\").GeometryLayout} */ (layout);\n}\n\n/**\n * @param {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n * @return {number} Stride.\n */\nexport function getStrideForLayout(layout) {\n let stride;\n if (layout == 'XY') {\n stride = 2;\n } else if (layout == 'XYZ' || layout == 'XYM') {\n stride = 3;\n } else if (layout == 'XYZM') {\n stride = 4;\n }\n return /** @type {number} */ (stride);\n}\n\n/**\n * @param {SimpleGeometry} simpleGeometry Simple geometry.\n * @param {import(\"../transform.js\").Transform} transform Transform.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed flat coordinates.\n */\nexport function transformGeom2D(simpleGeometry, transform, dest) {\n const flatCoordinates = simpleGeometry.getFlatCoordinates();\n if (!flatCoordinates) {\n return null;\n }\n const stride = simpleGeometry.getStride();\n return transform2D(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n transform,\n dest\n );\n}\n\nexport default SimpleGeometry;\n","/**\n * @module ol/geom/flat/closest\n */\nimport {lerp, squaredDistance as squaredDx} from '../../math.js';\n\n/**\n * Returns the point on the 2D line segment flatCoordinates[offset1] to\n * flatCoordinates[offset2] that is closest to the point (x, y). Extra\n * dimensions are linearly interpolated.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset1 Offset 1.\n * @param {number} offset2 Offset 2.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n */\nfunction assignClosest(\n flatCoordinates,\n offset1,\n offset2,\n stride,\n x,\n y,\n closestPoint\n) {\n const x1 = flatCoordinates[offset1];\n const y1 = flatCoordinates[offset1 + 1];\n const dx = flatCoordinates[offset2] - x1;\n const dy = flatCoordinates[offset2 + 1] - y1;\n let offset;\n if (dx === 0 && dy === 0) {\n offset = offset1;\n } else {\n const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);\n if (t > 1) {\n offset = offset2;\n } else if (t > 0) {\n for (let i = 0; i < stride; ++i) {\n closestPoint[i] = lerp(\n flatCoordinates[offset1 + i],\n flatCoordinates[offset2 + i],\n t\n );\n }\n closestPoint.length = stride;\n return;\n } else {\n offset = offset1;\n }\n }\n for (let i = 0; i < stride; ++i) {\n closestPoint[i] = flatCoordinates[offset + i];\n }\n closestPoint.length = stride;\n}\n\n/**\n * Return the squared of the largest distance between any pair of consecutive\n * coordinates.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function maxSquaredDelta(flatCoordinates, offset, end, stride, max) {\n let x1 = flatCoordinates[offset];\n let y1 = flatCoordinates[offset + 1];\n for (offset += stride; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n const squaredDelta = squaredDx(x1, y1, x2, y2);\n if (squaredDelta > max) {\n max = squaredDelta;\n }\n x1 = x2;\n y1 = y2;\n }\n return max;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function arrayMaxSquaredDelta(\n flatCoordinates,\n offset,\n ends,\n stride,\n max\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n max = maxSquaredDelta(flatCoordinates, offset, end, stride, max);\n offset = end;\n }\n return max;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function multiArrayMaxSquaredDelta(\n flatCoordinates,\n offset,\n endss,\n stride,\n max\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n max = arrayMaxSquaredDelta(flatCoordinates, offset, ends, stride, max);\n offset = ends[ends.length - 1];\n }\n return max;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestPoint(\n flatCoordinates,\n offset,\n end,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n) {\n if (offset == end) {\n return minSquaredDistance;\n }\n let i, squaredDistance;\n if (maxDelta === 0) {\n // All points are identical, so just test the first point.\n squaredDistance = squaredDx(\n x,\n y,\n flatCoordinates[offset],\n flatCoordinates[offset + 1]\n );\n if (squaredDistance < minSquaredDistance) {\n for (i = 0; i < stride; ++i) {\n closestPoint[i] = flatCoordinates[offset + i];\n }\n closestPoint.length = stride;\n return squaredDistance;\n }\n return minSquaredDistance;\n }\n tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n let index = offset + stride;\n while (index < end) {\n assignClosest(\n flatCoordinates,\n index - stride,\n index,\n stride,\n x,\n y,\n tmpPoint\n );\n squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]);\n if (squaredDistance < minSquaredDistance) {\n minSquaredDistance = squaredDistance;\n for (i = 0; i < stride; ++i) {\n closestPoint[i] = tmpPoint[i];\n }\n closestPoint.length = stride;\n index += stride;\n } else {\n // Skip ahead multiple points, because we know that all the skipped\n // points cannot be any closer than the closest point we have found so\n // far. We know this because we know how close the current point is, how\n // close the closest point we have found so far is, and the maximum\n // distance between consecutive points. For example, if we're currently\n // at distance 10, the best we've found so far is 3, and that the maximum\n // distance between consecutive points is 2, then we'll need to skip at\n // least (10 - 3) / 2 == 3 (rounded down) points to have any chance of\n // finding a closer point. We use Math.max(..., 1) to ensure that we\n // always advance at least one point, to avoid an infinite loop.\n index +=\n stride *\n Math.max(\n ((Math.sqrt(squaredDistance) - Math.sqrt(minSquaredDistance)) /\n maxDelta) |\n 0,\n 1\n );\n }\n }\n if (isRing) {\n // Check the closing segment.\n assignClosest(\n flatCoordinates,\n end - stride,\n offset,\n stride,\n x,\n y,\n tmpPoint\n );\n squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]);\n if (squaredDistance < minSquaredDistance) {\n minSquaredDistance = squaredDistance;\n for (i = 0; i < stride; ++i) {\n closestPoint[i] = tmpPoint[i];\n }\n closestPoint.length = stride;\n }\n }\n return minSquaredDistance;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestArrayPoint(\n flatCoordinates,\n offset,\n ends,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n) {\n tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n minSquaredDistance = assignClosestPoint(\n flatCoordinates,\n offset,\n end,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n );\n offset = end;\n }\n return minSquaredDistance;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestMultiArrayPoint(\n flatCoordinates,\n offset,\n endss,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n) {\n tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n minSquaredDistance = assignClosestArrayPoint(\n flatCoordinates,\n offset,\n ends,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n );\n offset = ends[ends.length - 1];\n }\n return minSquaredDistance;\n}\n","/**\n * @module ol/geom/flat/deflate\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} stride Stride.\n * @return {number} offset Offset.\n */\nexport function deflateCoordinate(flatCoordinates, offset, coordinate, stride) {\n for (let i = 0, ii = coordinate.length; i < ii; ++i) {\n flatCoordinates[offset++] = coordinate[i];\n }\n return offset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} coordinates Coordinates.\n * @param {number} stride Stride.\n * @return {number} offset Offset.\n */\nexport function deflateCoordinates(\n flatCoordinates,\n offset,\n coordinates,\n stride\n) {\n for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n const coordinate = coordinates[i];\n for (let j = 0; j < stride; ++j) {\n flatCoordinates[offset++] = coordinate[j];\n }\n }\n return offset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} coordinatess Coordinatess.\n * @param {number} stride Stride.\n * @param {Array} [ends] Ends.\n * @return {Array} Ends.\n */\nexport function deflateCoordinatesArray(\n flatCoordinates,\n offset,\n coordinatess,\n stride,\n ends\n) {\n ends = ends ? ends : [];\n let i = 0;\n for (let j = 0, jj = coordinatess.length; j < jj; ++j) {\n const end = deflateCoordinates(\n flatCoordinates,\n offset,\n coordinatess[j],\n stride\n );\n ends[i++] = end;\n offset = end;\n }\n ends.length = i;\n return ends;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>>} coordinatesss Coordinatesss.\n * @param {number} stride Stride.\n * @param {Array>} [endss] Endss.\n * @return {Array>} Endss.\n */\nexport function deflateMultiCoordinatesArray(\n flatCoordinates,\n offset,\n coordinatesss,\n stride,\n endss\n) {\n endss = endss ? endss : [];\n let i = 0;\n for (let j = 0, jj = coordinatesss.length; j < jj; ++j) {\n const ends = deflateCoordinatesArray(\n flatCoordinates,\n offset,\n coordinatesss[j],\n stride,\n endss[i]\n );\n if (ends.length === 0) {\n ends[0] = offset;\n }\n endss[i++] = ends;\n offset = ends[ends.length - 1];\n }\n endss.length = i;\n return endss;\n}\n","/**\n * @module ol/geom/flat/simplify\n */\n// Based on simplify-js https://github.com/mourner/simplify-js\n// Copyright (c) 2012, Vladimir Agafonkin\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice,\n// this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n\nimport {squaredDistance, squaredSegmentDistance} from '../../math.js';\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {boolean} highQuality Highest quality.\n * @param {Array} [simplifiedFlatCoordinates] Simplified flat\n * coordinates.\n * @return {Array} Simplified line string.\n */\nexport function simplifyLineString(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n highQuality,\n simplifiedFlatCoordinates\n) {\n simplifiedFlatCoordinates =\n simplifiedFlatCoordinates !== undefined ? simplifiedFlatCoordinates : [];\n if (!highQuality) {\n end = radialDistance(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n 0\n );\n flatCoordinates = simplifiedFlatCoordinates;\n offset = 0;\n stride = 2;\n }\n simplifiedFlatCoordinates.length = douglasPeucker(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n 0\n );\n return simplifiedFlatCoordinates;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function douglasPeucker(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n) {\n const n = (end - offset) / stride;\n if (n < 3) {\n for (; offset < end; offset += stride) {\n simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + 1];\n }\n return simplifiedOffset;\n }\n /** @type {Array} */\n const markers = new Array(n);\n markers[0] = 1;\n markers[n - 1] = 1;\n /** @type {Array} */\n const stack = [offset, end - stride];\n let index = 0;\n while (stack.length > 0) {\n const last = stack.pop();\n const first = stack.pop();\n let maxSquaredDistance = 0;\n const x1 = flatCoordinates[first];\n const y1 = flatCoordinates[first + 1];\n const x2 = flatCoordinates[last];\n const y2 = flatCoordinates[last + 1];\n for (let i = first + stride; i < last; i += stride) {\n const x = flatCoordinates[i];\n const y = flatCoordinates[i + 1];\n const squaredDistance = squaredSegmentDistance(x, y, x1, y1, x2, y2);\n if (squaredDistance > maxSquaredDistance) {\n index = i;\n maxSquaredDistance = squaredDistance;\n }\n }\n if (maxSquaredDistance > squaredTolerance) {\n markers[(index - offset) / stride] = 1;\n if (first + stride < index) {\n stack.push(first, index);\n }\n if (index + stride < last) {\n stack.push(index, last);\n }\n }\n }\n for (let i = 0; i < n; ++i) {\n if (markers[i]) {\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + i * stride];\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + i * stride + 1];\n }\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array} simplifiedEnds Simplified ends.\n * @return {number} Simplified offset.\n */\nexport function douglasPeuckerArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n simplifiedOffset = douglasPeucker(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n );\n simplifiedEnds.push(simplifiedOffset);\n offset = end;\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array>} simplifiedEndss Simplified endss.\n * @return {number} Simplified offset.\n */\nexport function douglasPeuckerMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEndss\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n const simplifiedEnds = [];\n simplifiedOffset = douglasPeuckerArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n );\n simplifiedEndss.push(simplifiedEnds);\n offset = ends[ends.length - 1];\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function radialDistance(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n) {\n if (end <= offset + stride) {\n // zero or one point, no simplification possible, so copy and return\n for (; offset < end; offset += stride) {\n simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + 1];\n }\n return simplifiedOffset;\n }\n let x1 = flatCoordinates[offset];\n let y1 = flatCoordinates[offset + 1];\n // copy first point\n simplifiedFlatCoordinates[simplifiedOffset++] = x1;\n simplifiedFlatCoordinates[simplifiedOffset++] = y1;\n let x2 = x1;\n let y2 = y1;\n for (offset += stride; offset < end; offset += stride) {\n x2 = flatCoordinates[offset];\n y2 = flatCoordinates[offset + 1];\n if (squaredDistance(x1, y1, x2, y2) > squaredTolerance) {\n // copy point at offset\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n x1 = x2;\n y1 = y2;\n }\n }\n if (x2 != x1 || y2 != y1) {\n // copy last point\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {number} value Value.\n * @param {number} tolerance Tolerance.\n * @return {number} Rounded value.\n */\nexport function snap(value, tolerance) {\n return tolerance * Math.round(value / tolerance);\n}\n\n/**\n * Simplifies a line string using an algorithm designed by Tim Schaub.\n * Coordinates are snapped to the nearest value in a virtual grid and\n * consecutive duplicate coordinates are discarded. This effectively preserves\n * topology as the simplification of any subsection of a line string is\n * independent of the rest of the line string. This means that, for examples,\n * the common edge between two polygons will be simplified to the same line\n * string independently in both polygons. This implementation uses a single\n * pass over the coordinates and eliminates intermediate collinear points.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function quantize(\n flatCoordinates,\n offset,\n end,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n) {\n // do nothing if the line is empty\n if (offset == end) {\n return simplifiedOffset;\n }\n // snap the first coordinate (P1)\n let x1 = snap(flatCoordinates[offset], tolerance);\n let y1 = snap(flatCoordinates[offset + 1], tolerance);\n offset += stride;\n // add the first coordinate to the output\n simplifiedFlatCoordinates[simplifiedOffset++] = x1;\n simplifiedFlatCoordinates[simplifiedOffset++] = y1;\n // find the next coordinate that does not snap to the same value as the first\n // coordinate (P2)\n let x2, y2;\n do {\n x2 = snap(flatCoordinates[offset], tolerance);\n y2 = snap(flatCoordinates[offset + 1], tolerance);\n offset += stride;\n if (offset == end) {\n // all coordinates snap to the same value, the line collapses to a point\n // push the last snapped value anyway to ensure that the output contains\n // at least two points\n // FIXME should we really return at least two points anyway?\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n return simplifiedOffset;\n }\n } while (x2 == x1 && y2 == y1);\n while (offset < end) {\n // snap the next coordinate (P3)\n const x3 = snap(flatCoordinates[offset], tolerance);\n const y3 = snap(flatCoordinates[offset + 1], tolerance);\n offset += stride;\n // skip P3 if it is equal to P2\n if (x3 == x2 && y3 == y2) {\n continue;\n }\n // calculate the delta between P1 and P2\n const dx1 = x2 - x1;\n const dy1 = y2 - y1;\n // calculate the delta between P3 and P1\n const dx2 = x3 - x1;\n const dy2 = y3 - y1;\n // if P1, P2, and P3 are colinear and P3 is further from P1 than P2 is from\n // P1 in the same direction then P2 is on the straight line between P1 and\n // P3\n if (\n dx1 * dy2 == dy1 * dx2 &&\n ((dx1 < 0 && dx2 < dx1) || dx1 == dx2 || (dx1 > 0 && dx2 > dx1)) &&\n ((dy1 < 0 && dy2 < dy1) || dy1 == dy2 || (dy1 > 0 && dy2 > dy1))\n ) {\n // discard P2 and set P2 = P3\n x2 = x3;\n y2 = y3;\n continue;\n }\n // either P1, P2, and P3 are not colinear, or they are colinear but P3 is\n // between P3 and P1 or on the opposite half of the line to P2. add P2,\n // and continue with P1 = P2 and P2 = P3\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n x1 = x2;\n y1 = y2;\n x2 = x3;\n y2 = y3;\n }\n // add the last point (P2)\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array} simplifiedEnds Simplified ends.\n * @return {number} Simplified offset.\n */\nexport function quantizeArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n simplifiedOffset = quantize(\n flatCoordinates,\n offset,\n end,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n );\n simplifiedEnds.push(simplifiedOffset);\n offset = end;\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array>} simplifiedEndss Simplified endss.\n * @return {number} Simplified offset.\n */\nexport function quantizeMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEndss\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n const simplifiedEnds = [];\n simplifiedOffset = quantizeArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n );\n simplifiedEndss.push(simplifiedEnds);\n offset = ends[ends.length - 1];\n }\n return simplifiedOffset;\n}\n","/**\n * @module ol/geom/flat/inflate\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {Array} [coordinates] Coordinates.\n * @return {Array} Coordinates.\n */\nexport function inflateCoordinates(\n flatCoordinates,\n offset,\n end,\n stride,\n coordinates\n) {\n coordinates = coordinates !== undefined ? coordinates : [];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n coordinates[i++] = flatCoordinates.slice(j, j + stride);\n }\n coordinates.length = i;\n return coordinates;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {Array>} [coordinatess] Coordinatess.\n * @return {Array>} Coordinatess.\n */\nexport function inflateCoordinatesArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n coordinatess\n) {\n coordinatess = coordinatess !== undefined ? coordinatess : [];\n let i = 0;\n for (let j = 0, jj = ends.length; j < jj; ++j) {\n const end = ends[j];\n coordinatess[i++] = inflateCoordinates(\n flatCoordinates,\n offset,\n end,\n stride,\n coordinatess[i]\n );\n offset = end;\n }\n coordinatess.length = i;\n return coordinatess;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {Array>>} [coordinatesss]\n * Coordinatesss.\n * @return {Array>>} Coordinatesss.\n */\nexport function inflateMultiCoordinatesArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n coordinatesss\n) {\n coordinatesss = coordinatesss !== undefined ? coordinatesss : [];\n let i = 0;\n for (let j = 0, jj = endss.length; j < jj; ++j) {\n const ends = endss[j];\n coordinatesss[i++] =\n ends.length === 1 && ends[0] === offset\n ? []\n : inflateCoordinatesArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n coordinatesss[i]\n );\n offset = ends[ends.length - 1];\n }\n coordinatesss.length = i;\n return coordinatesss;\n}\n","/**\n * @module ol/geom/flat/area\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRing(flatCoordinates, offset, end, stride) {\n let twiceArea = 0;\n let x1 = flatCoordinates[end - stride];\n let y1 = flatCoordinates[end - stride + 1];\n for (; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n twiceArea += y1 * x2 - x1 * y2;\n x1 = x2;\n y1 = y2;\n }\n return twiceArea / 2;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRings(flatCoordinates, offset, ends, stride) {\n let area = 0;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n area += linearRing(flatCoordinates, offset, end, stride);\n offset = end;\n }\n return area;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRingss(flatCoordinates, offset, endss, stride) {\n let area = 0;\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n area += linearRings(flatCoordinates, offset, ends, stride);\n offset = ends[ends.length - 1];\n }\n return area;\n}\n","/**\n * @module ol/geom/LinearRing\n */\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {assignClosestPoint, maxSquaredDelta} from './flat/closest.js';\nimport {closestSquaredDistanceXY} from '../extent.js';\nimport {deflateCoordinates} from './flat/deflate.js';\nimport {douglasPeucker} from './flat/simplify.js';\nimport {inflateCoordinates} from './flat/inflate.js';\nimport {linearRing as linearRingArea} from './flat/area.js';\n\n/**\n * @classdesc\n * Linear ring geometry. Only used as part of polygon; cannot be rendered\n * on its own.\n *\n * @api\n */\nclass LinearRing extends SimpleGeometry {\n /**\n * @param {Array|Array} coordinates Coordinates.\n * For internal use, flat coordinates in combination with `layout` are also accepted.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n */\n constructor(coordinates, layout) {\n super();\n\n /**\n * @private\n * @type {number}\n */\n this.maxDelta_ = -1;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDeltaRevision_ = -1;\n\n if (layout !== undefined && !Array.isArray(coordinates[0])) {\n this.setFlatCoordinates(\n layout,\n /** @type {Array} */ (coordinates)\n );\n } else {\n this.setCoordinates(\n /** @type {Array} */ (\n coordinates\n ),\n layout\n );\n }\n }\n\n /**\n * Make a complete copy of the geometry.\n * @return {!LinearRing} Clone.\n * @api\n */\n clone() {\n return new LinearRing(this.flatCoordinates.slice(), this.layout);\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n return minSquaredDistance;\n }\n if (this.maxDeltaRevision_ != this.getRevision()) {\n this.maxDelta_ = Math.sqrt(\n maxSquaredDelta(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n 0\n )\n );\n this.maxDeltaRevision_ = this.getRevision();\n }\n return assignClosestPoint(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n this.maxDelta_,\n true,\n x,\n y,\n closestPoint,\n minSquaredDistance\n );\n }\n\n /**\n * Return the area of the linear ring on projected plane.\n * @return {number} Area (on projected plane).\n * @api\n */\n getArea() {\n return linearRingArea(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride\n );\n }\n\n /**\n * Return the coordinates of the linear ring.\n * @return {Array} Coordinates.\n * @api\n */\n getCoordinates() {\n return inflateCoordinates(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride\n );\n }\n\n /**\n * @param {number} squaredTolerance Squared tolerance.\n * @return {LinearRing} Simplified LinearRing.\n * @protected\n */\n getSimplifiedGeometryInternal(squaredTolerance) {\n const simplifiedFlatCoordinates = [];\n simplifiedFlatCoordinates.length = douglasPeucker(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n 0\n );\n return new LinearRing(simplifiedFlatCoordinates, 'XY');\n }\n\n /**\n * Get the type of this geometry.\n * @return {import(\"./Geometry.js\").Type} Geometry type.\n * @api\n */\n getType() {\n return 'LinearRing';\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n * @api\n */\n intersectsExtent(extent) {\n return false;\n }\n\n /**\n * Set the coordinates of the linear ring.\n * @param {!Array} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @api\n */\n setCoordinates(coordinates, layout) {\n this.setLayout(layout, coordinates, 1);\n if (!this.flatCoordinates) {\n this.flatCoordinates = [];\n }\n this.flatCoordinates.length = deflateCoordinates(\n this.flatCoordinates,\n 0,\n coordinates,\n this.stride\n );\n this.changed();\n }\n}\n\nexport default LinearRing;\n","/**\n * @module ol/geom/Point\n */\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {containsXY, createOrUpdateFromCoordinate} from '../extent.js';\nimport {deflateCoordinate} from './flat/deflate.js';\nimport {squaredDistance as squaredDx} from '../math.js';\n\n/**\n * @classdesc\n * Point geometry.\n *\n * @api\n */\nclass Point extends SimpleGeometry {\n /**\n * @param {import(\"../coordinate.js\").Coordinate} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n */\n constructor(coordinates, layout) {\n super();\n this.setCoordinates(coordinates, layout);\n }\n\n /**\n * Make a complete copy of the geometry.\n * @return {!Point} Clone.\n * @api\n */\n clone() {\n const point = new Point(this.flatCoordinates.slice(), this.layout);\n point.applyProperties(this);\n return point;\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n const flatCoordinates = this.flatCoordinates;\n const squaredDistance = squaredDx(\n x,\n y,\n flatCoordinates[0],\n flatCoordinates[1]\n );\n if (squaredDistance < minSquaredDistance) {\n const stride = this.stride;\n for (let i = 0; i < stride; ++i) {\n closestPoint[i] = flatCoordinates[i];\n }\n closestPoint.length = stride;\n return squaredDistance;\n }\n return minSquaredDistance;\n }\n\n /**\n * Return the coordinate of the point.\n * @return {import(\"../coordinate.js\").Coordinate} Coordinates.\n * @api\n */\n getCoordinates() {\n return !this.flatCoordinates ? [] : this.flatCoordinates.slice();\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @protected\n * @return {import(\"../extent.js\").Extent} extent Extent.\n */\n computeExtent(extent) {\n return createOrUpdateFromCoordinate(this.flatCoordinates, extent);\n }\n\n /**\n * Get the type of this geometry.\n * @return {import(\"./Geometry.js\").Type} Geometry type.\n * @api\n */\n getType() {\n return 'Point';\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n * @api\n */\n intersectsExtent(extent) {\n return containsXY(extent, this.flatCoordinates[0], this.flatCoordinates[1]);\n }\n\n /**\n * @param {!Array<*>} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @api\n */\n setCoordinates(coordinates, layout) {\n this.setLayout(layout, coordinates, 0);\n if (!this.flatCoordinates) {\n this.flatCoordinates = [];\n }\n this.flatCoordinates.length = deflateCoordinate(\n this.flatCoordinates,\n 0,\n coordinates,\n this.stride\n );\n this.changed();\n }\n}\n\nexport default Point;\n","/**\n * @module ol/geom/flat/contains\n */\nimport {forEachCorner} from '../../extent.js';\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} Contains extent.\n */\nexport function linearRingContainsExtent(\n flatCoordinates,\n offset,\n end,\n stride,\n extent\n) {\n const outside = forEachCorner(\n extent,\n /**\n * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {boolean} Contains (x, y).\n */\n function (coordinate) {\n return !linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n coordinate[0],\n coordinate[1]\n );\n }\n );\n return !outside;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n x,\n y\n) {\n // https://geomalgorithms.com/a03-_inclusion.html\n // Copyright 2000 softSurfer, 2012 Dan Sunday\n // This code may be freely used and modified for any purpose\n // providing that this copyright notice is included with it.\n // SoftSurfer makes no warranty for this code, and cannot be held\n // liable for any real or imagined damage resulting from its use.\n // Users of this code must verify correctness for their application.\n let wn = 0;\n let x1 = flatCoordinates[end - stride];\n let y1 = flatCoordinates[end - stride + 1];\n for (; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n if (y1 <= y) {\n if (y2 > y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) > 0) {\n wn++;\n }\n } else if (y2 <= y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) < 0) {\n wn--;\n }\n x1 = x2;\n y1 = y2;\n }\n return wn !== 0;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingsContainsXY(\n flatCoordinates,\n offset,\n ends,\n stride,\n x,\n y\n) {\n if (ends.length === 0) {\n return false;\n }\n if (!linearRingContainsXY(flatCoordinates, offset, ends[0], stride, x, y)) {\n return false;\n }\n for (let i = 1, ii = ends.length; i < ii; ++i) {\n if (\n linearRingContainsXY(flatCoordinates, ends[i - 1], ends[i], stride, x, y)\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingssContainsXY(\n flatCoordinates,\n offset,\n endss,\n stride,\n x,\n y\n) {\n if (endss.length === 0) {\n return false;\n }\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {\n return true;\n }\n offset = ends[ends.length - 1];\n }\n return false;\n}\n","/**\n * @module ol/geom/flat/interiorpoint\n */\nimport {ascending} from '../../array.js';\nimport {linearRingsContainsXY} from './contains.js';\n\n/**\n * Calculates a point that is likely to lie in the interior of the linear rings.\n * Inspired by JTS's com.vividsolutions.jts.geom.Geometry#getInteriorPoint.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {Array} flatCenters Flat centers.\n * @param {number} flatCentersOffset Flat center offset.\n * @param {Array} [dest] Destination.\n * @return {Array} Destination point as XYM coordinate, where M is the\n * length of the horizontal intersection that the point belongs to.\n */\nexport function getInteriorPointOfArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n flatCenters,\n flatCentersOffset,\n dest\n) {\n let i, ii, x, x1, x2, y1, y2;\n const y = flatCenters[flatCentersOffset + 1];\n /** @type {Array} */\n const intersections = [];\n // Calculate intersections with the horizontal line\n for (let r = 0, rr = ends.length; r < rr; ++r) {\n const end = ends[r];\n x1 = flatCoordinates[end - stride];\n y1 = flatCoordinates[end - stride + 1];\n for (i = offset; i < end; i += stride) {\n x2 = flatCoordinates[i];\n y2 = flatCoordinates[i + 1];\n if ((y <= y1 && y2 <= y) || (y1 <= y && y <= y2)) {\n x = ((y - y1) / (y2 - y1)) * (x2 - x1) + x1;\n intersections.push(x);\n }\n x1 = x2;\n y1 = y2;\n }\n }\n // Find the longest segment of the horizontal line that has its center point\n // inside the linear ring.\n let pointX = NaN;\n let maxSegmentLength = -Infinity;\n intersections.sort(ascending);\n x1 = intersections[0];\n for (i = 1, ii = intersections.length; i < ii; ++i) {\n x2 = intersections[i];\n const segmentLength = Math.abs(x2 - x1);\n if (segmentLength > maxSegmentLength) {\n x = (x1 + x2) / 2;\n if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {\n pointX = x;\n maxSegmentLength = segmentLength;\n }\n }\n x1 = x2;\n }\n if (isNaN(pointX)) {\n // There is no horizontal line that has its center point inside the linear\n // ring. Use the center of the the linear ring's extent.\n pointX = flatCenters[flatCentersOffset];\n }\n if (dest) {\n dest.push(pointX, y, maxSegmentLength);\n return dest;\n }\n return [pointX, y, maxSegmentLength];\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {Array} flatCenters Flat centers.\n * @return {Array} Interior points as XYM coordinates, where M is the\n * length of the horizontal intersection that the point belongs to.\n */\nexport function getInteriorPointsOfMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n flatCenters\n) {\n let interiorPoints = [];\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n interiorPoints = getInteriorPointOfArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n flatCenters,\n 2 * i,\n interiorPoints\n );\n offset = ends[ends.length - 1];\n }\n return interiorPoints;\n}\n","/**\n * @module ol/geom/flat/segments\n */\n\n/**\n * This function calls `callback` for each segment of the flat coordinates\n * array. If the callback returns a truthy value the function returns that\n * value immediately. Otherwise the function returns `false`.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {function(import(\"../../coordinate.js\").Coordinate, import(\"../../coordinate.js\").Coordinate): T} callback Function\n * called for each segment.\n * @return {T|boolean} Value.\n * @template T\n */\nexport function forEach(flatCoordinates, offset, end, stride, callback) {\n let ret;\n offset += stride;\n for (; offset < end; offset += stride) {\n ret = callback(\n flatCoordinates.slice(offset - stride, offset),\n flatCoordinates.slice(offset, offset + stride)\n );\n if (ret) {\n return ret;\n }\n }\n return false;\n}\n","/**\n * @module ol/geom/flat/intersectsextent\n */\nimport {\n containsExtent,\n createEmpty,\n extendFlatCoordinates,\n intersects,\n intersectsSegment,\n} from '../../extent.js';\nimport {forEach as forEachSegment} from './segments.js';\nimport {linearRingContainsExtent, linearRingContainsXY} from './contains.js';\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLineString(\n flatCoordinates,\n offset,\n end,\n stride,\n extent\n) {\n const coordinatesExtent = extendFlatCoordinates(\n createEmpty(),\n flatCoordinates,\n offset,\n end,\n stride\n );\n if (!intersects(extent, coordinatesExtent)) {\n return false;\n }\n if (containsExtent(extent, coordinatesExtent)) {\n return true;\n }\n if (coordinatesExtent[0] >= extent[0] && coordinatesExtent[2] <= extent[2]) {\n return true;\n }\n if (coordinatesExtent[1] >= extent[1] && coordinatesExtent[3] <= extent[3]) {\n return true;\n }\n return forEachSegment(\n flatCoordinates,\n offset,\n end,\n stride,\n /**\n * @param {import(\"../../coordinate.js\").Coordinate} point1 Start point.\n * @param {import(\"../../coordinate.js\").Coordinate} point2 End point.\n * @return {boolean} `true` if the segment and the extent intersect,\n * `false` otherwise.\n */\n function (point1, point2) {\n return intersectsSegment(extent, point1, point2);\n }\n );\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLineStringArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n extent\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n if (\n intersectsLineString(flatCoordinates, offset, ends[i], stride, extent)\n ) {\n return true;\n }\n offset = ends[i];\n }\n return false;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRing(\n flatCoordinates,\n offset,\n end,\n stride,\n extent\n) {\n if (intersectsLineString(flatCoordinates, offset, end, stride, extent)) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[0],\n extent[1]\n )\n ) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[0],\n extent[3]\n )\n ) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[2],\n extent[1]\n )\n ) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[2],\n extent[3]\n )\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRingArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n extent\n) {\n if (!intersectsLinearRing(flatCoordinates, offset, ends[0], stride, extent)) {\n return false;\n }\n if (ends.length === 1) {\n return true;\n }\n for (let i = 1, ii = ends.length; i < ii; ++i) {\n if (\n linearRingContainsExtent(\n flatCoordinates,\n ends[i - 1],\n ends[i],\n stride,\n extent\n )\n ) {\n if (\n !intersectsLineString(\n flatCoordinates,\n ends[i - 1],\n ends[i],\n stride,\n extent\n )\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRingMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n extent\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n if (\n intersectsLinearRingArray(flatCoordinates, offset, ends, stride, extent)\n ) {\n return true;\n }\n offset = ends[ends.length - 1];\n }\n return false;\n}\n","/**\n * @module ol/geom/flat/reverse\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n */\nexport function coordinates(flatCoordinates, offset, end, stride) {\n while (offset < end - stride) {\n for (let i = 0; i < stride; ++i) {\n const tmp = flatCoordinates[offset + i];\n flatCoordinates[offset + i] = flatCoordinates[end - stride + i];\n flatCoordinates[end - stride + i] = tmp;\n }\n offset += stride;\n end -= stride;\n }\n}\n","/**\n * @module ol/geom/flat/orient\n */\nimport {coordinates as reverseCoordinates} from './reverse.js';\n\n/**\n * Is the linear ring oriented clockwise in a coordinate system with a bottom-left\n * coordinate origin? For a coordinate system with a top-left coordinate origin,\n * the ring's orientation is clockwise when this function returns false.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {boolean} Is clockwise.\n */\nexport function linearRingIsClockwise(flatCoordinates, offset, end, stride) {\n // https://stackoverflow.com/q/1165647/clockwise-method#1165943\n // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrlinearring.cpp\n let edge = 0;\n let x1 = flatCoordinates[end - stride];\n let y1 = flatCoordinates[end - stride + 1];\n for (; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n edge += (x2 - x1) * (y2 + y1);\n x1 = x2;\n y1 = y2;\n }\n return edge === 0 ? undefined : edge > 0;\n}\n\n/**\n * Determines if linear rings are oriented. By default, left-hand orientation\n * is tested (first ring must be clockwise, remaining rings counter-clockwise).\n * To test for right-hand orientation, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Test for right-hand orientation\n * (counter-clockwise exterior ring and clockwise interior rings).\n * @return {boolean} Rings are correctly oriented.\n */\nexport function linearRingsAreOriented(\n flatCoordinates,\n offset,\n ends,\n stride,\n right\n) {\n right = right !== undefined ? right : false;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n const isClockwise = linearRingIsClockwise(\n flatCoordinates,\n offset,\n end,\n stride\n );\n if (i === 0) {\n if ((right && isClockwise) || (!right && !isClockwise)) {\n return false;\n }\n } else {\n if ((right && !isClockwise) || (!right && isClockwise)) {\n return false;\n }\n }\n offset = end;\n }\n return true;\n}\n\n/**\n * Determines if linear rings are oriented. By default, left-hand orientation\n * is tested (first ring must be clockwise, remaining rings counter-clockwise).\n * To test for right-hand orientation, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Array of array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Test for right-hand orientation\n * (counter-clockwise exterior ring and clockwise interior rings).\n * @return {boolean} Rings are correctly oriented.\n */\nexport function linearRingssAreOriented(\n flatCoordinates,\n offset,\n endss,\n stride,\n right\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n if (!linearRingsAreOriented(flatCoordinates, offset, ends, stride, right)) {\n return false;\n }\n if (ends.length) {\n offset = ends[ends.length - 1];\n }\n }\n return true;\n}\n\n/**\n * Orient coordinates in a flat array of linear rings. By default, rings\n * are oriented following the left-hand rule (clockwise for exterior and\n * counter-clockwise for interior rings). To orient according to the\n * right-hand rule, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {boolean} [right] Follow the right-hand rule for orientation.\n * @return {number} End.\n */\nexport function orientLinearRings(\n flatCoordinates,\n offset,\n ends,\n stride,\n right\n) {\n right = right !== undefined ? right : false;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n const isClockwise = linearRingIsClockwise(\n flatCoordinates,\n offset,\n end,\n stride\n );\n const reverse =\n i === 0\n ? (right && isClockwise) || (!right && !isClockwise)\n : (right && !isClockwise) || (!right && isClockwise);\n if (reverse) {\n reverseCoordinates(flatCoordinates, offset, end, stride);\n }\n offset = end;\n }\n return offset;\n}\n\n/**\n * Orient coordinates in a flat array of linear rings. By default, rings\n * are oriented following the left-hand rule (clockwise for exterior and\n * counter-clockwise for interior rings). To orient according to the\n * right-hand rule, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Array of array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Follow the right-hand rule for orientation.\n * @return {number} End.\n */\nexport function orientLinearRingsArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n right\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n offset = orientLinearRings(\n flatCoordinates,\n offset,\n endss[i],\n stride,\n right\n );\n }\n return offset;\n}\n\n/**\n * Return a two-dimensional endss\n * @param {Array} flatCoordinates Flat coordinates\n * @param {Array} ends Linear ring end indexes\n * @return {Array>} Two dimensional endss array that can\n * be used to construct a MultiPolygon\n */\nexport function inflateEnds(flatCoordinates, ends) {\n const endss = [];\n let offset = 0;\n let prevEndIndex = 0;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n // classifies an array of rings into polygons with outer rings and holes\n if (!linearRingIsClockwise(flatCoordinates, offset, end, 2)) {\n endss.push(ends.slice(prevEndIndex, i + 1));\n } else {\n if (endss.length === 0) {\n continue;\n }\n endss[endss.length - 1].push(ends[prevEndIndex]);\n }\n prevEndIndex = i + 1;\n offset = end;\n }\n return endss;\n}\n","/**\n * @module ol/geom/Polygon\n */\nimport LinearRing from './LinearRing.js';\nimport Point from './Point.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {arrayMaxSquaredDelta, assignClosestArrayPoint} from './flat/closest.js';\nimport {closestSquaredDistanceXY, getCenter, isEmpty} from '../extent.js';\nimport {deflateCoordinatesArray} from './flat/deflate.js';\nimport {extend} from '../array.js';\nimport {getInteriorPointOfArray} from './flat/interiorpoint.js';\nimport {inflateCoordinatesArray} from './flat/inflate.js';\nimport {intersectsLinearRingArray} from './flat/intersectsextent.js';\nimport {linearRingsAreOriented, orientLinearRings} from './flat/orient.js';\nimport {linearRings as linearRingsArea} from './flat/area.js';\nimport {linearRingsContainsXY} from './flat/contains.js';\nimport {modulo} from '../math.js';\nimport {quantizeArray} from './flat/simplify.js';\nimport {offset as sphereOffset} from '../sphere.js';\n\n/**\n * @classdesc\n * Polygon geometry.\n *\n * @api\n */\nclass Polygon extends SimpleGeometry {\n /**\n * @param {!Array>|!Array} coordinates\n * Array of linear rings that define the polygon. The first linear ring of the\n * array defines the outer-boundary or surface of the polygon. Each subsequent\n * linear ring defines a hole in the surface of the polygon. A linear ring is\n * an array of vertices' coordinates where the first coordinate and the last are\n * equivalent. (For internal use, flat coordinates in combination with\n * `layout` and `ends` are also accepted.)\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @param {Array} [ends] Ends (for internal use with flat coordinates).\n */\n constructor(coordinates, layout, ends) {\n super();\n\n /**\n * @type {Array}\n * @private\n */\n this.ends_ = [];\n\n /**\n * @private\n * @type {number}\n */\n this.flatInteriorPointRevision_ = -1;\n\n /**\n * @private\n * @type {import(\"../coordinate.js\").Coordinate}\n */\n this.flatInteriorPoint_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDelta_ = -1;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDeltaRevision_ = -1;\n\n /**\n * @private\n * @type {number}\n */\n this.orientedRevision_ = -1;\n\n /**\n * @private\n * @type {Array}\n */\n this.orientedFlatCoordinates_ = null;\n\n if (layout !== undefined && ends) {\n this.setFlatCoordinates(\n layout,\n /** @type {Array} */ (coordinates)\n );\n this.ends_ = ends;\n } else {\n this.setCoordinates(\n /** @type {Array>} */ (\n coordinates\n ),\n layout\n );\n }\n }\n\n /**\n * Append the passed linear ring to this polygon.\n * @param {LinearRing} linearRing Linear ring.\n * @api\n */\n appendLinearRing(linearRing) {\n if (!this.flatCoordinates) {\n this.flatCoordinates = linearRing.getFlatCoordinates().slice();\n } else {\n extend(this.flatCoordinates, linearRing.getFlatCoordinates());\n }\n this.ends_.push(this.flatCoordinates.length);\n this.changed();\n }\n\n /**\n * Make a complete copy of the geometry.\n * @return {!Polygon} Clone.\n * @api\n */\n clone() {\n const polygon = new Polygon(\n this.flatCoordinates.slice(),\n this.layout,\n this.ends_.slice()\n );\n polygon.applyProperties(this);\n return polygon;\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n return minSquaredDistance;\n }\n if (this.maxDeltaRevision_ != this.getRevision()) {\n this.maxDelta_ = Math.sqrt(\n arrayMaxSquaredDelta(\n this.flatCoordinates,\n 0,\n this.ends_,\n this.stride,\n 0\n )\n );\n this.maxDeltaRevision_ = this.getRevision();\n }\n return assignClosestArrayPoint(\n this.flatCoordinates,\n 0,\n this.ends_,\n this.stride,\n this.maxDelta_,\n true,\n x,\n y,\n closestPoint,\n minSquaredDistance\n );\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\n containsXY(x, y) {\n return linearRingsContainsXY(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride,\n x,\n y\n );\n }\n\n /**\n * Return the area of the polygon on projected plane.\n * @return {number} Area (on projected plane).\n * @api\n */\n getArea() {\n return linearRingsArea(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride\n );\n }\n\n /**\n * Get the coordinate array for this geometry. This array has the structure\n * of a GeoJSON coordinate array for polygons.\n *\n * @param {boolean} [right] Orient coordinates according to the right-hand\n * rule (counter-clockwise for exterior and clockwise for interior rings).\n * If `false`, coordinates will be oriented according to the left-hand rule\n * (clockwise for exterior and counter-clockwise for interior rings).\n * By default, coordinate orientation will depend on how the geometry was\n * constructed.\n * @return {Array>} Coordinates.\n * @api\n */\n getCoordinates(right) {\n let flatCoordinates;\n if (right !== undefined) {\n flatCoordinates = this.getOrientedFlatCoordinates().slice();\n orientLinearRings(flatCoordinates, 0, this.ends_, this.stride, right);\n } else {\n flatCoordinates = this.flatCoordinates;\n }\n\n return inflateCoordinatesArray(flatCoordinates, 0, this.ends_, this.stride);\n }\n\n /**\n * @return {Array} Ends.\n */\n getEnds() {\n return this.ends_;\n }\n\n /**\n * @return {Array} Interior point.\n */\n getFlatInteriorPoint() {\n if (this.flatInteriorPointRevision_ != this.getRevision()) {\n const flatCenter = getCenter(this.getExtent());\n this.flatInteriorPoint_ = getInteriorPointOfArray(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride,\n flatCenter,\n 0\n );\n this.flatInteriorPointRevision_ = this.getRevision();\n }\n return this.flatInteriorPoint_;\n }\n\n /**\n * Return an interior point of the polygon.\n * @return {Point} Interior point as XYM coordinate, where M is the\n * length of the horizontal intersection that the point belongs to.\n * @api\n */\n getInteriorPoint() {\n return new Point(this.getFlatInteriorPoint(), 'XYM');\n }\n\n /**\n * Return the number of rings of the polygon, this includes the exterior\n * ring and any interior rings.\n *\n * @return {number} Number of rings.\n * @api\n */\n getLinearRingCount() {\n return this.ends_.length;\n }\n\n /**\n * Return the Nth linear ring of the polygon geometry. Return `null` if the\n * given index is out of range.\n * The exterior linear ring is available at index `0` and the interior rings\n * at index `1` and beyond.\n *\n * @param {number} index Index.\n * @return {LinearRing|null} Linear ring.\n * @api\n */\n getLinearRing(index) {\n if (index < 0 || this.ends_.length <= index) {\n return null;\n }\n return new LinearRing(\n this.flatCoordinates.slice(\n index === 0 ? 0 : this.ends_[index - 1],\n this.ends_[index]\n ),\n this.layout\n );\n }\n\n /**\n * Return the linear rings of the polygon.\n * @return {Array} Linear rings.\n * @api\n */\n getLinearRings() {\n const layout = this.layout;\n const flatCoordinates = this.flatCoordinates;\n const ends = this.ends_;\n const linearRings = [];\n let offset = 0;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n const linearRing = new LinearRing(\n flatCoordinates.slice(offset, end),\n layout\n );\n linearRings.push(linearRing);\n offset = end;\n }\n return linearRings;\n }\n\n /**\n * @return {Array} Oriented flat coordinates.\n */\n getOrientedFlatCoordinates() {\n if (this.orientedRevision_ != this.getRevision()) {\n const flatCoordinates = this.flatCoordinates;\n if (linearRingsAreOriented(flatCoordinates, 0, this.ends_, this.stride)) {\n this.orientedFlatCoordinates_ = flatCoordinates;\n } else {\n this.orientedFlatCoordinates_ = flatCoordinates.slice();\n this.orientedFlatCoordinates_.length = orientLinearRings(\n this.orientedFlatCoordinates_,\n 0,\n this.ends_,\n this.stride\n );\n }\n this.orientedRevision_ = this.getRevision();\n }\n return this.orientedFlatCoordinates_;\n }\n\n /**\n * @param {number} squaredTolerance Squared tolerance.\n * @return {Polygon} Simplified Polygon.\n * @protected\n */\n getSimplifiedGeometryInternal(squaredTolerance) {\n const simplifiedFlatCoordinates = [];\n const simplifiedEnds = [];\n simplifiedFlatCoordinates.length = quantizeArray(\n this.flatCoordinates,\n 0,\n this.ends_,\n this.stride,\n Math.sqrt(squaredTolerance),\n simplifiedFlatCoordinates,\n 0,\n simplifiedEnds\n );\n return new Polygon(simplifiedFlatCoordinates, 'XY', simplifiedEnds);\n }\n\n /**\n * Get the type of this geometry.\n * @return {import(\"./Geometry.js\").Type} Geometry type.\n * @api\n */\n getType() {\n return 'Polygon';\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n * @api\n */\n intersectsExtent(extent) {\n return intersectsLinearRingArray(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride,\n extent\n );\n }\n\n /**\n * Set the coordinates of the polygon.\n * @param {!Array>} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @api\n */\n setCoordinates(coordinates, layout) {\n this.setLayout(layout, coordinates, 2);\n if (!this.flatCoordinates) {\n this.flatCoordinates = [];\n }\n const ends = deflateCoordinatesArray(\n this.flatCoordinates,\n 0,\n coordinates,\n this.stride,\n this.ends_\n );\n this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];\n this.changed();\n }\n}\n\nexport default Polygon;\n\n/**\n * Create an approximation of a circle on the surface of a sphere.\n * @param {import(\"../coordinate.js\").Coordinate} center Center (`[lon, lat]` in degrees).\n * @param {number} radius The great-circle distance from the center to\n * the polygon vertices in meters.\n * @param {number} [n] Optional number of vertices for the resulting\n * polygon. Default is `32`.\n * @param {number} [sphereRadius] Optional radius for the sphere (defaults to\n * the Earth's mean radius using the WGS84 ellipsoid).\n * @return {Polygon} The \"circular\" polygon.\n * @api\n */\nexport function circular(center, radius, n, sphereRadius) {\n n = n ? n : 32;\n /** @type {Array} */\n const flatCoordinates = [];\n for (let i = 0; i < n; ++i) {\n extend(\n flatCoordinates,\n sphereOffset(center, radius, (2 * Math.PI * i) / n, sphereRadius)\n );\n }\n flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]);\n return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);\n}\n\n/**\n * Create a polygon from an extent. The layout used is `XY`.\n * @param {import(\"../extent.js\").Extent} extent The extent.\n * @return {Polygon} The polygon.\n * @api\n */\nexport function fromExtent(extent) {\n if (isEmpty(extent)) {\n throw new Error('Cannot create polygon from empty extent');\n }\n const minX = extent[0];\n const minY = extent[1];\n const maxX = extent[2];\n const maxY = extent[3];\n const flatCoordinates = [\n minX,\n minY,\n minX,\n maxY,\n maxX,\n maxY,\n maxX,\n minY,\n minX,\n minY,\n ];\n return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);\n}\n\n/**\n * Create a regular polygon from a circle.\n * @param {import(\"./Circle.js\").default} circle Circle geometry.\n * @param {number} [sides] Number of sides of the polygon. Default is 32.\n * @param {number} [angle] Start angle for the first vertex of the polygon in\n * counter-clockwise radians. 0 means East. Default is 0.\n * @return {Polygon} Polygon geometry.\n * @api\n */\nexport function fromCircle(circle, sides, angle) {\n sides = sides ? sides : 32;\n const stride = circle.getStride();\n const layout = circle.getLayout();\n const center = circle.getCenter();\n const arrayLength = stride * (sides + 1);\n const flatCoordinates = new Array(arrayLength);\n for (let i = 0; i < arrayLength; i += stride) {\n flatCoordinates[i] = 0;\n flatCoordinates[i + 1] = 0;\n for (let j = 2; j < stride; j++) {\n flatCoordinates[i + j] = center[j];\n }\n }\n const ends = [flatCoordinates.length];\n const polygon = new Polygon(flatCoordinates, layout, ends);\n makeRegular(polygon, center, circle.getRadius(), angle);\n return polygon;\n}\n\n/**\n * Modify the coordinates of a polygon to make it a regular polygon.\n * @param {Polygon} polygon Polygon geometry.\n * @param {import(\"../coordinate.js\").Coordinate} center Center of the regular polygon.\n * @param {number} radius Radius of the regular polygon.\n * @param {number} [angle] Start angle for the first vertex of the polygon in\n * counter-clockwise radians. 0 means East. Default is 0.\n */\nexport function makeRegular(polygon, center, radius, angle) {\n const flatCoordinates = polygon.getFlatCoordinates();\n const stride = polygon.getStride();\n const sides = flatCoordinates.length / stride - 1;\n const startAngle = angle ? angle : 0;\n for (let i = 0; i <= sides; ++i) {\n const offset = i * stride;\n const angle = startAngle + (modulo(i, sides) * 2 * Math.PI) / sides;\n flatCoordinates[offset] = center[0] + radius * Math.cos(angle);\n flatCoordinates[offset + 1] = center[1] + radius * Math.sin(angle);\n }\n polygon.changed();\n}\n","/**\n * @module ol/View\n */\nimport BaseObject from './Object.js';\nimport ViewHint from './ViewHint.js';\nimport ViewProperty from './ViewProperty.js';\nimport {DEFAULT_TILE_SIZE} from './tilegrid/common.js';\nimport {\n METERS_PER_UNIT,\n createProjection,\n disableCoordinateWarning,\n fromUserCoordinate,\n fromUserExtent,\n getUserProjection,\n toUserCoordinate,\n toUserExtent,\n} from './proj.js';\nimport {VOID} from './functions.js';\nimport {\n add as addCoordinate,\n equals as coordinatesEqual,\n equals,\n rotate as rotateCoordinate,\n} from './coordinate.js';\nimport {assert} from './asserts.js';\nimport {none as centerNone, createExtent} from './centerconstraint.js';\nimport {clamp, modulo} from './math.js';\nimport {\n createMinMaxResolution,\n createSnapToPower,\n createSnapToResolutions,\n} from './resolutionconstraint.js';\nimport {\n createSnapToN,\n createSnapToZero,\n disable,\n none as rotationNone,\n} from './rotationconstraint.js';\nimport {easeOut, inAndOut} from './easing.js';\nimport {\n getCenter,\n getForViewAndSize,\n getHeight,\n getWidth,\n isEmpty,\n} from './extent.js';\nimport {linearFindNearest} from './array.js';\nimport {fromExtent as polygonFromExtent} from './geom/Polygon.js';\n\n/**\n * An animation configuration\n *\n * @typedef {Object} Animation\n * @property {import(\"./coordinate.js\").Coordinate} [sourceCenter] Source center.\n * @property {import(\"./coordinate.js\").Coordinate} [targetCenter] Target center.\n * @property {number} [sourceResolution] Source resolution.\n * @property {number} [targetResolution] Target resolution.\n * @property {number} [sourceRotation] Source rotation.\n * @property {number} [targetRotation] Target rotation.\n * @property {import(\"./coordinate.js\").Coordinate} [anchor] Anchor.\n * @property {number} start Start.\n * @property {number} duration Duration.\n * @property {boolean} complete Complete.\n * @property {function(number):number} easing Easing.\n * @property {function(boolean):void} callback Callback.\n */\n\n/**\n * @typedef {Object} Constraints\n * @property {import(\"./centerconstraint.js\").Type} center Center.\n * @property {import(\"./resolutionconstraint.js\").Type} resolution Resolution.\n * @property {import(\"./rotationconstraint.js\").Type} rotation Rotation.\n */\n\n/**\n * @typedef {Object} FitOptions\n * @property {import(\"./size.js\").Size} [size] The size in pixels of the box to fit\n * the extent into. Default is the current size of the first map in the DOM that\n * uses this view, or `[100, 100]` if no such map is found.\n * @property {!Array} [padding=[0, 0, 0, 0]] Padding (in pixels) to be\n * cleared inside the view. Values in the array are top, right, bottom and left\n * padding.\n * @property {boolean} [nearest=false] If the view `constrainResolution` option is `true`,\n * get the nearest extent instead of the closest that actually fits the view.\n * @property {number} [minResolution=0] Minimum resolution that we zoom to.\n * @property {number} [maxZoom] Maximum zoom level that we zoom to. If\n * `minResolution` is given, this property is ignored.\n * @property {number} [duration] The duration of the animation in milliseconds.\n * By default, there is no animation to the target extent.\n * @property {function(number):number} [easing] The easing function used during\n * the animation (defaults to {@link module:ol/easing.inAndOut}).\n * The function will be called for each frame with a number representing a\n * fraction of the animation's duration. The function should return a number\n * between 0 and 1 representing the progress toward the destination state.\n * @property {function(boolean):void} [callback] Function called when the view is in\n * its final position. The callback will be called with `true` if the animation\n * series completed on its own or `false` if it was cancelled.\n */\n\n/**\n * @typedef {Object} ViewOptions\n * @property {import(\"./coordinate.js\").Coordinate} [center] The initial center for\n * the view. If a user projection is not set, the coordinate system for the center is\n * specified with the `projection` option. Layer sources will not be fetched if this\n * is not set, but the center can be set later with {@link #setCenter}.\n * @property {boolean|number} [constrainRotation=true] Rotation constraint.\n * `false` means no constraint. `true` means no constraint, but snap to zero\n * near zero. A number constrains the rotation to that number of values. For\n * example, `4` will constrain the rotation to 0, 90, 180, and 270 degrees.\n * @property {boolean} [enableRotation=true] Enable rotation.\n * If `false`, a rotation constraint that always sets the rotation to zero is\n * used. The `constrainRotation` option has no effect if `enableRotation` is\n * `false`.\n * @property {import(\"./extent.js\").Extent} [extent] The extent that constrains the\n * view, in other words, nothing outside of this extent can be visible on the map.\n * @property {boolean} [constrainOnlyCenter=false] If true, the extent\n * constraint will only apply to the view center and not the whole extent.\n * @property {boolean} [smoothExtentConstraint=true] If true, the extent\n * constraint will be applied smoothly, i.e. allow the view to go slightly outside\n * of the given `extent`.\n * @property {number} [maxResolution] The maximum resolution used to determine\n * the resolution constraint. It is used together with `minResolution` (or\n * `maxZoom`) and `zoomFactor`. If unspecified it is calculated in such a way\n * that the projection's validity extent fits in a 256x256 px tile. If the\n * projection is Spherical Mercator (the default) then `maxResolution` defaults\n * to `40075016.68557849 / 256 = 156543.03392804097`.\n * @property {number} [minResolution] The minimum resolution used to determine\n * the resolution constraint. It is used together with `maxResolution` (or\n * `minZoom`) and `zoomFactor`. If unspecified it is calculated assuming 29\n * zoom levels (with a factor of 2). If the projection is Spherical Mercator\n * (the default) then `minResolution` defaults to\n * `40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253`.\n * @property {number} [maxZoom=28] The maximum zoom level used to determine the\n * resolution constraint. It is used together with `minZoom` (or\n * `maxResolution`) and `zoomFactor`. Note that if `minResolution` is also\n * provided, it is given precedence over `maxZoom`.\n * @property {number} [minZoom=0] The minimum zoom level used to determine the\n * resolution constraint. It is used together with `maxZoom` (or\n * `minResolution`) and `zoomFactor`. Note that if `maxResolution` is also\n * provided, it is given precedence over `minZoom`.\n * @property {boolean} [multiWorld=false] If `false` the view is constrained so\n * only one world is visible, and you cannot pan off the edge. If `true` the map\n * may show multiple worlds at low zoom levels. Only used if the `projection` is\n * global. Note that if `extent` is also provided it is given precedence.\n * @property {boolean} [constrainResolution=false] If true, the view will always\n * animate to the closest zoom level after an interaction; false means\n * intermediary zoom levels are allowed.\n * @property {boolean} [smoothResolutionConstraint=true] If true, the resolution\n * min/max values will be applied smoothly, i. e. allow the view to exceed slightly\n * the given resolution or zoom bounds.\n * @property {boolean} [showFullExtent=false] Allow the view to be zoomed out to\n * show the full configured extent. By default, when a view is configured with an\n * extent, users will not be able to zoom out so the viewport exceeds the extent in\n * either dimension. This means the full extent may not be visible if the viewport\n * is taller or wider than the aspect ratio of the configured extent. If\n * showFullExtent is true, the user will be able to zoom out so that the viewport\n * exceeds the height or width of the configured extent, but not both, allowing the\n * full extent to be shown.\n * @property {import(\"./proj.js\").ProjectionLike} [projection='EPSG:3857'] The\n * projection. The default is Spherical Mercator.\n * @property {number} [resolution] The initial resolution for the view. The\n * units are `projection` units per pixel (e.g. meters per pixel). An\n * alternative to setting this is to set `zoom`. Layer sources will not be\n * fetched if neither this nor `zoom` are defined, but they can be set later\n * with {@link #setZoom} or {@link #setResolution}.\n * @property {Array} [resolutions] Resolutions that determine the\n * zoom levels if specified. The index in the array corresponds to the zoom level,\n * therefore the resolution values have to be in descending order. It also constrains\n * the resolution by the minimum and maximum value. If set the `maxResolution`,\n * `minResolution`, `minZoom`, `maxZoom`, and `zoomFactor` options are ignored.\n * @property {number} [rotation=0] The initial rotation for the view in radians\n * (positive rotation clockwise, 0 means North).\n * @property {number} [zoom] Only used if `resolution` is not defined. Zoom\n * level used to calculate the initial resolution for the view.\n * @property {number} [zoomFactor=2] The zoom factor used to compute the\n * corresponding resolution.\n * @property {!Array} [padding=[0, 0, 0, 0]] Padding (in css pixels).\n * If the map viewport is partially covered with other content (overlays) along\n * its edges, this setting allows to shift the center of the viewport away from\n * that content. The order of the values is top, right, bottom, left.\n */\n\n/**\n * @typedef {Object} AnimationOptions\n * @property {import(\"./coordinate.js\").Coordinate} [center] The center of the view at the end of\n * the animation.\n * @property {number} [zoom] The zoom level of the view at the end of the\n * animation. This takes precedence over `resolution`.\n * @property {number} [resolution] The resolution of the view at the end\n * of the animation. If `zoom` is also provided, this option will be ignored.\n * @property {number} [rotation] The rotation of the view at the end of\n * the animation.\n * @property {import(\"./coordinate.js\").Coordinate} [anchor] Optional anchor to remain fixed\n * during a rotation or resolution animation.\n * @property {number} [duration=1000] The duration of the animation in milliseconds.\n * @property {function(number):number} [easing] The easing function used\n * during the animation (defaults to {@link module:ol/easing.inAndOut}).\n * The function will be called for each frame with a number representing a\n * fraction of the animation's duration. The function should return a number\n * between 0 and 1 representing the progress toward the destination state.\n */\n\n/**\n * @typedef {Object} State\n * @property {import(\"./coordinate.js\").Coordinate} center Center (in view projection coordinates).\n * @property {import(\"./proj/Projection.js\").default} projection Projection.\n * @property {number} resolution Resolution.\n * @property {import(\"./coordinate.js\").Coordinate} [nextCenter] The next center during an animation series.\n * @property {number} [nextResolution] The next resolution during an animation series.\n * @property {number} [nextRotation] The next rotation during an animation series.\n * @property {number} rotation Rotation.\n * @property {number} zoom Zoom.\n */\n\n/**\n * Like {@link import(\"./Map.js\").FrameState}, but just `viewState` and `extent`.\n * @typedef {Object} ViewStateLayerStateExtent\n * @property {State} viewState View state.\n * @property {import(\"./extent.js\").Extent} extent Extent (in user projection coordinates).\n * @property {Array} [layerStatesArray] Layer states.\n */\n\n/**\n * Default min zoom level for the map view.\n * @type {number}\n */\nconst DEFAULT_MIN_ZOOM = 0;\n\n/**\n * @typedef {import(\"./ObjectEventType\").Types|'change:center'|'change:resolution'|'change:rotation'} ViewObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} ViewOnSignature\n */\n\n/**\n * @classdesc\n * A View object represents a simple 2D view of the map.\n *\n * This is the object to act upon to change the center, resolution,\n * and rotation of the map.\n *\n * A View has a `projection`. The projection determines the\n * coordinate system of the center, and its units determine the units of the\n * resolution (projection units per pixel). The default projection is\n * Web Mercator (EPSG:3857).\n *\n * ### The view states\n *\n * A View is determined by three states: `center`, `resolution`,\n * and `rotation`. Each state has a corresponding getter and setter, e.g.\n * `getCenter` and `setCenter` for the `center` state.\n *\n * The `zoom` state is actually not saved on the view: all computations\n * internally use the `resolution` state. Still, the `setZoom` and `getZoom`\n * methods are available, as well as `getResolutionForZoom` and\n * `getZoomForResolution` to switch from one system to the other.\n *\n * ### The constraints\n *\n * `setCenter`, `setResolution` and `setRotation` can be used to change the\n * states of the view, but any constraint defined in the constructor will\n * be applied along the way.\n *\n * A View object can have a *resolution constraint*, a *rotation constraint*\n * and a *center constraint*.\n *\n * The *resolution constraint* typically restricts min/max values and\n * snaps to specific resolutions. It is determined by the following\n * options: `resolutions`, `maxResolution`, `maxZoom` and `zoomFactor`.\n * If `resolutions` is set, the other three options are ignored. See\n * documentation for each option for more information. By default, the view\n * only has a min/max restriction and allow intermediary zoom levels when\n * pinch-zooming for example.\n *\n * The *rotation constraint* snaps to specific angles. It is determined\n * by the following options: `enableRotation` and `constrainRotation`.\n * By default rotation is allowed and its value is snapped to zero when approaching the\n * horizontal.\n *\n * The *center constraint* is determined by the `extent` option. By\n * default the view center is not constrained at all.\n *\n * ### Changing the view state\n *\n * It is important to note that `setZoom`, `setResolution`, `setCenter` and\n * `setRotation` are subject to the above mentioned constraints. As such, it\n * may sometimes not be possible to know in advance the resulting state of the\n * View. For example, calling `setResolution(10)` does not guarantee that\n * `getResolution()` will return `10`.\n *\n * A consequence of this is that, when applying a delta on the view state, one\n * should use `adjustCenter`, `adjustRotation`, `adjustZoom` and `adjustResolution`\n * rather than the corresponding setters. This will let view do its internal\n * computations. Besides, the `adjust*` methods also take an `anchor`\n * argument which allows specifying an origin for the transformation.\n *\n * ### Interacting with the view\n *\n * View constraints are usually only applied when the view is *at rest*, meaning that\n * no interaction or animation is ongoing. As such, if the user puts the view in a\n * state that is not equivalent to a constrained one (e.g. rotating the view when\n * the snap angle is 0), an animation will be triggered at the interaction end to\n * put back the view to a stable state;\n *\n * @api\n */\nclass View extends BaseObject {\n /**\n * @param {ViewOptions} [options] View options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {ViewOnSignature}\n */\n this.on;\n\n /***\n * @type {ViewOnSignature}\n */\n this.once;\n\n /***\n * @type {ViewOnSignature}\n */\n this.un;\n\n options = Object.assign({}, options);\n\n /**\n * @private\n * @type {Array}\n */\n this.hints_ = [0, 0];\n\n /**\n * @private\n * @type {Array>}\n */\n this.animations_ = [];\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.updateAnimationKey_;\n\n /**\n * @private\n * @const\n * @type {import(\"./proj/Projection.js\").default}\n */\n this.projection_ = createProjection(options.projection, 'EPSG:3857');\n\n /**\n * @private\n * @type {import(\"./size.js\").Size}\n */\n this.viewportSize_ = [100, 100];\n\n /**\n * @private\n * @type {import(\"./coordinate.js\").Coordinate|undefined}\n */\n this.targetCenter_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.targetResolution_;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.targetRotation_;\n\n /**\n * @private\n * @type {import(\"./coordinate.js\").Coordinate}\n */\n this.nextCenter_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.nextResolution_;\n\n /**\n * @private\n * @type {number}\n */\n this.nextRotation_;\n\n /**\n * @private\n * @type {import(\"./coordinate.js\").Coordinate|undefined}\n */\n this.cancelAnchor_ = undefined;\n\n if (options.projection) {\n disableCoordinateWarning();\n }\n if (options.center) {\n options.center = fromUserCoordinate(options.center, this.projection_);\n }\n if (options.extent) {\n options.extent = fromUserExtent(options.extent, this.projection_);\n }\n\n this.applyOptions_(options);\n }\n\n /**\n * Set up the view with the given options.\n * @param {ViewOptions} options View options.\n */\n applyOptions_(options) {\n const properties = Object.assign({}, options);\n for (const key in ViewProperty) {\n delete properties[key];\n }\n this.setProperties(properties, true);\n\n const resolutionConstraintInfo = createResolutionConstraint(options);\n\n /**\n * @private\n * @type {number}\n */\n this.maxResolution_ = resolutionConstraintInfo.maxResolution;\n\n /**\n * @private\n * @type {number}\n */\n this.minResolution_ = resolutionConstraintInfo.minResolution;\n\n /**\n * @private\n * @type {number}\n */\n this.zoomFactor_ = resolutionConstraintInfo.zoomFactor;\n\n /**\n * @private\n * @type {Array|undefined}\n */\n this.resolutions_ = options.resolutions;\n\n /**\n * @type {Array|undefined}\n * @private\n */\n this.padding_ = options.padding;\n\n /**\n * @private\n * @type {number}\n */\n this.minZoom_ = resolutionConstraintInfo.minZoom;\n\n const centerConstraint = createCenterConstraint(options);\n const resolutionConstraint = resolutionConstraintInfo.constraint;\n const rotationConstraint = createRotationConstraint(options);\n\n /**\n * @private\n * @type {Constraints}\n */\n this.constraints_ = {\n center: centerConstraint,\n resolution: resolutionConstraint,\n rotation: rotationConstraint,\n };\n\n this.setRotation(options.rotation !== undefined ? options.rotation : 0);\n this.setCenterInternal(\n options.center !== undefined ? options.center : null\n );\n if (options.resolution !== undefined) {\n this.setResolution(options.resolution);\n } else if (options.zoom !== undefined) {\n this.setZoom(options.zoom);\n }\n }\n\n /**\n * Padding (in css pixels).\n * If the map viewport is partially covered with other content (overlays) along\n * its edges, this setting allows to shift the center of the viewport away from that\n * content. The order of the values in the array is top, right, bottom, left.\n * The default is no padding, which is equivalent to `[0, 0, 0, 0]`.\n * @type {Array|undefined}\n * @api\n */\n get padding() {\n return this.padding_;\n }\n set padding(padding) {\n let oldPadding = this.padding_;\n this.padding_ = padding;\n const center = this.getCenterInternal();\n if (center) {\n const newPadding = padding || [0, 0, 0, 0];\n oldPadding = oldPadding || [0, 0, 0, 0];\n const resolution = this.getResolution();\n const offsetX =\n (resolution / 2) *\n (newPadding[3] - oldPadding[3] + oldPadding[1] - newPadding[1]);\n const offsetY =\n (resolution / 2) *\n (newPadding[0] - oldPadding[0] + oldPadding[2] - newPadding[2]);\n this.setCenterInternal([center[0] + offsetX, center[1] - offsetY]);\n }\n }\n\n /**\n * Get an updated version of the view options used to construct the view. The\n * current resolution (or zoom), center, and rotation are applied to any stored\n * options. The provided options can be used to apply new min/max zoom or\n * resolution limits.\n * @param {ViewOptions} newOptions New options to be applied.\n * @return {ViewOptions} New options updated with the current view state.\n */\n getUpdatedOptions_(newOptions) {\n const options = this.getProperties();\n\n // preserve resolution (or zoom)\n if (options.resolution !== undefined) {\n options.resolution = this.getResolution();\n } else {\n options.zoom = this.getZoom();\n }\n\n // preserve center\n options.center = this.getCenterInternal();\n\n // preserve rotation\n options.rotation = this.getRotation();\n\n return Object.assign({}, options, newOptions);\n }\n\n /**\n * Animate the view. The view's center, zoom (or resolution), and rotation\n * can be animated for smooth transitions between view states. For example,\n * to animate the view to a new zoom level:\n *\n * view.animate({zoom: view.getZoom() + 1});\n *\n * By default, the animation lasts one second and uses in-and-out easing. You\n * can customize this behavior by including `duration` (in milliseconds) and\n * `easing` options (see {@link module:ol/easing}).\n *\n * To chain together multiple animations, call the method with multiple\n * animation objects. For example, to first zoom and then pan:\n *\n * view.animate({zoom: 10}, {center: [0, 0]});\n *\n * If you provide a function as the last argument to the animate method, it\n * will get called at the end of an animation series. The callback will be\n * called with `true` if the animation series completed on its own or `false`\n * if it was cancelled.\n *\n * Animations are cancelled by user interactions (e.g. dragging the map) or by\n * calling `view.setCenter()`, `view.setResolution()`, or `view.setRotation()`\n * (or another method that calls one of these).\n *\n * @param {...(AnimationOptions|function(boolean): void)} var_args Animation\n * options. Multiple animations can be run in series by passing multiple\n * options objects. To run multiple animations in parallel, call the method\n * multiple times. An optional callback can be provided as a final\n * argument. The callback will be called with a boolean indicating whether\n * the animation completed without being cancelled.\n * @api\n */\n animate(var_args) {\n if (this.isDef() && !this.getAnimating()) {\n this.resolveConstraints(0);\n }\n const args = new Array(arguments.length);\n for (let i = 0; i < args.length; ++i) {\n let options = arguments[i];\n if (options.center) {\n options = Object.assign({}, options);\n options.center = fromUserCoordinate(\n options.center,\n this.getProjection()\n );\n }\n if (options.anchor) {\n options = Object.assign({}, options);\n options.anchor = fromUserCoordinate(\n options.anchor,\n this.getProjection()\n );\n }\n args[i] = options;\n }\n this.animateInternal.apply(this, args);\n }\n\n /**\n * @param {...(AnimationOptions|function(boolean): void)} var_args Animation options.\n */\n animateInternal(var_args) {\n let animationCount = arguments.length;\n let callback;\n if (\n animationCount > 1 &&\n typeof arguments[animationCount - 1] === 'function'\n ) {\n callback = arguments[animationCount - 1];\n --animationCount;\n }\n\n let i = 0;\n for (; i < animationCount && !this.isDef(); ++i) {\n // if view properties are not yet set, shortcut to the final state\n const state = arguments[i];\n if (state.center) {\n this.setCenterInternal(state.center);\n }\n if (state.zoom !== undefined) {\n this.setZoom(state.zoom);\n } else if (state.resolution) {\n this.setResolution(state.resolution);\n }\n if (state.rotation !== undefined) {\n this.setRotation(state.rotation);\n }\n }\n if (i === animationCount) {\n if (callback) {\n animationCallback(callback, true);\n }\n return;\n }\n\n let start = Date.now();\n let center = this.targetCenter_.slice();\n let resolution = this.targetResolution_;\n let rotation = this.targetRotation_;\n const series = [];\n for (; i < animationCount; ++i) {\n const options = /** @type {AnimationOptions} */ (arguments[i]);\n\n const animation = {\n start: start,\n complete: false,\n anchor: options.anchor,\n duration: options.duration !== undefined ? options.duration : 1000,\n easing: options.easing || inAndOut,\n callback: callback,\n };\n\n if (options.center) {\n animation.sourceCenter = center;\n animation.targetCenter = options.center.slice();\n center = animation.targetCenter;\n }\n\n if (options.zoom !== undefined) {\n animation.sourceResolution = resolution;\n animation.targetResolution = this.getResolutionForZoom(options.zoom);\n resolution = animation.targetResolution;\n } else if (options.resolution) {\n animation.sourceResolution = resolution;\n animation.targetResolution = options.resolution;\n resolution = animation.targetResolution;\n }\n\n if (options.rotation !== undefined) {\n animation.sourceRotation = rotation;\n const delta =\n modulo(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI;\n animation.targetRotation = rotation + delta;\n rotation = animation.targetRotation;\n }\n\n // check if animation is a no-op\n if (isNoopAnimation(animation)) {\n animation.complete = true;\n // we still push it onto the series for callback handling\n } else {\n start += animation.duration;\n }\n series.push(animation);\n }\n this.animations_.push(series);\n this.setHint(ViewHint.ANIMATING, 1);\n this.updateAnimations_();\n }\n\n /**\n * Determine if the view is being animated.\n * @return {boolean} The view is being animated.\n * @api\n */\n getAnimating() {\n return this.hints_[ViewHint.ANIMATING] > 0;\n }\n\n /**\n * Determine if the user is interacting with the view, such as panning or zooming.\n * @return {boolean} The view is being interacted with.\n * @api\n */\n getInteracting() {\n return this.hints_[ViewHint.INTERACTING] > 0;\n }\n\n /**\n * Cancel any ongoing animations.\n * @api\n */\n cancelAnimations() {\n this.setHint(ViewHint.ANIMATING, -this.hints_[ViewHint.ANIMATING]);\n let anchor;\n for (let i = 0, ii = this.animations_.length; i < ii; ++i) {\n const series = this.animations_[i];\n if (series[0].callback) {\n animationCallback(series[0].callback, false);\n }\n if (!anchor) {\n for (let j = 0, jj = series.length; j < jj; ++j) {\n const animation = series[j];\n if (!animation.complete) {\n anchor = animation.anchor;\n break;\n }\n }\n }\n }\n this.animations_.length = 0;\n this.cancelAnchor_ = anchor;\n this.nextCenter_ = null;\n this.nextResolution_ = NaN;\n this.nextRotation_ = NaN;\n }\n\n /**\n * Update all animations.\n */\n updateAnimations_() {\n if (this.updateAnimationKey_ !== undefined) {\n cancelAnimationFrame(this.updateAnimationKey_);\n this.updateAnimationKey_ = undefined;\n }\n if (!this.getAnimating()) {\n return;\n }\n const now = Date.now();\n let more = false;\n for (let i = this.animations_.length - 1; i >= 0; --i) {\n const series = this.animations_[i];\n let seriesComplete = true;\n for (let j = 0, jj = series.length; j < jj; ++j) {\n const animation = series[j];\n if (animation.complete) {\n continue;\n }\n const elapsed = now - animation.start;\n let fraction =\n animation.duration > 0 ? elapsed / animation.duration : 1;\n if (fraction >= 1) {\n animation.complete = true;\n fraction = 1;\n } else {\n seriesComplete = false;\n }\n const progress = animation.easing(fraction);\n if (animation.sourceCenter) {\n const x0 = animation.sourceCenter[0];\n const y0 = animation.sourceCenter[1];\n const x1 = animation.targetCenter[0];\n const y1 = animation.targetCenter[1];\n this.nextCenter_ = animation.targetCenter;\n const x = x0 + progress * (x1 - x0);\n const y = y0 + progress * (y1 - y0);\n this.targetCenter_ = [x, y];\n }\n if (animation.sourceResolution && animation.targetResolution) {\n const resolution =\n progress === 1\n ? animation.targetResolution\n : animation.sourceResolution +\n progress *\n (animation.targetResolution - animation.sourceResolution);\n if (animation.anchor) {\n const size = this.getViewportSize_(this.getRotation());\n const constrainedResolution = this.constraints_.resolution(\n resolution,\n 0,\n size,\n true\n );\n this.targetCenter_ = this.calculateCenterZoom(\n constrainedResolution,\n animation.anchor\n );\n }\n this.nextResolution_ = animation.targetResolution;\n this.targetResolution_ = resolution;\n this.applyTargetState_(true);\n }\n if (\n animation.sourceRotation !== undefined &&\n animation.targetRotation !== undefined\n ) {\n const rotation =\n progress === 1\n ? modulo(animation.targetRotation + Math.PI, 2 * Math.PI) -\n Math.PI\n : animation.sourceRotation +\n progress *\n (animation.targetRotation - animation.sourceRotation);\n if (animation.anchor) {\n const constrainedRotation = this.constraints_.rotation(\n rotation,\n true\n );\n this.targetCenter_ = this.calculateCenterRotate(\n constrainedRotation,\n animation.anchor\n );\n }\n this.nextRotation_ = animation.targetRotation;\n this.targetRotation_ = rotation;\n }\n this.applyTargetState_(true);\n more = true;\n if (!animation.complete) {\n break;\n }\n }\n if (seriesComplete) {\n this.animations_[i] = null;\n this.setHint(ViewHint.ANIMATING, -1);\n this.nextCenter_ = null;\n this.nextResolution_ = NaN;\n this.nextRotation_ = NaN;\n const callback = series[0].callback;\n if (callback) {\n animationCallback(callback, true);\n }\n }\n }\n // prune completed series\n this.animations_ = this.animations_.filter(Boolean);\n if (more && this.updateAnimationKey_ === undefined) {\n this.updateAnimationKey_ = requestAnimationFrame(\n this.updateAnimations_.bind(this)\n );\n }\n }\n\n /**\n * @param {number} rotation Target rotation.\n * @param {import(\"./coordinate.js\").Coordinate} anchor Rotation anchor.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center for rotation and anchor.\n */\n calculateCenterRotate(rotation, anchor) {\n let center;\n const currentCenter = this.getCenterInternal();\n if (currentCenter !== undefined) {\n center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]];\n rotateCoordinate(center, rotation - this.getRotation());\n addCoordinate(center, anchor);\n }\n return center;\n }\n\n /**\n * @param {number} resolution Target resolution.\n * @param {import(\"./coordinate.js\").Coordinate} anchor Zoom anchor.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center for resolution and anchor.\n */\n calculateCenterZoom(resolution, anchor) {\n let center;\n const currentCenter = this.getCenterInternal();\n const currentResolution = this.getResolution();\n if (currentCenter !== undefined && currentResolution !== undefined) {\n const x =\n anchor[0] -\n (resolution * (anchor[0] - currentCenter[0])) / currentResolution;\n const y =\n anchor[1] -\n (resolution * (anchor[1] - currentCenter[1])) / currentResolution;\n center = [x, y];\n }\n return center;\n }\n\n /**\n * Returns the current viewport size.\n * @private\n * @param {number} [rotation] Take into account the rotation of the viewport when giving the size\n * @return {import(\"./size.js\").Size} Viewport size or `[100, 100]` when no viewport is found.\n */\n getViewportSize_(rotation) {\n const size = this.viewportSize_;\n if (rotation) {\n const w = size[0];\n const h = size[1];\n return [\n Math.abs(w * Math.cos(rotation)) + Math.abs(h * Math.sin(rotation)),\n Math.abs(w * Math.sin(rotation)) + Math.abs(h * Math.cos(rotation)),\n ];\n }\n return size;\n }\n\n /**\n * Stores the viewport size on the view. The viewport size is not read every time from the DOM\n * to avoid performance hit and layout reflow.\n * This should be done on map size change.\n * Note: the constraints are not resolved during an animation to avoid stopping it\n * @param {import(\"./size.js\").Size} [size] Viewport size; if undefined, [100, 100] is assumed\n */\n setViewportSize(size) {\n this.viewportSize_ = Array.isArray(size) ? size.slice() : [100, 100];\n if (!this.getAnimating()) {\n this.resolveConstraints(0);\n }\n }\n\n /**\n * Get the view center.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} The center of the view.\n * @observable\n * @api\n */\n getCenter() {\n const center = this.getCenterInternal();\n if (!center) {\n return center;\n }\n return toUserCoordinate(center, this.getProjection());\n }\n\n /**\n * Get the view center without transforming to user projection.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} The center of the view.\n */\n getCenterInternal() {\n return /** @type {import(\"./coordinate.js\").Coordinate|undefined} */ (\n this.get(ViewProperty.CENTER)\n );\n }\n\n /**\n * @return {Constraints} Constraints.\n */\n getConstraints() {\n return this.constraints_;\n }\n\n /**\n * @return {boolean} Resolution constraint is set\n */\n getConstrainResolution() {\n return this.get('constrainResolution');\n }\n\n /**\n * @param {Array} [hints] Destination array.\n * @return {Array} Hint.\n */\n getHints(hints) {\n if (hints !== undefined) {\n hints[0] = this.hints_[0];\n hints[1] = this.hints_[1];\n return hints;\n }\n return this.hints_.slice();\n }\n\n /**\n * Calculate the extent for the current view state and the passed size.\n * The size is the pixel dimensions of the box into which the calculated extent\n * should fit. In most cases you want to get the extent of the entire map,\n * that is `map.getSize()`.\n * @param {import(\"./size.js\").Size} [size] Box pixel size. If not provided, the size\n * of the map that uses this view will be used.\n * @return {import(\"./extent.js\").Extent} Extent.\n * @api\n */\n calculateExtent(size) {\n const extent = this.calculateExtentInternal(size);\n return toUserExtent(extent, this.getProjection());\n }\n\n /**\n * @param {import(\"./size.js\").Size} [size] Box pixel size. If not provided,\n * the map's last known viewport size will be used.\n * @return {import(\"./extent.js\").Extent} Extent.\n */\n calculateExtentInternal(size) {\n size = size || this.getViewportSizeMinusPadding_();\n const center = /** @type {!import(\"./coordinate.js\").Coordinate} */ (\n this.getCenterInternal()\n );\n assert(center, 'The view center is not defined');\n const resolution = /** @type {!number} */ (this.getResolution());\n assert(resolution !== undefined, 'The view resolution is not defined');\n const rotation = /** @type {!number} */ (this.getRotation());\n assert(rotation !== undefined, 'The view rotation is not defined');\n\n return getForViewAndSize(center, resolution, rotation, size);\n }\n\n /**\n * Get the maximum resolution of the view.\n * @return {number} The maximum resolution of the view.\n * @api\n */\n getMaxResolution() {\n return this.maxResolution_;\n }\n\n /**\n * Get the minimum resolution of the view.\n * @return {number} The minimum resolution of the view.\n * @api\n */\n getMinResolution() {\n return this.minResolution_;\n }\n\n /**\n * Get the maximum zoom level for the view.\n * @return {number} The maximum zoom level.\n * @api\n */\n getMaxZoom() {\n return /** @type {number} */ (\n this.getZoomForResolution(this.minResolution_)\n );\n }\n\n /**\n * Set a new maximum zoom level for the view.\n * @param {number} zoom The maximum zoom level.\n * @api\n */\n setMaxZoom(zoom) {\n this.applyOptions_(this.getUpdatedOptions_({maxZoom: zoom}));\n }\n\n /**\n * Get the minimum zoom level for the view.\n * @return {number} The minimum zoom level.\n * @api\n */\n getMinZoom() {\n return /** @type {number} */ (\n this.getZoomForResolution(this.maxResolution_)\n );\n }\n\n /**\n * Set a new minimum zoom level for the view.\n * @param {number} zoom The minimum zoom level.\n * @api\n */\n setMinZoom(zoom) {\n this.applyOptions_(this.getUpdatedOptions_({minZoom: zoom}));\n }\n\n /**\n * Set whether the view should allow intermediary zoom levels.\n * @param {boolean} enabled Whether the resolution is constrained.\n * @api\n */\n setConstrainResolution(enabled) {\n this.applyOptions_(this.getUpdatedOptions_({constrainResolution: enabled}));\n }\n\n /**\n * Get the view projection.\n * @return {import(\"./proj/Projection.js\").default} The projection of the view.\n * @api\n */\n getProjection() {\n return this.projection_;\n }\n\n /**\n * Get the view resolution.\n * @return {number|undefined} The resolution of the view.\n * @observable\n * @api\n */\n getResolution() {\n return /** @type {number|undefined} */ (this.get(ViewProperty.RESOLUTION));\n }\n\n /**\n * Get the resolutions for the view. This returns the array of resolutions\n * passed to the constructor of the View, or undefined if none were given.\n * @return {Array|undefined} The resolutions of the view.\n * @api\n */\n getResolutions() {\n return this.resolutions_;\n }\n\n /**\n * Get the resolution for a provided extent (in map units) and size (in pixels).\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {import(\"./size.js\").Size} [size] Box pixel size.\n * @return {number} The resolution at which the provided extent will render at\n * the given size.\n * @api\n */\n getResolutionForExtent(extent, size) {\n return this.getResolutionForExtentInternal(\n fromUserExtent(extent, this.getProjection()),\n size\n );\n }\n\n /**\n * Get the resolution for a provided extent (in map units) and size (in pixels).\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {import(\"./size.js\").Size} [size] Box pixel size.\n * @return {number} The resolution at which the provided extent will render at\n * the given size.\n */\n getResolutionForExtentInternal(extent, size) {\n size = size || this.getViewportSizeMinusPadding_();\n const xResolution = getWidth(extent) / size[0];\n const yResolution = getHeight(extent) / size[1];\n return Math.max(xResolution, yResolution);\n }\n\n /**\n * Return a function that returns a value between 0 and 1 for a\n * resolution. Exponential scaling is assumed.\n * @param {number} [power] Power.\n * @return {function(number): number} Resolution for value function.\n */\n getResolutionForValueFunction(power) {\n power = power || 2;\n const maxResolution = this.getConstrainedResolution(this.maxResolution_);\n const minResolution = this.minResolution_;\n const max = Math.log(maxResolution / minResolution) / Math.log(power);\n return (\n /**\n * @param {number} value Value.\n * @return {number} Resolution.\n */\n function (value) {\n const resolution = maxResolution / Math.pow(power, value * max);\n return resolution;\n }\n );\n }\n\n /**\n * Get the view rotation.\n * @return {number} The rotation of the view in radians.\n * @observable\n * @api\n */\n getRotation() {\n return /** @type {number} */ (this.get(ViewProperty.ROTATION));\n }\n\n /**\n * Return a function that returns a resolution for a value between\n * 0 and 1. Exponential scaling is assumed.\n * @param {number} [power] Power.\n * @return {function(number): number} Value for resolution function.\n */\n getValueForResolutionFunction(power) {\n const logPower = Math.log(power || 2);\n const maxResolution = this.getConstrainedResolution(this.maxResolution_);\n const minResolution = this.minResolution_;\n const max = Math.log(maxResolution / minResolution) / logPower;\n return (\n /**\n * @param {number} resolution Resolution.\n * @return {number} Value.\n */\n function (resolution) {\n const value = Math.log(maxResolution / resolution) / logPower / max;\n return value;\n }\n );\n }\n\n /**\n * Returns the size of the viewport minus padding.\n * @private\n * @param {number} [rotation] Take into account the rotation of the viewport when giving the size\n * @return {import(\"./size.js\").Size} Viewport size reduced by the padding.\n */\n getViewportSizeMinusPadding_(rotation) {\n let size = this.getViewportSize_(rotation);\n const padding = this.padding_;\n if (padding) {\n size = [\n size[0] - padding[1] - padding[3],\n size[1] - padding[0] - padding[2],\n ];\n }\n return size;\n }\n\n /**\n * @return {State} View state.\n */\n getState() {\n const projection = this.getProjection();\n const resolution = this.getResolution();\n const rotation = this.getRotation();\n let center = /** @type {import(\"./coordinate.js\").Coordinate} */ (\n this.getCenterInternal()\n );\n const padding = this.padding_;\n if (padding) {\n const reducedSize = this.getViewportSizeMinusPadding_();\n center = calculateCenterOn(\n center,\n this.getViewportSize_(),\n [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],\n resolution,\n rotation\n );\n }\n return {\n center: center.slice(0),\n projection: projection !== undefined ? projection : null,\n resolution: resolution,\n nextCenter: this.nextCenter_,\n nextResolution: this.nextResolution_,\n nextRotation: this.nextRotation_,\n rotation: rotation,\n zoom: this.getZoom(),\n };\n }\n\n /**\n * @return {ViewStateLayerStateExtent} Like `FrameState`, but just `viewState` and `extent`.\n */\n getViewStateAndExtent() {\n return {\n viewState: this.getState(),\n extent: this.calculateExtent(),\n };\n }\n\n /**\n * Get the current zoom level. This method may return non-integer zoom levels\n * if the view does not constrain the resolution, or if an interaction or\n * animation is underway.\n * @return {number|undefined} Zoom.\n * @api\n */\n getZoom() {\n let zoom;\n const resolution = this.getResolution();\n if (resolution !== undefined) {\n zoom = this.getZoomForResolution(resolution);\n }\n return zoom;\n }\n\n /**\n * Get the zoom level for a resolution.\n * @param {number} resolution The resolution.\n * @return {number|undefined} The zoom level for the provided resolution.\n * @api\n */\n getZoomForResolution(resolution) {\n let offset = this.minZoom_ || 0;\n let max, zoomFactor;\n if (this.resolutions_) {\n const nearest = linearFindNearest(this.resolutions_, resolution, 1);\n offset = nearest;\n max = this.resolutions_[nearest];\n if (nearest == this.resolutions_.length - 1) {\n zoomFactor = 2;\n } else {\n zoomFactor = max / this.resolutions_[nearest + 1];\n }\n } else {\n max = this.maxResolution_;\n zoomFactor = this.zoomFactor_;\n }\n return offset + Math.log(max / resolution) / Math.log(zoomFactor);\n }\n\n /**\n * Get the resolution for a zoom level.\n * @param {number} zoom Zoom level.\n * @return {number} The view resolution for the provided zoom level.\n * @api\n */\n getResolutionForZoom(zoom) {\n if (this.resolutions_) {\n if (this.resolutions_.length <= 1) {\n return 0;\n }\n const baseLevel = clamp(\n Math.floor(zoom),\n 0,\n this.resolutions_.length - 2\n );\n const zoomFactor =\n this.resolutions_[baseLevel] / this.resolutions_[baseLevel + 1];\n return (\n this.resolutions_[baseLevel] /\n Math.pow(zoomFactor, clamp(zoom - baseLevel, 0, 1))\n );\n }\n return (\n this.maxResolution_ / Math.pow(this.zoomFactor_, zoom - this.minZoom_)\n );\n }\n\n /**\n * Fit the given geometry or extent based on the given map size and border.\n * The size is pixel dimensions of the box to fit the extent into.\n * In most cases you will want to use the map size, that is `map.getSize()`.\n * Takes care of the map angle.\n * @param {import(\"./geom/SimpleGeometry.js\").default|import(\"./extent.js\").Extent} geometryOrExtent The geometry or\n * extent to fit the view to.\n * @param {FitOptions} [options] Options.\n * @api\n */\n fit(geometryOrExtent, options) {\n /** @type {import(\"./geom/SimpleGeometry.js\").default} */\n let geometry;\n assert(\n Array.isArray(geometryOrExtent) ||\n typeof (/** @type {?} */ (geometryOrExtent).getSimplifiedGeometry) ===\n 'function',\n 'Invalid extent or geometry provided as `geometry`'\n );\n if (Array.isArray(geometryOrExtent)) {\n assert(\n !isEmpty(geometryOrExtent),\n 'Cannot fit empty extent provided as `geometry`'\n );\n const extent = fromUserExtent(geometryOrExtent, this.getProjection());\n geometry = polygonFromExtent(extent);\n } else if (geometryOrExtent.getType() === 'Circle') {\n const extent = fromUserExtent(\n geometryOrExtent.getExtent(),\n this.getProjection()\n );\n geometry = polygonFromExtent(extent);\n geometry.rotate(this.getRotation(), getCenter(extent));\n } else {\n const userProjection = getUserProjection();\n if (userProjection) {\n geometry = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometryOrExtent\n .clone()\n .transform(userProjection, this.getProjection())\n );\n } else {\n geometry = geometryOrExtent;\n }\n }\n\n this.fitInternal(geometry, options);\n }\n\n /**\n * Calculate rotated extent\n * @param {import(\"./geom/SimpleGeometry.js\").default} geometry The geometry.\n * @return {import(\"./extent\").Extent} The rotated extent for the geometry.\n */\n rotatedExtentForGeometry(geometry) {\n const rotation = this.getRotation();\n const cosAngle = Math.cos(rotation);\n const sinAngle = Math.sin(-rotation);\n const coords = geometry.getFlatCoordinates();\n const stride = geometry.getStride();\n let minRotX = +Infinity;\n let minRotY = +Infinity;\n let maxRotX = -Infinity;\n let maxRotY = -Infinity;\n for (let i = 0, ii = coords.length; i < ii; i += stride) {\n const rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle;\n const rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle;\n minRotX = Math.min(minRotX, rotX);\n minRotY = Math.min(minRotY, rotY);\n maxRotX = Math.max(maxRotX, rotX);\n maxRotY = Math.max(maxRotY, rotY);\n }\n return [minRotX, minRotY, maxRotX, maxRotY];\n }\n\n /**\n * @param {import(\"./geom/SimpleGeometry.js\").default} geometry The geometry.\n * @param {FitOptions} [options] Options.\n */\n fitInternal(geometry, options) {\n options = options || {};\n let size = options.size;\n if (!size) {\n size = this.getViewportSizeMinusPadding_();\n }\n const padding =\n options.padding !== undefined ? options.padding : [0, 0, 0, 0];\n const nearest = options.nearest !== undefined ? options.nearest : false;\n let minResolution;\n if (options.minResolution !== undefined) {\n minResolution = options.minResolution;\n } else if (options.maxZoom !== undefined) {\n minResolution = this.getResolutionForZoom(options.maxZoom);\n } else {\n minResolution = 0;\n }\n\n const rotatedExtent = this.rotatedExtentForGeometry(geometry);\n\n // calculate resolution\n let resolution = this.getResolutionForExtentInternal(rotatedExtent, [\n size[0] - padding[1] - padding[3],\n size[1] - padding[0] - padding[2],\n ]);\n resolution = isNaN(resolution)\n ? minResolution\n : Math.max(resolution, minResolution);\n resolution = this.getConstrainedResolution(resolution, nearest ? 0 : 1);\n\n // calculate center\n const rotation = this.getRotation();\n const sinAngle = Math.sin(rotation);\n const cosAngle = Math.cos(rotation);\n const centerRot = getCenter(rotatedExtent);\n centerRot[0] += ((padding[1] - padding[3]) / 2) * resolution;\n centerRot[1] += ((padding[0] - padding[2]) / 2) * resolution;\n const centerX = centerRot[0] * cosAngle - centerRot[1] * sinAngle;\n const centerY = centerRot[1] * cosAngle + centerRot[0] * sinAngle;\n const center = this.getConstrainedCenter([centerX, centerY], resolution);\n const callback = options.callback ? options.callback : VOID;\n\n if (options.duration !== undefined) {\n this.animateInternal(\n {\n resolution: resolution,\n center: center,\n duration: options.duration,\n easing: options.easing,\n },\n callback\n );\n } else {\n this.targetResolution_ = resolution;\n this.targetCenter_ = center;\n this.applyTargetState_(false, true);\n animationCallback(callback, true);\n }\n }\n\n /**\n * Center on coordinate and view position.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"./size.js\").Size} size Box pixel size.\n * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n * @api\n */\n centerOn(coordinate, size, position) {\n this.centerOnInternal(\n fromUserCoordinate(coordinate, this.getProjection()),\n size,\n position\n );\n }\n\n /**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"./size.js\").Size} size Box pixel size.\n * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n */\n centerOnInternal(coordinate, size, position) {\n this.setCenterInternal(\n calculateCenterOn(\n coordinate,\n size,\n position,\n this.getResolution(),\n this.getRotation()\n )\n );\n }\n\n /**\n * Calculates the shift between map and viewport center.\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @return {Array|undefined} Center shift.\n */\n calculateCenterShift(center, resolution, rotation, size) {\n let centerShift;\n const padding = this.padding_;\n if (padding && center) {\n const reducedSize = this.getViewportSizeMinusPadding_(-rotation);\n const shiftedCenter = calculateCenterOn(\n center,\n size,\n [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],\n resolution,\n rotation\n );\n centerShift = [\n center[0] - shiftedCenter[0],\n center[1] - shiftedCenter[1],\n ];\n }\n return centerShift;\n }\n\n /**\n * @return {boolean} Is defined.\n */\n isDef() {\n return !!this.getCenterInternal() && this.getResolution() !== undefined;\n }\n\n /**\n * Adds relative coordinates to the center of the view. Any extent constraint will apply.\n * @param {import(\"./coordinate.js\").Coordinate} deltaCoordinates Relative value to add.\n * @api\n */\n adjustCenter(deltaCoordinates) {\n const center = toUserCoordinate(this.targetCenter_, this.getProjection());\n this.setCenter([\n center[0] + deltaCoordinates[0],\n center[1] + deltaCoordinates[1],\n ]);\n }\n\n /**\n * Adds relative coordinates to the center of the view. Any extent constraint will apply.\n * @param {import(\"./coordinate.js\").Coordinate} deltaCoordinates Relative value to add.\n */\n adjustCenterInternal(deltaCoordinates) {\n const center = this.targetCenter_;\n this.setCenterInternal([\n center[0] + deltaCoordinates[0],\n center[1] + deltaCoordinates[1],\n ]);\n }\n\n /**\n * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution\n * constraint will apply.\n * @param {number} ratio The ratio to apply on the view resolution.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n * @api\n */\n adjustResolution(ratio, anchor) {\n anchor = anchor && fromUserCoordinate(anchor, this.getProjection());\n this.adjustResolutionInternal(ratio, anchor);\n }\n\n /**\n * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution\n * constraint will apply.\n * @param {number} ratio The ratio to apply on the view resolution.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n */\n adjustResolutionInternal(ratio, anchor) {\n const isMoving = this.getAnimating() || this.getInteracting();\n const size = this.getViewportSize_(this.getRotation());\n const newResolution = this.constraints_.resolution(\n this.targetResolution_ * ratio,\n 0,\n size,\n isMoving\n );\n\n if (anchor) {\n this.targetCenter_ = this.calculateCenterZoom(newResolution, anchor);\n }\n\n this.targetResolution_ *= ratio;\n this.applyTargetState_();\n }\n\n /**\n * Adds a value to the view zoom level, optionally using an anchor. Any resolution\n * constraint will apply.\n * @param {number} delta Relative value to add to the zoom level.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n * @api\n */\n adjustZoom(delta, anchor) {\n this.adjustResolution(Math.pow(this.zoomFactor_, -delta), anchor);\n }\n\n /**\n * Adds a value to the view rotation, optionally using an anchor. Any rotation\n * constraint will apply.\n * @param {number} delta Relative value to add to the zoom rotation, in radians.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The rotation center.\n * @api\n */\n adjustRotation(delta, anchor) {\n if (anchor) {\n anchor = fromUserCoordinate(anchor, this.getProjection());\n }\n this.adjustRotationInternal(delta, anchor);\n }\n\n /**\n * @param {number} delta Relative value to add to the zoom rotation, in radians.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The rotation center.\n */\n adjustRotationInternal(delta, anchor) {\n const isMoving = this.getAnimating() || this.getInteracting();\n const newRotation = this.constraints_.rotation(\n this.targetRotation_ + delta,\n isMoving\n );\n if (anchor) {\n this.targetCenter_ = this.calculateCenterRotate(newRotation, anchor);\n }\n this.targetRotation_ += delta;\n this.applyTargetState_();\n }\n\n /**\n * Set the center of the current view. Any extent constraint will apply.\n * @param {import(\"./coordinate.js\").Coordinate|undefined} center The center of the view.\n * @observable\n * @api\n */\n setCenter(center) {\n this.setCenterInternal(\n center ? fromUserCoordinate(center, this.getProjection()) : center\n );\n }\n\n /**\n * Set the center using the view projection (not the user projection).\n * @param {import(\"./coordinate.js\").Coordinate|undefined} center The center of the view.\n */\n setCenterInternal(center) {\n this.targetCenter_ = center;\n this.applyTargetState_();\n }\n\n /**\n * @param {import(\"./ViewHint.js\").default} hint Hint.\n * @param {number} delta Delta.\n * @return {number} New value.\n */\n setHint(hint, delta) {\n this.hints_[hint] += delta;\n this.changed();\n return this.hints_[hint];\n }\n\n /**\n * Set the resolution for this view. Any resolution constraint will apply.\n * @param {number|undefined} resolution The resolution of the view.\n * @observable\n * @api\n */\n setResolution(resolution) {\n this.targetResolution_ = resolution;\n this.applyTargetState_();\n }\n\n /**\n * Set the rotation for this view. Any rotation constraint will apply.\n * @param {number} rotation The rotation of the view in radians.\n * @observable\n * @api\n */\n setRotation(rotation) {\n this.targetRotation_ = rotation;\n this.applyTargetState_();\n }\n\n /**\n * Zoom to a specific zoom level. Any resolution constrain will apply.\n * @param {number} zoom Zoom level.\n * @api\n */\n setZoom(zoom) {\n this.setResolution(this.getResolutionForZoom(zoom));\n }\n\n /**\n * Recompute rotation/resolution/center based on target values.\n * Note: we have to compute rotation first, then resolution and center considering that\n * parameters can influence one another in case a view extent constraint is present.\n * @param {boolean} [doNotCancelAnims] Do not cancel animations.\n * @param {boolean} [forceMoving] Apply constraints as if the view is moving.\n * @private\n */\n applyTargetState_(doNotCancelAnims, forceMoving) {\n const isMoving =\n this.getAnimating() || this.getInteracting() || forceMoving;\n\n // compute rotation\n const newRotation = this.constraints_.rotation(\n this.targetRotation_,\n isMoving\n );\n const size = this.getViewportSize_(newRotation);\n const newResolution = this.constraints_.resolution(\n this.targetResolution_,\n 0,\n size,\n isMoving\n );\n const newCenter = this.constraints_.center(\n this.targetCenter_,\n newResolution,\n size,\n isMoving,\n this.calculateCenterShift(\n this.targetCenter_,\n newResolution,\n newRotation,\n size\n )\n );\n\n if (this.get(ViewProperty.ROTATION) !== newRotation) {\n this.set(ViewProperty.ROTATION, newRotation);\n }\n if (this.get(ViewProperty.RESOLUTION) !== newResolution) {\n this.set(ViewProperty.RESOLUTION, newResolution);\n this.set('zoom', this.getZoom(), true);\n }\n if (\n !newCenter ||\n !this.get(ViewProperty.CENTER) ||\n !equals(this.get(ViewProperty.CENTER), newCenter)\n ) {\n this.set(ViewProperty.CENTER, newCenter);\n }\n\n if (this.getAnimating() && !doNotCancelAnims) {\n this.cancelAnimations();\n }\n this.cancelAnchor_ = undefined;\n }\n\n /**\n * If any constraints need to be applied, an animation will be triggered.\n * This is typically done on interaction end.\n * Note: calling this with a duration of 0 will apply the constrained values straight away,\n * without animation.\n * @param {number} [duration] The animation duration in ms.\n * @param {number} [resolutionDirection] Which direction to zoom.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n */\n resolveConstraints(duration, resolutionDirection, anchor) {\n duration = duration !== undefined ? duration : 200;\n const direction = resolutionDirection || 0;\n\n const newRotation = this.constraints_.rotation(this.targetRotation_);\n const size = this.getViewportSize_(newRotation);\n const newResolution = this.constraints_.resolution(\n this.targetResolution_,\n direction,\n size\n );\n const newCenter = this.constraints_.center(\n this.targetCenter_,\n newResolution,\n size,\n false,\n this.calculateCenterShift(\n this.targetCenter_,\n newResolution,\n newRotation,\n size\n )\n );\n\n if (duration === 0 && !this.cancelAnchor_) {\n this.targetResolution_ = newResolution;\n this.targetRotation_ = newRotation;\n this.targetCenter_ = newCenter;\n this.applyTargetState_();\n return;\n }\n\n anchor = anchor || (duration === 0 ? this.cancelAnchor_ : undefined);\n this.cancelAnchor_ = undefined;\n\n if (\n this.getResolution() !== newResolution ||\n this.getRotation() !== newRotation ||\n !this.getCenterInternal() ||\n !equals(this.getCenterInternal(), newCenter)\n ) {\n if (this.getAnimating()) {\n this.cancelAnimations();\n }\n\n this.animateInternal({\n rotation: newRotation,\n center: newCenter,\n resolution: newResolution,\n duration: duration,\n easing: easeOut,\n anchor: anchor,\n });\n }\n }\n\n /**\n * Notify the View that an interaction has started.\n * The view state will be resolved to a stable one if needed\n * (depending on its constraints).\n * @api\n */\n beginInteraction() {\n this.resolveConstraints(0);\n\n this.setHint(ViewHint.INTERACTING, 1);\n }\n\n /**\n * Notify the View that an interaction has ended. The view state will be resolved\n * to a stable one if needed (depending on its constraints).\n * @param {number} [duration] Animation duration in ms.\n * @param {number} [resolutionDirection] Which direction to zoom.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n * @api\n */\n endInteraction(duration, resolutionDirection, anchor) {\n anchor = anchor && fromUserCoordinate(anchor, this.getProjection());\n this.endInteractionInternal(duration, resolutionDirection, anchor);\n }\n\n /**\n * Notify the View that an interaction has ended. The view state will be resolved\n * to a stable one if needed (depending on its constraints).\n * @param {number} [duration] Animation duration in ms.\n * @param {number} [resolutionDirection] Which direction to zoom.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n */\n endInteractionInternal(duration, resolutionDirection, anchor) {\n if (!this.getInteracting()) {\n return;\n }\n this.setHint(ViewHint.INTERACTING, -1);\n this.resolveConstraints(duration, resolutionDirection, anchor);\n }\n\n /**\n * Get a valid position for the view center according to the current constraints.\n * @param {import(\"./coordinate.js\").Coordinate|undefined} targetCenter Target center position.\n * @param {number} [targetResolution] Target resolution. If not supplied, the current one will be used.\n * This is useful to guess a valid center position at a different zoom level.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Valid center position.\n */\n getConstrainedCenter(targetCenter, targetResolution) {\n const size = this.getViewportSize_(this.getRotation());\n return this.constraints_.center(\n targetCenter,\n targetResolution || this.getResolution(),\n size\n );\n }\n\n /**\n * Get a valid zoom level according to the current view constraints.\n * @param {number|undefined} targetZoom Target zoom.\n * @param {number} [direction=0] Indicate which resolution should be used\n * by a renderer if the view resolution does not match any resolution of the tile source.\n * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n * will be used. If -1, the nearest higher resolution will be used.\n * @return {number|undefined} Valid zoom level.\n */\n getConstrainedZoom(targetZoom, direction) {\n const targetRes = this.getResolutionForZoom(targetZoom);\n return this.getZoomForResolution(\n this.getConstrainedResolution(targetRes, direction)\n );\n }\n\n /**\n * Get a valid resolution according to the current view constraints.\n * @param {number|undefined} targetResolution Target resolution.\n * @param {number} [direction=0] Indicate which resolution should be used\n * by a renderer if the view resolution does not match any resolution of the tile source.\n * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n * will be used. If -1, the nearest higher resolution will be used.\n * @return {number|undefined} Valid resolution.\n */\n getConstrainedResolution(targetResolution, direction) {\n direction = direction || 0;\n const size = this.getViewportSize_(this.getRotation());\n\n return this.constraints_.resolution(targetResolution, direction, size);\n }\n}\n\n/**\n * @param {Function} callback Callback.\n * @param {*} returnValue Return value.\n */\nfunction animationCallback(callback, returnValue) {\n setTimeout(function () {\n callback(returnValue);\n }, 0);\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {import(\"./centerconstraint.js\").Type} The constraint.\n */\nexport function createCenterConstraint(options) {\n if (options.extent !== undefined) {\n const smooth =\n options.smoothExtentConstraint !== undefined\n ? options.smoothExtentConstraint\n : true;\n return createExtent(options.extent, options.constrainOnlyCenter, smooth);\n }\n\n const projection = createProjection(options.projection, 'EPSG:3857');\n if (options.multiWorld !== true && projection.isGlobal()) {\n const extent = projection.getExtent().slice();\n extent[0] = -Infinity;\n extent[2] = Infinity;\n return createExtent(extent, false, false);\n }\n\n return centerNone;\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {{constraint: import(\"./resolutionconstraint.js\").Type, maxResolution: number,\n * minResolution: number, minZoom: number, zoomFactor: number}} The constraint.\n */\nexport function createResolutionConstraint(options) {\n let resolutionConstraint;\n let maxResolution;\n let minResolution;\n\n // TODO: move these to be ol constants\n // see https://github.com/openlayers/openlayers/issues/2076\n const defaultMaxZoom = 28;\n const defaultZoomFactor = 2;\n\n let minZoom =\n options.minZoom !== undefined ? options.minZoom : DEFAULT_MIN_ZOOM;\n\n let maxZoom =\n options.maxZoom !== undefined ? options.maxZoom : defaultMaxZoom;\n\n const zoomFactor =\n options.zoomFactor !== undefined ? options.zoomFactor : defaultZoomFactor;\n\n const multiWorld =\n options.multiWorld !== undefined ? options.multiWorld : false;\n\n const smooth =\n options.smoothResolutionConstraint !== undefined\n ? options.smoothResolutionConstraint\n : true;\n\n const showFullExtent =\n options.showFullExtent !== undefined ? options.showFullExtent : false;\n\n const projection = createProjection(options.projection, 'EPSG:3857');\n const projExtent = projection.getExtent();\n let constrainOnlyCenter = options.constrainOnlyCenter;\n let extent = options.extent;\n if (!multiWorld && !extent && projection.isGlobal()) {\n constrainOnlyCenter = false;\n extent = projExtent;\n }\n\n if (options.resolutions !== undefined) {\n const resolutions = options.resolutions;\n maxResolution = resolutions[minZoom];\n minResolution =\n resolutions[maxZoom] !== undefined\n ? resolutions[maxZoom]\n : resolutions[resolutions.length - 1];\n\n if (options.constrainResolution) {\n resolutionConstraint = createSnapToResolutions(\n resolutions,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n } else {\n resolutionConstraint = createMinMaxResolution(\n maxResolution,\n minResolution,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n }\n } else {\n // calculate the default min and max resolution\n const size = !projExtent\n ? // use an extent that can fit the whole world if need be\n (360 * METERS_PER_UNIT.degrees) / projection.getMetersPerUnit()\n : Math.max(getWidth(projExtent), getHeight(projExtent));\n\n const defaultMaxResolution =\n size / DEFAULT_TILE_SIZE / Math.pow(defaultZoomFactor, DEFAULT_MIN_ZOOM);\n\n const defaultMinResolution =\n defaultMaxResolution /\n Math.pow(defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM);\n\n // user provided maxResolution takes precedence\n maxResolution = options.maxResolution;\n if (maxResolution !== undefined) {\n minZoom = 0;\n } else {\n maxResolution = defaultMaxResolution / Math.pow(zoomFactor, minZoom);\n }\n\n // user provided minResolution takes precedence\n minResolution = options.minResolution;\n if (minResolution === undefined) {\n if (options.maxZoom !== undefined) {\n if (options.maxResolution !== undefined) {\n minResolution = maxResolution / Math.pow(zoomFactor, maxZoom);\n } else {\n minResolution = defaultMaxResolution / Math.pow(zoomFactor, maxZoom);\n }\n } else {\n minResolution = defaultMinResolution;\n }\n }\n\n // given discrete zoom levels, minResolution may be different than provided\n maxZoom =\n minZoom +\n Math.floor(\n Math.log(maxResolution / minResolution) / Math.log(zoomFactor)\n );\n minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom);\n\n if (options.constrainResolution) {\n resolutionConstraint = createSnapToPower(\n zoomFactor,\n maxResolution,\n minResolution,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n } else {\n resolutionConstraint = createMinMaxResolution(\n maxResolution,\n minResolution,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n }\n }\n return {\n constraint: resolutionConstraint,\n maxResolution: maxResolution,\n minResolution: minResolution,\n minZoom: minZoom,\n zoomFactor: zoomFactor,\n };\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {import(\"./rotationconstraint.js\").Type} Rotation constraint.\n */\nexport function createRotationConstraint(options) {\n const enableRotation =\n options.enableRotation !== undefined ? options.enableRotation : true;\n if (enableRotation) {\n const constrainRotation = options.constrainRotation;\n if (constrainRotation === undefined || constrainRotation === true) {\n return createSnapToZero();\n }\n if (constrainRotation === false) {\n return rotationNone;\n }\n if (typeof constrainRotation === 'number') {\n return createSnapToN(constrainRotation);\n }\n return rotationNone;\n }\n return disable;\n}\n\n/**\n * Determine if an animation involves no view change.\n * @param {Animation} animation The animation.\n * @return {boolean} The animation involves no view change.\n */\nexport function isNoopAnimation(animation) {\n if (animation.sourceCenter && animation.targetCenter) {\n if (!coordinatesEqual(animation.sourceCenter, animation.targetCenter)) {\n return false;\n }\n }\n if (animation.sourceResolution !== animation.targetResolution) {\n return false;\n }\n if (animation.sourceRotation !== animation.targetRotation) {\n return false;\n }\n return true;\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"./size.js\").Size} size Box pixel size.\n * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @return {import(\"./coordinate.js\").Coordinate} Shifted center.\n */\nfunction calculateCenterOn(coordinate, size, position, resolution, rotation) {\n // calculate rotated position\n const cosAngle = Math.cos(-rotation);\n let sinAngle = Math.sin(-rotation);\n let rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle;\n let rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle;\n rotX += (size[0] / 2 - position[0]) * resolution;\n rotY += (position[1] - size[1] / 2) * resolution;\n\n // go back to original angle\n sinAngle = -sinAngle; // go back to original rotation\n const centerX = rotX * cosAngle - rotY * sinAngle;\n const centerY = rotY * cosAngle + rotX * sinAngle;\n\n return [centerX, centerY];\n}\n\nexport default View;\n","/**\n * @module ol/layer/Layer\n */\nimport BaseLayer from './Base.js';\nimport EventType from '../events/EventType.js';\nimport LayerProperty from './Property.js';\nimport RenderEventType from '../render/EventType.js';\nimport View from '../View.js';\nimport {assert} from '../asserts.js';\nimport {intersects} from '../extent.js';\nimport {listen, unlistenByKey} from '../events.js';\n\n/**\n * @typedef {function(import(\"../Map.js\").FrameState):HTMLElement} RenderFunction\n */\n\n/**\n * @typedef {'sourceready'|'change:source'} LayerEventType\n */\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} LayerOnSignature\n */\n\n/**\n * @template {import(\"../source/Source.js\").default} [SourceType=import(\"../source/Source.js\").default]\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {SourceType} [source] Source for this layer. If not provided to the constructor,\n * the source can be set by calling {@link module:ol/layer/Layer~Layer#setSource layer.setSource(source)} after\n * construction.\n * @property {import(\"../Map.js\").default|null} [map] Map.\n * @property {RenderFunction} [render] Render function. Takes the frame state as input and is expected to return an\n * HTML element. Will overwrite the default rendering for the layer.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @typedef {Object} State\n * @property {import(\"./Layer.js\").default} layer Layer.\n * @property {number} opacity Opacity, the value is rounded to two digits to appear after the decimal point.\n * @property {boolean} visible Visible.\n * @property {boolean} managed Managed.\n * @property {import(\"../extent.js\").Extent} [extent] Extent.\n * @property {number | undefined} zIndex ZIndex.\n * @property {number} maxResolution Maximum resolution.\n * @property {number} minResolution Minimum resolution.\n * @property {number} minZoom Minimum zoom.\n * @property {number} maxZoom Maximum zoom.\n */\n\n/**\n * @classdesc\n * Base class from which all layer types are derived. This should only be instantiated\n * in the case where a custom layer is added to the map with a custom `render` function.\n * Such a function can be specified in the `options` object, and is expected to return an HTML element.\n *\n * A visual representation of raster or vector map data.\n * Layers group together those properties that pertain to how the data is to be\n * displayed, irrespective of the source of that data.\n *\n * Layers are usually added to a map with [map.addLayer()]{@link import(\"../Map.js\").default#addLayer}.\n * Components like {@link module:ol/interaction/Draw~Draw} use unmanaged layers\n * internally. These unmanaged layers are associated with the map using\n * [layer.setMap()]{@link module:ol/layer/Layer~Layer#setMap} instead.\n *\n * A generic `change` event is fired when the state of the source changes.\n * A `sourceready` event is fired when the layer's source is ready.\n *\n * @fires import(\"../render/Event.js\").RenderEvent#prerender\n * @fires import(\"../render/Event.js\").RenderEvent#postrender\n * @fires import(\"../events/Event.js\").BaseEvent#sourceready\n *\n * @template {import(\"../source/Source.js\").default} [SourceType=import(\"../source/Source.js\").default]\n * @template {import(\"../renderer/Layer.js\").default} [RendererType=import(\"../renderer/Layer.js\").default]\n * @api\n */\nclass Layer extends BaseLayer {\n /**\n * @param {Options} options Layer options.\n */\n constructor(options) {\n const baseOptions = Object.assign({}, options);\n delete baseOptions.source;\n\n super(baseOptions);\n\n /***\n * @type {LayerOnSignature}\n */\n this.on;\n\n /***\n * @type {LayerOnSignature}\n */\n this.once;\n\n /***\n * @type {LayerOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {?import(\"../events.js\").EventsKey}\n */\n this.mapPrecomposeKey_ = null;\n\n /**\n * @private\n * @type {?import(\"../events.js\").EventsKey}\n */\n this.mapRenderKey_ = null;\n\n /**\n * @private\n * @type {?import(\"../events.js\").EventsKey}\n */\n this.sourceChangeKey_ = null;\n\n /**\n * @private\n * @type {RendererType}\n */\n this.renderer_ = null;\n\n /**\n * @private\n * @type {boolean}\n */\n this.sourceReady_ = false;\n\n /**\n * @protected\n * @type {boolean}\n */\n this.rendered = false;\n\n // Overwrite default render method with a custom one\n if (options.render) {\n this.render = options.render;\n }\n\n if (options.map) {\n this.setMap(options.map);\n }\n\n this.addChangeListener(\n LayerProperty.SOURCE,\n this.handleSourcePropertyChange_\n );\n\n const source = options.source\n ? /** @type {SourceType} */ (options.source)\n : null;\n this.setSource(source);\n }\n\n /**\n * @param {Array} [array] Array of layers (to be modified in place).\n * @return {Array} Array of layers.\n */\n getLayersArray(array) {\n array = array ? array : [];\n array.push(this);\n return array;\n }\n\n /**\n * @param {Array} [states] Optional list of layer states (to be modified in place).\n * @return {Array} List of layer states.\n */\n getLayerStatesArray(states) {\n states = states ? states : [];\n states.push(this.getLayerState());\n return states;\n }\n\n /**\n * Get the layer source.\n * @return {SourceType|null} The layer source (or `null` if not yet set).\n * @observable\n * @api\n */\n getSource() {\n return /** @type {SourceType} */ (this.get(LayerProperty.SOURCE)) || null;\n }\n\n /**\n * @return {SourceType|null} The source being rendered.\n */\n getRenderSource() {\n return this.getSource();\n }\n\n /**\n * @return {import(\"../source/Source.js\").State} Source state.\n */\n getSourceState() {\n const source = this.getSource();\n return !source ? 'undefined' : source.getState();\n }\n\n /**\n * @private\n */\n handleSourceChange_() {\n this.changed();\n if (this.sourceReady_ || this.getSource().getState() !== 'ready') {\n return;\n }\n this.sourceReady_ = true;\n this.dispatchEvent('sourceready');\n }\n\n /**\n * @private\n */\n handleSourcePropertyChange_() {\n if (this.sourceChangeKey_) {\n unlistenByKey(this.sourceChangeKey_);\n this.sourceChangeKey_ = null;\n }\n this.sourceReady_ = false;\n const source = this.getSource();\n if (source) {\n this.sourceChangeKey_ = listen(\n source,\n EventType.CHANGE,\n this.handleSourceChange_,\n this\n );\n if (source.getState() === 'ready') {\n this.sourceReady_ = true;\n setTimeout(() => {\n this.dispatchEvent('sourceready');\n }, 0);\n }\n }\n this.changed();\n }\n\n /**\n * @param {import(\"../pixel\").Pixel} pixel Pixel.\n * @return {Promise>} Promise that resolves with\n * an array of features.\n */\n getFeatures(pixel) {\n if (!this.renderer_) {\n return Promise.resolve([]);\n }\n return this.renderer_.getFeatures(pixel);\n }\n\n /**\n * @param {import(\"../pixel\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n */\n getData(pixel) {\n if (!this.renderer_ || !this.rendered) {\n return null;\n }\n return this.renderer_.getData(pixel);\n }\n\n /**\n * The layer is visible on the map view, i.e. within its min/max resolution or zoom and\n * extent, not set to `visible: false`, and not inside a layer group that is set\n * to `visible: false`.\n * @param {View|import(\"../View.js\").ViewStateLayerStateExtent} [view] View or {@link import(\"../Map.js\").FrameState}.\n * Only required when the layer is not added to a map.\n * @return {boolean} The layer is visible in the map view.\n * @api\n */\n isVisible(view) {\n let frameState;\n const map = this.getMapInternal();\n if (!view && map) {\n view = map.getView();\n }\n if (view instanceof View) {\n frameState = {\n viewState: view.getState(),\n extent: view.calculateExtent(),\n };\n } else {\n frameState = view;\n }\n if (!frameState.layerStatesArray && map) {\n frameState.layerStatesArray = map.getLayerGroup().getLayerStatesArray();\n }\n let layerState;\n if (frameState.layerStatesArray) {\n layerState = frameState.layerStatesArray.find(\n (layerState) => layerState.layer === this\n );\n } else {\n layerState = this.getLayerState();\n }\n\n const layerExtent = this.getExtent();\n\n return (\n inView(layerState, frameState.viewState) &&\n (!layerExtent || intersects(layerExtent, frameState.extent))\n );\n }\n\n /**\n * Get the attributions of the source of this layer for the given view.\n * @param {View|import(\"../View.js\").ViewStateLayerStateExtent} [view] View or {@link import(\"../Map.js\").FrameState}.\n * Only required when the layer is not added to a map.\n * @return {Array} Attributions for this layer at the given view.\n * @api\n */\n getAttributions(view) {\n if (!this.isVisible(view)) {\n return [];\n }\n let getAttributions;\n const source = this.getSource();\n if (source) {\n getAttributions = source.getAttributions();\n }\n if (!getAttributions) {\n return [];\n }\n const frameState =\n view instanceof View ? view.getViewStateAndExtent() : view;\n let attributions = getAttributions(frameState);\n if (!Array.isArray(attributions)) {\n attributions = [attributions];\n }\n return attributions;\n }\n\n /**\n * In charge to manage the rendering of the layer. One layer type is\n * bounded with one layer renderer.\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n * @param {HTMLElement} target Target which the renderer may (but need not) use\n * for rendering its content.\n * @return {HTMLElement|null} The rendered element.\n */\n render(frameState, target) {\n const layerRenderer = this.getRenderer();\n\n if (layerRenderer.prepareFrame(frameState)) {\n this.rendered = true;\n return layerRenderer.renderFrame(frameState, target);\n }\n return null;\n }\n\n /**\n * Called when a layer is not visible during a map render.\n */\n unrender() {\n this.rendered = false;\n }\n\n /**\n * For use inside the library only.\n * @param {import(\"../Map.js\").default|null} map Map.\n */\n setMapInternal(map) {\n if (!map) {\n this.unrender();\n }\n this.set(LayerProperty.MAP, map);\n }\n\n /**\n * For use inside the library only.\n * @return {import(\"../Map.js\").default|null} Map.\n */\n getMapInternal() {\n return this.get(LayerProperty.MAP);\n }\n\n /**\n * Sets the layer to be rendered on top of other layers on a map. The map will\n * not manage this layer in its layers collection. This\n * is useful for temporary layers. To remove an unmanaged layer from the map,\n * use `#setMap(null)`.\n *\n * To add the layer to a map and have it managed by the map, use\n * {@link module:ol/Map~Map#addLayer} instead.\n * @param {import(\"../Map.js\").default|null} map Map.\n * @api\n */\n setMap(map) {\n if (this.mapPrecomposeKey_) {\n unlistenByKey(this.mapPrecomposeKey_);\n this.mapPrecomposeKey_ = null;\n }\n if (!map) {\n this.changed();\n }\n if (this.mapRenderKey_) {\n unlistenByKey(this.mapRenderKey_);\n this.mapRenderKey_ = null;\n }\n if (map) {\n this.mapPrecomposeKey_ = listen(\n map,\n RenderEventType.PRECOMPOSE,\n function (evt) {\n const renderEvent =\n /** @type {import(\"../render/Event.js\").default} */ (evt);\n const layerStatesArray = renderEvent.frameState.layerStatesArray;\n const layerState = this.getLayerState(false);\n assert(\n !layerStatesArray.some(function (arrayLayerState) {\n return arrayLayerState.layer === layerState.layer;\n }),\n 'A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both.'\n );\n layerStatesArray.push(layerState);\n },\n this\n );\n this.mapRenderKey_ = listen(this, EventType.CHANGE, map.render, map);\n this.changed();\n }\n }\n\n /**\n * Set the layer source.\n * @param {SourceType|null} source The layer source.\n * @observable\n * @api\n */\n setSource(source) {\n this.set(LayerProperty.SOURCE, source);\n }\n\n /**\n * Get the renderer for this layer.\n * @return {RendererType|null} The layer renderer.\n */\n getRenderer() {\n if (!this.renderer_) {\n this.renderer_ = this.createRenderer();\n }\n return this.renderer_;\n }\n\n /**\n * @return {boolean} The layer has a renderer.\n */\n hasRenderer() {\n return !!this.renderer_;\n }\n\n /**\n * Create a renderer for this layer.\n * @return {RendererType} A layer renderer.\n * @protected\n */\n createRenderer() {\n return null;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n if (this.renderer_) {\n this.renderer_.dispose();\n delete this.renderer_;\n }\n\n this.setSource(null);\n super.disposeInternal();\n }\n}\n\n/**\n * Return `true` if the layer is visible and if the provided view state\n * has resolution and zoom levels that are in range of the layer's min/max.\n * @param {State} layerState Layer state.\n * @param {import(\"../View.js\").State} viewState View state.\n * @return {boolean} The layer is visible at the given view state.\n */\nexport function inView(layerState, viewState) {\n if (!layerState.visible) {\n return false;\n }\n const resolution = viewState.resolution;\n if (\n resolution < layerState.minResolution ||\n resolution >= layerState.maxResolution\n ) {\n return false;\n }\n const zoom = viewState.zoom;\n return zoom > layerState.minZoom && zoom <= layerState.maxZoom;\n}\n\nexport default Layer;\n","/**\n * @module ol/renderer/Map\n */\nimport Disposable from '../Disposable.js';\nimport {TRUE} from '../functions.js';\nimport {abstract} from '../util.js';\nimport {compose as composeTransform, makeInverse} from '../transform.js';\nimport {getWidth} from '../extent.js';\nimport {shared as iconImageCache} from '../style/IconImageCache.js';\nimport {inView} from '../layer/Layer.js';\nimport {wrapX} from '../coordinate.js';\n\n/**\n * @template T\n * @typedef HitMatch\n * @property {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @property {import(\"../layer/Layer.js\").default} layer Layer.\n * @property {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n * @property {number} distanceSq Squared distance.\n * @property {import(\"./vector.js\").FeatureCallback} callback Callback.\n */\n\n/**\n * @abstract\n */\nclass MapRenderer extends Disposable {\n /**\n * @param {import(\"../Map.js\").default} map Map.\n */\n constructor(map) {\n super();\n\n /**\n * @private\n * @type {import(\"../Map.js\").default}\n */\n this.map_ = map;\n }\n\n /**\n * @abstract\n * @param {import(\"../render/EventType.js\").default} type Event type.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n dispatchRenderEvent(type, frameState) {\n abstract();\n }\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n * @protected\n */\n calculateMatrices2D(frameState) {\n const viewState = frameState.viewState;\n const coordinateToPixelTransform = frameState.coordinateToPixelTransform;\n const pixelToCoordinateTransform = frameState.pixelToCoordinateTransform;\n\n composeTransform(\n coordinateToPixelTransform,\n frameState.size[0] / 2,\n frameState.size[1] / 2,\n 1 / viewState.resolution,\n -1 / viewState.resolution,\n -viewState.rotation,\n -viewState.center[0],\n -viewState.center[1]\n );\n\n makeInverse(pixelToCoordinateTransform, coordinateToPixelTransform);\n }\n\n /**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n * @param {number} hitTolerance Hit tolerance in pixels.\n * @param {boolean} checkWrapped Check for wrapped geometries.\n * @param {import(\"./vector.js\").FeatureCallback} callback Feature callback.\n * @param {S} thisArg Value to use as `this` when executing `callback`.\n * @param {function(this: U, import(\"../layer/Layer.js\").default): boolean} layerFilter Layer filter\n * function, only layers which are visible and for which this function\n * returns `true` will be tested for features. By default, all visible\n * layers will be tested.\n * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.\n * @return {T|undefined} Callback result.\n * @template S,T,U\n */\n forEachFeatureAtCoordinate(\n coordinate,\n frameState,\n hitTolerance,\n checkWrapped,\n callback,\n thisArg,\n layerFilter,\n thisArg2\n ) {\n let result;\n const viewState = frameState.viewState;\n\n /**\n * @param {boolean} managed Managed layer.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../layer/Layer.js\").default} layer Layer.\n * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n * @return {T|undefined} Callback result.\n */\n function forEachFeatureAtCoordinate(managed, feature, layer, geometry) {\n return callback.call(thisArg, feature, managed ? layer : null, geometry);\n }\n\n const projection = viewState.projection;\n\n const translatedCoordinate = wrapX(coordinate.slice(), projection);\n const offsets = [[0, 0]];\n if (projection.canWrapX() && checkWrapped) {\n const projectionExtent = projection.getExtent();\n const worldWidth = getWidth(projectionExtent);\n offsets.push([-worldWidth, 0], [worldWidth, 0]);\n }\n\n const layerStates = frameState.layerStatesArray;\n const numLayers = layerStates.length;\n\n const matches = /** @type {Array>} */ ([]);\n const tmpCoord = [];\n for (let i = 0; i < offsets.length; i++) {\n for (let j = numLayers - 1; j >= 0; --j) {\n const layerState = layerStates[j];\n const layer = layerState.layer;\n if (\n layer.hasRenderer() &&\n inView(layerState, viewState) &&\n layerFilter.call(thisArg2, layer)\n ) {\n const layerRenderer = layer.getRenderer();\n const source = layer.getSource();\n if (layerRenderer && source) {\n const coordinates = source.getWrapX()\n ? translatedCoordinate\n : coordinate;\n const callback = forEachFeatureAtCoordinate.bind(\n null,\n layerState.managed\n );\n tmpCoord[0] = coordinates[0] + offsets[i][0];\n tmpCoord[1] = coordinates[1] + offsets[i][1];\n result = layerRenderer.forEachFeatureAtCoordinate(\n tmpCoord,\n frameState,\n hitTolerance,\n callback,\n matches\n );\n }\n if (result) {\n return result;\n }\n }\n }\n }\n if (matches.length === 0) {\n return undefined;\n }\n const order = 1 / matches.length;\n matches.forEach((m, i) => (m.distanceSq += i * order));\n matches.sort((a, b) => a.distanceSq - b.distanceSq);\n matches.some((m) => {\n return (result = m.callback(m.feature, m.layer, m.geometry));\n });\n return result;\n }\n\n /**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n * @param {number} hitTolerance Hit tolerance in pixels.\n * @param {boolean} checkWrapped Check for wrapped geometries.\n * @param {function(this: U, import(\"../layer/Layer.js\").default): boolean} layerFilter Layer filter\n * function, only layers which are visible and for which this function\n * returns `true` will be tested for features. By default, all visible\n * layers will be tested.\n * @param {U} thisArg Value to use as `this` when executing `layerFilter`.\n * @return {boolean} Is there a feature at the given coordinate?\n * @template U\n */\n hasFeatureAtCoordinate(\n coordinate,\n frameState,\n hitTolerance,\n checkWrapped,\n layerFilter,\n thisArg\n ) {\n const hasFeature = this.forEachFeatureAtCoordinate(\n coordinate,\n frameState,\n hitTolerance,\n checkWrapped,\n TRUE,\n this,\n layerFilter,\n thisArg\n );\n\n return hasFeature !== undefined;\n }\n\n /**\n * @return {import(\"../Map.js\").default} Map.\n */\n getMap() {\n return this.map_;\n }\n\n /**\n * Render.\n * @abstract\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n */\n renderFrame(frameState) {\n abstract();\n }\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n flushDeclutterItems(frameState) {}\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n scheduleExpireIconCache(frameState) {\n if (iconImageCache.canExpireCache()) {\n frameState.postRenderFunctions.push(expireIconCache);\n }\n }\n}\n\n/**\n * @param {import(\"../Map.js\").default} map Map.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\nfunction expireIconCache(map, frameState) {\n iconImageCache.expire();\n}\n\nexport default MapRenderer;\n","/**\n * @module ol/render/Event\n */\n\nimport Event from '../events/Event.js';\n\nclass RenderEvent extends Event {\n /**\n * @param {import(\"./EventType.js\").default} type Type.\n * @param {import(\"../transform.js\").Transform} [inversePixelTransform] Transform for\n * CSS pixels to rendered pixels.\n * @param {import(\"../Map.js\").FrameState} [frameState] Frame state.\n * @param {?(CanvasRenderingContext2D|WebGLRenderingContext)} [context] Context.\n */\n constructor(type, inversePixelTransform, frameState, context) {\n super(type);\n\n /**\n * Transform from CSS pixels (relative to the top-left corner of the map viewport)\n * to rendered pixels on this event's `context`. Only available when a Canvas renderer is used, null otherwise.\n * @type {import(\"../transform.js\").Transform|undefined}\n * @api\n */\n this.inversePixelTransform = inversePixelTransform;\n\n /**\n * An object representing the current render frame state.\n * @type {import(\"../Map.js\").FrameState|undefined}\n * @api\n */\n this.frameState = frameState;\n\n /**\n * Canvas context. Not available when the event is dispatched by the map. For Canvas 2D layers,\n * the context will be the 2D rendering context. For WebGL layers, the context will be the WebGL\n * context.\n * @type {CanvasRenderingContext2D|WebGLRenderingContext|undefined}\n * @api\n */\n this.context = context;\n }\n}\n\nexport default RenderEvent;\n","/**\n * @module ol/css\n */\n\n/**\n * @typedef {Object} FontParameters\n * @property {string} style Style.\n * @property {string} variant Variant.\n * @property {string} weight Weight.\n * @property {string} size Size.\n * @property {string} lineHeight LineHeight.\n * @property {string} family Family.\n * @property {Array} families Families.\n */\n\n/**\n * The CSS class for hidden feature.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_HIDDEN = 'ol-hidden';\n\n/**\n * The CSS class that we'll give the DOM elements to have them selectable.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_SELECTABLE = 'ol-selectable';\n\n/**\n * The CSS class that we'll give the DOM elements to have them unselectable.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_UNSELECTABLE = 'ol-unselectable';\n\n/**\n * The CSS class for unsupported feature.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_UNSUPPORTED = 'ol-unsupported';\n\n/**\n * The CSS class for controls.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_CONTROL = 'ol-control';\n\n/**\n * The CSS class that we'll give the DOM elements that are collapsed, i.e.\n * to those elements which usually can be expanded.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_COLLAPSED = 'ol-collapsed';\n\n/**\n * From https://stackoverflow.com/questions/10135697/regex-to-parse-any-css-font\n * @type {RegExp}\n */\nconst fontRegEx = new RegExp(\n [\n '^\\\\s*(?=(?:(?:[-a-z]+\\\\s*){0,2}(italic|oblique))?)',\n '(?=(?:(?:[-a-z]+\\\\s*){0,2}(small-caps))?)',\n '(?=(?:(?:[-a-z]+\\\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)',\n '(?:(?:normal|\\\\1|\\\\2|\\\\3)\\\\s*){0,3}((?:xx?-)?',\n '(?:small|large)|medium|smaller|larger|[\\\\.\\\\d]+(?:\\\\%|in|[cem]m|ex|p[ctx]))',\n '(?:\\\\s*\\\\/\\\\s*(normal|[\\\\.\\\\d]+(?:\\\\%|in|[cem]m|ex|p[ctx])?))',\n '?\\\\s*([-,\\\\\"\\\\\\'\\\\sa-z]+?)\\\\s*$',\n ].join(''),\n 'i'\n);\nconst fontRegExMatchIndex = [\n 'style',\n 'variant',\n 'weight',\n 'size',\n 'lineHeight',\n 'family',\n];\n\n/**\n * Get the list of font families from a font spec. Note that this doesn't work\n * for font families that have commas in them.\n * @param {string} fontSpec The CSS font property.\n * @return {FontParameters|null} The font parameters (or null if the input spec is invalid).\n */\nexport const getFontParameters = function (fontSpec) {\n const match = fontSpec.match(fontRegEx);\n if (!match) {\n return null;\n }\n const style = /** @type {FontParameters} */ ({\n lineHeight: 'normal',\n size: '1.2em',\n style: 'normal',\n weight: 'normal',\n variant: 'normal',\n });\n for (let i = 0, ii = fontRegExMatchIndex.length; i < ii; ++i) {\n const value = match[i + 1];\n if (value !== undefined) {\n style[fontRegExMatchIndex[i]] = value;\n }\n }\n style.families = style.family.split(/,\\s?/);\n return style;\n};\n","import {WORKER_OFFSCREEN_CANVAS} from './has.js';\n\n/**\n * @module ol/dom\n */\n\n//FIXME Move this function to the canvas module\n/**\n * Create an html canvas element and returns its 2d context.\n * @param {number} [width] Canvas width.\n * @param {number} [height] Canvas height.\n * @param {Array} [canvasPool] Canvas pool to take existing canvas from.\n * @param {CanvasRenderingContext2DSettings} [settings] CanvasRenderingContext2DSettings\n * @return {CanvasRenderingContext2D} The context.\n */\nexport function createCanvasContext2D(width, height, canvasPool, settings) {\n /** @type {HTMLCanvasElement|OffscreenCanvas} */\n let canvas;\n if (canvasPool && canvasPool.length) {\n canvas = canvasPool.shift();\n } else if (WORKER_OFFSCREEN_CANVAS) {\n canvas = new OffscreenCanvas(width || 300, height || 300);\n } else {\n canvas = document.createElement('canvas');\n }\n if (width) {\n canvas.width = width;\n }\n if (height) {\n canvas.height = height;\n }\n //FIXME Allow OffscreenCanvasRenderingContext2D as return type\n return /** @type {CanvasRenderingContext2D} */ (\n canvas.getContext('2d', settings)\n );\n}\n\n/**\n * Releases canvas memory to avoid exceeding memory limits in Safari.\n * See https://pqina.nl/blog/total-canvas-memory-use-exceeds-the-maximum-limit/\n * @param {CanvasRenderingContext2D} context Context.\n */\nexport function releaseCanvas(context) {\n const canvas = context.canvas;\n canvas.width = 1;\n canvas.height = 1;\n context.clearRect(0, 0, 1, 1);\n}\n\n/**\n * Get the current computed width for the given element including margin,\n * padding and border.\n * Equivalent to jQuery's `$(el).outerWidth(true)`.\n * @param {!HTMLElement} element Element.\n * @return {number} The width.\n */\nexport function outerWidth(element) {\n let width = element.offsetWidth;\n const style = getComputedStyle(element);\n width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10);\n\n return width;\n}\n\n/**\n * Get the current computed height for the given element including margin,\n * padding and border.\n * Equivalent to jQuery's `$(el).outerHeight(true)`.\n * @param {!HTMLElement} element Element.\n * @return {number} The height.\n */\nexport function outerHeight(element) {\n let height = element.offsetHeight;\n const style = getComputedStyle(element);\n height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10);\n\n return height;\n}\n\n/**\n * @param {Node} newNode Node to replace old node\n * @param {Node} oldNode The node to be replaced\n */\nexport function replaceNode(newNode, oldNode) {\n const parent = oldNode.parentNode;\n if (parent) {\n parent.replaceChild(newNode, oldNode);\n }\n}\n\n/**\n * @param {Node} node The node to remove.\n * @return {Node|null} The node that was removed or null.\n */\nexport function removeNode(node) {\n return node && node.parentNode ? node.parentNode.removeChild(node) : null;\n}\n\n/**\n * @param {Node} node The node to remove the children from.\n */\nexport function removeChildren(node) {\n while (node.lastChild) {\n node.removeChild(node.lastChild);\n }\n}\n\n/**\n * Transform the children of a parent node so they match the\n * provided list of children. This function aims to efficiently\n * remove, add, and reorder child nodes while maintaining a simple\n * implementation (it is not guaranteed to minimize DOM operations).\n * @param {Node} node The parent node whose children need reworking.\n * @param {Array} children The desired children.\n */\nexport function replaceChildren(node, children) {\n const oldChildren = node.childNodes;\n\n for (let i = 0; true; ++i) {\n const oldChild = oldChildren[i];\n const newChild = children[i];\n\n // check if our work is done\n if (!oldChild && !newChild) {\n break;\n }\n\n // check if children match\n if (oldChild === newChild) {\n continue;\n }\n\n // check if a new child needs to be added\n if (!oldChild) {\n node.appendChild(newChild);\n continue;\n }\n\n // check if an old child needs to be removed\n if (!newChild) {\n node.removeChild(oldChild);\n --i;\n continue;\n }\n\n // reorder\n node.insertBefore(newChild, oldChild);\n }\n}\n","/**\n * @module ol/render/canvas\n */\nimport BaseObject from '../Object.js';\nimport {WORKER_OFFSCREEN_CANVAS} from '../has.js';\nimport {clear} from '../obj.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {getFontParameters} from '../css.js';\n\n/**\n * @typedef {'Circle' | 'Image' | 'LineString' | 'Polygon' | 'Text' | 'Default'} BuilderType\n */\n\n/**\n * @typedef {Object} FillState\n * @property {import(\"../colorlike.js\").ColorLike} fillStyle FillStyle.\n */\n\n/**\n * @typedef Label\n * @property {number} width Width.\n * @property {number} height Height.\n * @property {Array} contextInstructions ContextInstructions.\n */\n\n/**\n * @typedef {Object} FillStrokeState\n * @property {import(\"../colorlike.js\").ColorLike} [currentFillStyle] Current FillStyle.\n * @property {import(\"../colorlike.js\").ColorLike} [currentStrokeStyle] Current StrokeStyle.\n * @property {CanvasLineCap} [currentLineCap] Current LineCap.\n * @property {Array} currentLineDash Current LineDash.\n * @property {number} [currentLineDashOffset] Current LineDashOffset.\n * @property {CanvasLineJoin} [currentLineJoin] Current LineJoin.\n * @property {number} [currentLineWidth] Current LineWidth.\n * @property {number} [currentMiterLimit] Current MiterLimit.\n * @property {number} [lastStroke] Last stroke.\n * @property {import(\"../colorlike.js\").ColorLike} [fillStyle] FillStyle.\n * @property {import(\"../colorlike.js\").ColorLike} [strokeStyle] StrokeStyle.\n * @property {CanvasLineCap} [lineCap] LineCap.\n * @property {Array} lineDash LineDash.\n * @property {number} [lineDashOffset] LineDashOffset.\n * @property {CanvasLineJoin} [lineJoin] LineJoin.\n * @property {number} [lineWidth] LineWidth.\n * @property {number} [miterLimit] MiterLimit.\n */\n\n/**\n * @typedef {Object} StrokeState\n * @property {CanvasLineCap} lineCap LineCap.\n * @property {Array} lineDash LineDash.\n * @property {number} lineDashOffset LineDashOffset.\n * @property {CanvasLineJoin} lineJoin LineJoin.\n * @property {number} lineWidth LineWidth.\n * @property {number} miterLimit MiterLimit.\n * @property {import(\"../colorlike.js\").ColorLike} strokeStyle StrokeStyle.\n */\n\n/**\n * @typedef {Object} TextState\n * @property {string} font Font.\n * @property {CanvasTextAlign} [textAlign] TextAlign.\n * @property {number} [repeat] Repeat.\n * @property {import(\"../style/Text.js\").TextJustify} [justify] Justify.\n * @property {CanvasTextBaseline} textBaseline TextBaseline.\n * @property {import(\"../style/Text.js\").TextPlacement} [placement] Placement.\n * @property {number} [maxAngle] MaxAngle.\n * @property {boolean} [overflow] Overflow.\n * @property {import(\"../style/Fill.js\").default} [backgroundFill] BackgroundFill.\n * @property {import(\"../style/Stroke.js\").default} [backgroundStroke] BackgroundStroke.\n * @property {import(\"../size.js\").Size} [scale] Scale.\n * @property {Array} [padding] Padding.\n */\n\n/**\n * @typedef {Object} SerializableInstructions\n * @property {Array<*>} instructions The rendering instructions.\n * @property {Array<*>} hitDetectionInstructions The rendering hit detection instructions.\n * @property {Array} coordinates The array of all coordinates.\n * @property {!Object} [textStates] The text states (decluttering).\n * @property {!Object} [fillStates] The fill states (decluttering).\n * @property {!Object} [strokeStates] The stroke states (decluttering).\n */\n\n/**\n * @typedef {Object} DeclutterImageWithText\n */\n\n/**\n * @const\n * @type {string}\n */\nexport const defaultFont = '10px sans-serif';\n\n/**\n * @const\n * @type {string}\n */\nexport const defaultFillStyle = '#000';\n\n/**\n * @const\n * @type {CanvasLineCap}\n */\nexport const defaultLineCap = 'round';\n\n/**\n * @const\n * @type {Array}\n */\nexport const defaultLineDash = [];\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultLineDashOffset = 0;\n\n/**\n * @const\n * @type {CanvasLineJoin}\n */\nexport const defaultLineJoin = 'round';\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultMiterLimit = 10;\n\n/**\n * @const\n * @type {import(\"../colorlike.js\").ColorLike}\n */\nexport const defaultStrokeStyle = '#000';\n\n/**\n * @const\n * @type {CanvasTextAlign}\n */\nexport const defaultTextAlign = 'center';\n\n/**\n * @const\n * @type {CanvasTextBaseline}\n */\nexport const defaultTextBaseline = 'middle';\n\n/**\n * @const\n * @type {Array}\n */\nexport const defaultPadding = [0, 0, 0, 0];\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultLineWidth = 1;\n\n/**\n * @type {BaseObject}\n */\nexport const checkedFonts = new BaseObject();\n\n/**\n * @type {CanvasRenderingContext2D}\n */\nlet measureContext = null;\n\n/**\n * @type {string}\n */\nlet measureFont;\n\n/**\n * @type {!Object}\n */\nexport const textHeights = {};\n\n/**\n * Clears the label cache when a font becomes available.\n * @param {string} fontSpec CSS font spec.\n */\nexport const registerFont = (function () {\n const retries = 100;\n const size = '32px ';\n const referenceFonts = ['monospace', 'serif'];\n const len = referenceFonts.length;\n const text = 'wmytzilWMYTZIL@#/&?$%10\\uF013';\n let interval, referenceWidth;\n\n /**\n * @param {string} fontStyle Css font-style\n * @param {string} fontWeight Css font-weight\n * @param {*} fontFamily Css font-family\n * @return {boolean} Font with style and weight is available\n */\n function isAvailable(fontStyle, fontWeight, fontFamily) {\n let available = true;\n for (let i = 0; i < len; ++i) {\n const referenceFont = referenceFonts[i];\n referenceWidth = measureTextWidth(\n fontStyle + ' ' + fontWeight + ' ' + size + referenceFont,\n text\n );\n if (fontFamily != referenceFont) {\n const width = measureTextWidth(\n fontStyle +\n ' ' +\n fontWeight +\n ' ' +\n size +\n fontFamily +\n ',' +\n referenceFont,\n text\n );\n // If width and referenceWidth are the same, then the fallback was used\n // instead of the font we wanted, so the font is not available.\n available = available && width != referenceWidth;\n }\n }\n if (available) {\n return true;\n }\n return false;\n }\n\n function check() {\n let done = true;\n const fonts = checkedFonts.getKeys();\n for (let i = 0, ii = fonts.length; i < ii; ++i) {\n const font = fonts[i];\n if (checkedFonts.get(font) < retries) {\n if (isAvailable.apply(this, font.split('\\n'))) {\n clear(textHeights);\n // Make sure that loaded fonts are picked up by Safari\n measureContext = null;\n measureFont = undefined;\n checkedFonts.set(font, retries);\n } else {\n checkedFonts.set(font, checkedFonts.get(font) + 1, true);\n done = false;\n }\n }\n }\n if (done) {\n clearInterval(interval);\n interval = undefined;\n }\n }\n\n return function (fontSpec) {\n const font = getFontParameters(fontSpec);\n if (!font) {\n return;\n }\n const families = font.families;\n for (let i = 0, ii = families.length; i < ii; ++i) {\n const family = families[i];\n const key = font.style + '\\n' + font.weight + '\\n' + family;\n if (checkedFonts.get(key) === undefined) {\n checkedFonts.set(key, retries, true);\n if (!isAvailable(font.style, font.weight, family)) {\n checkedFonts.set(key, 0, true);\n if (interval === undefined) {\n interval = setInterval(check, 32);\n }\n }\n }\n }\n };\n})();\n\n/**\n * @param {string} font Font to use for measuring.\n * @return {import(\"../size.js\").Size} Measurement.\n */\nexport const measureTextHeight = (function () {\n /**\n * @type {HTMLDivElement}\n */\n let measureElement;\n return function (fontSpec) {\n let height = textHeights[fontSpec];\n if (height == undefined) {\n if (WORKER_OFFSCREEN_CANVAS) {\n const font = getFontParameters(fontSpec);\n const metrics = measureText(fontSpec, 'Žg');\n const lineHeight = isNaN(Number(font.lineHeight))\n ? 1.2\n : Number(font.lineHeight);\n height =\n lineHeight *\n (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent);\n } else {\n if (!measureElement) {\n measureElement = document.createElement('div');\n measureElement.innerHTML = 'M';\n measureElement.style.minHeight = '0';\n measureElement.style.maxHeight = 'none';\n measureElement.style.height = 'auto';\n measureElement.style.padding = '0';\n measureElement.style.border = 'none';\n measureElement.style.position = 'absolute';\n measureElement.style.display = 'block';\n measureElement.style.left = '-99999px';\n }\n measureElement.style.font = fontSpec;\n document.body.appendChild(measureElement);\n height = measureElement.offsetHeight;\n document.body.removeChild(measureElement);\n }\n textHeights[fontSpec] = height;\n }\n return height;\n };\n})();\n\n/**\n * @param {string} font Font.\n * @param {string} text Text.\n * @return {TextMetrics} Text metrics.\n */\nfunction measureText(font, text) {\n if (!measureContext) {\n measureContext = createCanvasContext2D(1, 1);\n }\n if (font != measureFont) {\n measureContext.font = font;\n measureFont = measureContext.font;\n }\n return measureContext.measureText(text);\n}\n\n/**\n * @param {string} font Font.\n * @param {string} text Text.\n * @return {number} Width.\n */\nexport function measureTextWidth(font, text) {\n return measureText(font, text).width;\n}\n\n/**\n * Measure text width using a cache.\n * @param {string} font The font.\n * @param {string} text The text to measure.\n * @param {Object} cache A lookup of cached widths by text.\n * @return {number} The text width.\n */\nexport function measureAndCacheTextWidth(font, text, cache) {\n if (text in cache) {\n return cache[text];\n }\n const width = text\n .split('\\n')\n .reduce((prev, curr) => Math.max(prev, measureTextWidth(font, curr)), 0);\n cache[text] = width;\n return width;\n}\n\n/**\n * @param {TextState} baseStyle Base style.\n * @param {Array} chunks Text chunks to measure.\n * @return {{width: number, height: number, widths: Array, heights: Array, lineWidths: Array}}} Text metrics.\n */\nexport function getTextDimensions(baseStyle, chunks) {\n const widths = [];\n const heights = [];\n const lineWidths = [];\n let width = 0;\n let lineWidth = 0;\n let height = 0;\n let lineHeight = 0;\n for (let i = 0, ii = chunks.length; i <= ii; i += 2) {\n const text = chunks[i];\n if (text === '\\n' || i === ii) {\n width = Math.max(width, lineWidth);\n lineWidths.push(lineWidth);\n lineWidth = 0;\n height += lineHeight;\n continue;\n }\n const font = chunks[i + 1] || baseStyle.font;\n const currentWidth = measureTextWidth(font, text);\n widths.push(currentWidth);\n lineWidth += currentWidth;\n const currentHeight = measureTextHeight(font);\n heights.push(currentHeight);\n lineHeight = Math.max(lineHeight, currentHeight);\n }\n return {width, height, widths, heights, lineWidths};\n}\n\n/**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {number} rotation Rotation.\n * @param {number} offsetX X offset.\n * @param {number} offsetY Y offset.\n */\nexport function rotateAtOffset(context, rotation, offsetX, offsetY) {\n if (rotation !== 0) {\n context.translate(offsetX, offsetY);\n context.rotate(rotation);\n context.translate(-offsetX, -offsetY);\n }\n}\n\n/**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {import(\"../transform.js\").Transform|null} transform Transform.\n * @param {number} opacity Opacity.\n * @param {Label|HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} labelOrImage Label.\n * @param {number} originX Origin X.\n * @param {number} originY Origin Y.\n * @param {number} w Width.\n * @param {number} h Height.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../size.js\").Size} scale Scale.\n */\nexport function drawImageOrLabel(\n context,\n transform,\n opacity,\n labelOrImage,\n originX,\n originY,\n w,\n h,\n x,\n y,\n scale\n) {\n context.save();\n\n if (opacity !== 1) {\n context.globalAlpha *= opacity;\n }\n if (transform) {\n context.transform.apply(context, transform);\n }\n\n if (/** @type {*} */ (labelOrImage).contextInstructions) {\n // label\n context.translate(x, y);\n context.scale(scale[0], scale[1]);\n executeLabelInstructions(/** @type {Label} */ (labelOrImage), context);\n } else if (scale[0] < 0 || scale[1] < 0) {\n // flipped image\n context.translate(x, y);\n context.scale(scale[0], scale[1]);\n context.drawImage(\n /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (\n labelOrImage\n ),\n originX,\n originY,\n w,\n h,\n 0,\n 0,\n w,\n h\n );\n } else {\n // if image not flipped translate and scale can be avoided\n context.drawImage(\n /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (\n labelOrImage\n ),\n originX,\n originY,\n w,\n h,\n x,\n y,\n w * scale[0],\n h * scale[1]\n );\n }\n\n context.restore();\n}\n\n/**\n * @param {Label} label Label.\n * @param {CanvasRenderingContext2D} context Context.\n */\nfunction executeLabelInstructions(label, context) {\n const contextInstructions = label.contextInstructions;\n for (let i = 0, ii = contextInstructions.length; i < ii; i += 2) {\n if (Array.isArray(contextInstructions[i + 1])) {\n context[contextInstructions[i]].apply(\n context,\n contextInstructions[i + 1]\n );\n } else {\n context[contextInstructions[i]] = contextInstructions[i + 1];\n }\n }\n}\n","/**\n * @module ol/renderer/Composite\n */\nimport MapRenderer from './Map.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport RenderEvent from '../render/Event.js';\nimport RenderEventType from '../render/EventType.js';\nimport {CLASS_UNSELECTABLE} from '../css.js';\nimport {checkedFonts} from '../render/canvas.js';\nimport {inView} from '../layer/Layer.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {replaceChildren} from '../dom.js';\n\n/**\n * @classdesc\n * Canvas map renderer.\n * @api\n */\nclass CompositeMapRenderer extends MapRenderer {\n /**\n * @param {import(\"../Map.js\").default} map Map.\n */\n constructor(map) {\n super(map);\n\n /**\n * @type {import(\"../events.js\").EventsKey}\n */\n this.fontChangeListenerKey_ = listen(\n checkedFonts,\n ObjectEventType.PROPERTYCHANGE,\n map.redrawText.bind(map)\n );\n\n /**\n * @private\n * @type {HTMLDivElement}\n */\n this.element_ = document.createElement('div');\n const style = this.element_.style;\n style.position = 'absolute';\n style.width = '100%';\n style.height = '100%';\n style.zIndex = '0';\n\n this.element_.className = CLASS_UNSELECTABLE + ' ol-layers';\n\n const container = map.getViewport();\n container.insertBefore(this.element_, container.firstChild || null);\n\n /**\n * @private\n * @type {Array}\n */\n this.children_ = [];\n\n /**\n * @private\n * @type {boolean}\n */\n this.renderedVisible_ = true;\n\n /**\n * @type {Array}\n */\n this.declutterLayers_ = [];\n }\n\n /**\n * @param {import(\"../render/EventType.js\").default} type Event type.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n dispatchRenderEvent(type, frameState) {\n const map = this.getMap();\n if (map.hasListener(type)) {\n const event = new RenderEvent(type, undefined, frameState);\n map.dispatchEvent(event);\n }\n }\n\n disposeInternal() {\n unlistenByKey(this.fontChangeListenerKey_);\n this.element_.parentNode.removeChild(this.element_);\n super.disposeInternal();\n }\n\n /**\n * Render.\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n */\n renderFrame(frameState) {\n if (!frameState) {\n if (this.renderedVisible_) {\n this.element_.style.display = 'none';\n this.renderedVisible_ = false;\n }\n return;\n }\n\n this.calculateMatrices2D(frameState);\n this.dispatchRenderEvent(RenderEventType.PRECOMPOSE, frameState);\n\n const layerStatesArray = frameState.layerStatesArray.sort(function (a, b) {\n return a.zIndex - b.zIndex;\n });\n const viewState = frameState.viewState;\n\n this.children_.length = 0;\n\n const declutterLayers = this.declutterLayers_;\n declutterLayers.length = 0;\n\n let previousElement = null;\n for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {\n const layerState = layerStatesArray[i];\n frameState.layerIndex = i;\n\n const layer = layerState.layer;\n const sourceState = layer.getSourceState();\n if (\n !inView(layerState, viewState) ||\n (sourceState != 'ready' && sourceState != 'undefined')\n ) {\n layer.unrender();\n continue;\n }\n\n const element = layer.render(frameState, previousElement);\n if (!element) {\n continue;\n }\n if (element !== previousElement) {\n this.children_.push(element);\n previousElement = element;\n }\n if ('getDeclutter' in layer) {\n declutterLayers.push(\n /** @type {import(\"../layer/BaseVector.js\").default} */ (layer)\n );\n }\n }\n this.flushDeclutterItems(frameState);\n\n replaceChildren(this.element_, this.children_);\n\n this.dispatchRenderEvent(RenderEventType.POSTCOMPOSE, frameState);\n\n if (!this.renderedVisible_) {\n this.element_.style.display = '';\n this.renderedVisible_ = true;\n }\n\n this.scheduleExpireIconCache(frameState);\n }\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n flushDeclutterItems(frameState) {\n const layers = this.declutterLayers_;\n for (let i = layers.length - 1; i >= 0; --i) {\n layers[i].renderDeclutter(frameState);\n }\n layers.length = 0;\n }\n}\n\nexport default CompositeMapRenderer;\n","/**\n * @module ol/layer/Group\n */\nimport BaseLayer from './Base.js';\nimport Collection from '../Collection.js';\nimport CollectionEventType from '../CollectionEventType.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport {assert} from '../asserts.js';\nimport {clear} from '../obj.js';\nimport {getIntersection} from '../extent.js';\nimport {getUid} from '../util.js';\nimport {listen, unlistenByKey} from '../events.js';\n\n/**\n * @typedef {'addlayer'|'removelayer'} EventType\n */\n\n/**\n * @classdesc\n * A layer group triggers 'addlayer' and 'removelayer' events when layers are added to or removed from\n * the group or one of its child groups. When a layer group is added to or removed from another layer group,\n * a single event will be triggered (instead of one per layer in the group added or removed).\n */\nexport class GroupEvent extends Event {\n /**\n * @param {EventType} type The event type.\n * @param {BaseLayer} layer The layer.\n */\n constructor(type, layer) {\n super(type);\n\n /**\n * The added or removed layer.\n * @type {BaseLayer}\n * @api\n */\n this.layer = layer;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} GroupOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {Array|Collection} [layers] Child layers.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @enum {string}\n * @private\n */\nconst Property = {\n LAYERS: 'layers',\n};\n\n/**\n * @classdesc\n * A {@link module:ol/Collection~Collection} of layers that are handled together.\n *\n * A generic `change` event is triggered when the group/Collection changes.\n *\n * @api\n */\nclass LayerGroup extends BaseLayer {\n /**\n * @param {Options} [options] Layer options.\n */\n constructor(options) {\n options = options || {};\n const baseOptions = /** @type {Options} */ (Object.assign({}, options));\n delete baseOptions.layers;\n\n let layers = options.layers;\n\n super(baseOptions);\n\n /***\n * @type {GroupOnSignature}\n */\n this.on;\n\n /***\n * @type {GroupOnSignature}\n */\n this.once;\n\n /***\n * @type {GroupOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {Array}\n */\n this.layersListenerKeys_ = [];\n\n /**\n * @private\n * @type {Object>}\n */\n this.listenerKeys_ = {};\n\n this.addChangeListener(Property.LAYERS, this.handleLayersChanged_);\n\n if (layers) {\n if (Array.isArray(layers)) {\n layers = new Collection(layers.slice(), {unique: true});\n } else {\n assert(\n typeof (/** @type {?} */ (layers).getArray) === 'function',\n 'Expected `layers` to be an array or a `Collection`'\n );\n }\n } else {\n layers = new Collection(undefined, {unique: true});\n }\n\n this.setLayers(layers);\n }\n\n /**\n * @private\n */\n handleLayerChange_() {\n this.changed();\n }\n\n /**\n * @private\n */\n handleLayersChanged_() {\n this.layersListenerKeys_.forEach(unlistenByKey);\n this.layersListenerKeys_.length = 0;\n\n const layers = this.getLayers();\n this.layersListenerKeys_.push(\n listen(layers, CollectionEventType.ADD, this.handleLayersAdd_, this),\n listen(layers, CollectionEventType.REMOVE, this.handleLayersRemove_, this)\n );\n\n for (const id in this.listenerKeys_) {\n this.listenerKeys_[id].forEach(unlistenByKey);\n }\n clear(this.listenerKeys_);\n\n const layersArray = layers.getArray();\n for (let i = 0, ii = layersArray.length; i < ii; i++) {\n const layer = layersArray[i];\n this.registerLayerListeners_(layer);\n this.dispatchEvent(new GroupEvent('addlayer', layer));\n }\n this.changed();\n }\n\n /**\n * @param {BaseLayer} layer The layer.\n */\n registerLayerListeners_(layer) {\n const listenerKeys = [\n listen(\n layer,\n ObjectEventType.PROPERTYCHANGE,\n this.handleLayerChange_,\n this\n ),\n listen(layer, EventType.CHANGE, this.handleLayerChange_, this),\n ];\n\n if (layer instanceof LayerGroup) {\n listenerKeys.push(\n listen(layer, 'addlayer', this.handleLayerGroupAdd_, this),\n listen(layer, 'removelayer', this.handleLayerGroupRemove_, this)\n );\n }\n\n this.listenerKeys_[getUid(layer)] = listenerKeys;\n }\n\n /**\n * @param {GroupEvent} event The layer group event.\n */\n handleLayerGroupAdd_(event) {\n this.dispatchEvent(new GroupEvent('addlayer', event.layer));\n }\n\n /**\n * @param {GroupEvent} event The layer group event.\n */\n handleLayerGroupRemove_(event) {\n this.dispatchEvent(new GroupEvent('removelayer', event.layer));\n }\n\n /**\n * @param {import(\"../Collection.js\").CollectionEvent} collectionEvent CollectionEvent.\n * @private\n */\n handleLayersAdd_(collectionEvent) {\n const layer = collectionEvent.element;\n this.registerLayerListeners_(layer);\n this.dispatchEvent(new GroupEvent('addlayer', layer));\n this.changed();\n }\n\n /**\n * @param {import(\"../Collection.js\").CollectionEvent} collectionEvent CollectionEvent.\n * @private\n */\n handleLayersRemove_(collectionEvent) {\n const layer = collectionEvent.element;\n const key = getUid(layer);\n this.listenerKeys_[key].forEach(unlistenByKey);\n delete this.listenerKeys_[key];\n this.dispatchEvent(new GroupEvent('removelayer', layer));\n this.changed();\n }\n\n /**\n * Returns the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}\n * in this group.\n * @return {!Collection} Collection of\n * {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.\n * @observable\n * @api\n */\n getLayers() {\n return /** @type {!Collection} */ (\n this.get(Property.LAYERS)\n );\n }\n\n /**\n * Set the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}\n * in this group.\n * @param {!Collection} layers Collection of\n * {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.\n * @observable\n * @api\n */\n setLayers(layers) {\n const collection = this.getLayers();\n if (collection) {\n const currentLayers = collection.getArray();\n for (let i = 0, ii = currentLayers.length; i < ii; ++i) {\n this.dispatchEvent(new GroupEvent('removelayer', currentLayers[i]));\n }\n }\n\n this.set(Property.LAYERS, layers);\n }\n\n /**\n * @param {Array} [array] Array of layers (to be modified in place).\n * @return {Array} Array of layers.\n */\n getLayersArray(array) {\n array = array !== undefined ? array : [];\n this.getLayers().forEach(function (layer) {\n layer.getLayersArray(array);\n });\n return array;\n }\n\n /**\n * Get the layer states list and use this groups z-index as the default\n * for all layers in this and nested groups, if it is unset at this point.\n * If dest is not provided and this group's z-index is undefined\n * 0 is used a the default z-index.\n * @param {Array} [dest] Optional list\n * of layer states (to be modified in place).\n * @return {Array} List of layer states.\n */\n getLayerStatesArray(dest) {\n const states = dest !== undefined ? dest : [];\n const pos = states.length;\n\n this.getLayers().forEach(function (layer) {\n layer.getLayerStatesArray(states);\n });\n\n const ownLayerState = this.getLayerState();\n let defaultZIndex = ownLayerState.zIndex;\n if (!dest && ownLayerState.zIndex === undefined) {\n defaultZIndex = 0;\n }\n for (let i = pos, ii = states.length; i < ii; i++) {\n const layerState = states[i];\n layerState.opacity *= ownLayerState.opacity;\n layerState.visible = layerState.visible && ownLayerState.visible;\n layerState.maxResolution = Math.min(\n layerState.maxResolution,\n ownLayerState.maxResolution\n );\n layerState.minResolution = Math.max(\n layerState.minResolution,\n ownLayerState.minResolution\n );\n layerState.minZoom = Math.max(layerState.minZoom, ownLayerState.minZoom);\n layerState.maxZoom = Math.min(layerState.maxZoom, ownLayerState.maxZoom);\n if (ownLayerState.extent !== undefined) {\n if (layerState.extent !== undefined) {\n layerState.extent = getIntersection(\n layerState.extent,\n ownLayerState.extent\n );\n } else {\n layerState.extent = ownLayerState.extent;\n }\n }\n if (layerState.zIndex === undefined) {\n layerState.zIndex = defaultZIndex;\n }\n }\n\n return states;\n }\n\n /**\n * @return {import(\"../source/Source.js\").State} Source state.\n */\n getSourceState() {\n return 'ready';\n }\n}\n\nexport default LayerGroup;\n","/**\n * @module ol/MapEvent\n */\nimport Event from './events/Event.js';\n\n/**\n * @classdesc\n * Events emitted as map events are instances of this type.\n * See {@link module:ol/Map~Map} for which events trigger a map event.\n */\nclass MapEvent extends Event {\n /**\n * @param {string} type Event type.\n * @param {import(\"./Map.js\").default} map Map.\n * @param {?import(\"./Map.js\").FrameState} [frameState] Frame state.\n */\n constructor(type, map, frameState) {\n super(type);\n\n /**\n * The map where the event occurred.\n * @type {import(\"./Map.js\").default}\n * @api\n */\n this.map = map;\n\n /**\n * The frame state at the time of the event.\n * @type {?import(\"./Map.js\").FrameState}\n * @api\n */\n this.frameState = frameState !== undefined ? frameState : null;\n }\n}\n\nexport default MapEvent;\n","/**\n * @module ol/MapBrowserEvent\n */\nimport MapEvent from './MapEvent.js';\n\n/**\n * @classdesc\n * Events emitted as map browser events are instances of this type.\n * See {@link module:ol/Map~Map} for which events trigger a map browser event.\n * @template {UIEvent} EVENT\n */\nclass MapBrowserEvent extends MapEvent {\n /**\n * @param {string} type Event type.\n * @param {import(\"./Map.js\").default} map Map.\n * @param {EVENT} originalEvent Original event.\n * @param {boolean} [dragging] Is the map currently being dragged?\n * @param {import(\"./Map.js\").FrameState} [frameState] Frame state.\n * @param {Array} [activePointers] Active pointers.\n */\n constructor(type, map, originalEvent, dragging, frameState, activePointers) {\n super(type, map, frameState);\n\n /**\n * The original browser event.\n * @const\n * @type {EVENT}\n * @api\n */\n this.originalEvent = originalEvent;\n\n /**\n * The map pixel relative to the viewport corresponding to the original browser event.\n * @type {?import(\"./pixel.js\").Pixel}\n */\n this.pixel_ = null;\n\n /**\n * The coordinate in the user projection corresponding to the original browser event.\n * @type {?import(\"./coordinate.js\").Coordinate}\n */\n this.coordinate_ = null;\n\n /**\n * Indicates if the map is currently being dragged. Only set for\n * `POINTERDRAG` and `POINTERMOVE` events. Default is `false`.\n *\n * @type {boolean}\n * @api\n */\n this.dragging = dragging !== undefined ? dragging : false;\n\n /**\n * @type {Array|undefined}\n */\n this.activePointers = activePointers;\n }\n\n /**\n * The map pixel relative to the viewport corresponding to the original event.\n * @type {import(\"./pixel.js\").Pixel}\n * @api\n */\n get pixel() {\n if (!this.pixel_) {\n this.pixel_ = this.map.getEventPixel(this.originalEvent);\n }\n return this.pixel_;\n }\n set pixel(pixel) {\n this.pixel_ = pixel;\n }\n\n /**\n * The coordinate corresponding to the original browser event. This will be in the user\n * projection if one is set. Otherwise it will be in the view projection.\n * @type {import(\"./coordinate.js\").Coordinate}\n * @api\n */\n get coordinate() {\n if (!this.coordinate_) {\n this.coordinate_ = this.map.getCoordinateFromPixel(this.pixel);\n }\n return this.coordinate_;\n }\n set coordinate(coordinate) {\n this.coordinate_ = coordinate;\n }\n\n /**\n * Prevents the default browser action.\n * See https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault.\n * @api\n */\n preventDefault() {\n super.preventDefault();\n if ('preventDefault' in this.originalEvent) {\n /** @type {UIEvent} */ (this.originalEvent).preventDefault();\n }\n }\n\n /**\n * Prevents further propagation of the current event.\n * See https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation.\n * @api\n */\n stopPropagation() {\n super.stopPropagation();\n if ('stopPropagation' in this.originalEvent) {\n /** @type {UIEvent} */ (this.originalEvent).stopPropagation();\n }\n }\n}\n\nexport default MapBrowserEvent;\n","/**\n * @module ol/MapBrowserEventType\n */\nimport EventType from './events/EventType.js';\n\n/**\n * Constants for event names.\n * @enum {string}\n */\nexport default {\n /**\n * A true single click with no dragging and no double click. Note that this\n * event is delayed by 250 ms to ensure that it is not a double click.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#singleclick\n * @api\n */\n SINGLECLICK: 'singleclick',\n\n /**\n * A click with no dragging. A double click will fire two of this.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#click\n * @api\n */\n CLICK: EventType.CLICK,\n\n /**\n * A true double click, with no dragging.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#dblclick\n * @api\n */\n DBLCLICK: EventType.DBLCLICK,\n\n /**\n * Triggered when a pointer is dragged.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointerdrag\n * @api\n */\n POINTERDRAG: 'pointerdrag',\n\n /**\n * Triggered when a pointer is moved. Note that on touch devices this is\n * triggered when the map is panned, so is not the same as mousemove.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointermove\n * @api\n */\n POINTERMOVE: 'pointermove',\n\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n POINTERCANCEL: 'pointercancel',\n};\n\n/***\n * @typedef {'singleclick'|'click'|'dblclick'|'pointerdrag'|'pointermove'} Types\n */\n","/**\n * @module ol/pointer/EventType\n */\n\n/**\n * Constants for event names.\n * @enum {string}\n */\nexport default {\n POINTERMOVE: 'pointermove',\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n POINTERCANCEL: 'pointercancel',\n};\n","/**\n * @module ol/MapBrowserEventHandler\n */\n\nimport EventType from './events/EventType.js';\nimport MapBrowserEvent from './MapBrowserEvent.js';\nimport MapBrowserEventType from './MapBrowserEventType.js';\nimport PointerEventType from './pointer/EventType.js';\nimport Target from './events/Target.js';\nimport {PASSIVE_EVENT_LISTENERS} from './has.js';\nimport {listen, unlistenByKey} from './events.js';\n\nclass MapBrowserEventHandler extends Target {\n /**\n * @param {import(\"./Map.js\").default} map The map with the viewport to listen to events on.\n * @param {number} [moveTolerance] The minimal distance the pointer must travel to trigger a move.\n */\n constructor(map, moveTolerance) {\n super(map);\n\n /**\n * This is the element that we will listen to the real events on.\n * @type {import(\"./Map.js\").default}\n * @private\n */\n this.map_ = map;\n\n /**\n * @type {ReturnType}\n * @private\n */\n this.clickTimeoutId_;\n\n /**\n * Emulate dblclick and singleclick. Will be true when only one pointer is active.\n * @type {boolean}\n */\n this.emulateClicks_ = false;\n\n /**\n * @type {boolean}\n * @private\n */\n this.dragging_ = false;\n\n /**\n * @type {!Array}\n * @private\n */\n this.dragListenerKeys_ = [];\n\n /**\n * @type {number}\n * @private\n */\n this.moveTolerance_ = moveTolerance === undefined ? 1 : moveTolerance;\n\n /**\n * The most recent \"down\" type event (or null if none have occurred).\n * Set on pointerdown.\n * @type {PointerEvent|null}\n * @private\n */\n this.down_ = null;\n\n const element = this.map_.getViewport();\n\n /**\n * @type {Array}\n * @private\n */\n this.activePointers_ = [];\n\n /**\n * @type {!Object}\n * @private\n */\n this.trackedTouches_ = {};\n\n this.element_ = element;\n\n /**\n * @type {?import(\"./events.js\").EventsKey}\n * @private\n */\n this.pointerdownListenerKey_ = listen(\n element,\n PointerEventType.POINTERDOWN,\n this.handlePointerDown_,\n this\n );\n\n /**\n * @type {PointerEvent}\n * @private\n */\n this.originalPointerMoveEvent_;\n\n /**\n * @type {?import(\"./events.js\").EventsKey}\n * @private\n */\n this.relayedListenerKey_ = listen(\n element,\n PointerEventType.POINTERMOVE,\n this.relayMoveEvent_,\n this\n );\n\n /**\n * @private\n */\n this.boundHandleTouchMove_ = this.handleTouchMove_.bind(this);\n\n this.element_.addEventListener(\n EventType.TOUCHMOVE,\n this.boundHandleTouchMove_,\n PASSIVE_EVENT_LISTENERS ? {passive: false} : false\n );\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n emulateClick_(pointerEvent) {\n let newEvent = new MapBrowserEvent(\n MapBrowserEventType.CLICK,\n this.map_,\n pointerEvent\n );\n this.dispatchEvent(newEvent);\n if (this.clickTimeoutId_ !== undefined) {\n // double-click\n clearTimeout(this.clickTimeoutId_);\n this.clickTimeoutId_ = undefined;\n newEvent = new MapBrowserEvent(\n MapBrowserEventType.DBLCLICK,\n this.map_,\n pointerEvent\n );\n this.dispatchEvent(newEvent);\n } else {\n // click\n this.clickTimeoutId_ = setTimeout(() => {\n this.clickTimeoutId_ = undefined;\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.SINGLECLICK,\n this.map_,\n pointerEvent\n );\n this.dispatchEvent(newEvent);\n }, 250);\n }\n }\n\n /**\n * Keeps track on how many pointers are currently active.\n *\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n updateActivePointers_(pointerEvent) {\n const event = pointerEvent;\n const id = event.pointerId;\n\n if (\n event.type == MapBrowserEventType.POINTERUP ||\n event.type == MapBrowserEventType.POINTERCANCEL\n ) {\n delete this.trackedTouches_[id];\n for (const pointerId in this.trackedTouches_) {\n if (this.trackedTouches_[pointerId].target !== event.target) {\n // Some platforms assign a new pointerId when the target changes.\n // If this happens, delete one tracked pointer. If there is more\n // than one tracked pointer for the old target, it will be cleared\n // by subsequent POINTERUP events from other pointers.\n delete this.trackedTouches_[pointerId];\n break;\n }\n }\n } else if (\n event.type == MapBrowserEventType.POINTERDOWN ||\n event.type == MapBrowserEventType.POINTERMOVE\n ) {\n this.trackedTouches_[id] = event;\n }\n this.activePointers_ = Object.values(this.trackedTouches_);\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n handlePointerUp_(pointerEvent) {\n this.updateActivePointers_(pointerEvent);\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.POINTERUP,\n this.map_,\n pointerEvent,\n undefined,\n undefined,\n this.activePointers_\n );\n this.dispatchEvent(newEvent);\n\n // We emulate click events on left mouse button click, touch contact, and pen\n // contact. isMouseActionButton returns true in these cases (evt.button is set\n // to 0).\n // See http://www.w3.org/TR/pointerevents/#button-states\n // We only fire click, singleclick, and doubleclick if nobody has called\n // event.preventDefault().\n if (\n this.emulateClicks_ &&\n !newEvent.defaultPrevented &&\n !this.dragging_ &&\n this.isMouseActionButton_(pointerEvent)\n ) {\n this.emulateClick_(this.down_);\n }\n\n if (this.activePointers_.length === 0) {\n this.dragListenerKeys_.forEach(unlistenByKey);\n this.dragListenerKeys_.length = 0;\n this.dragging_ = false;\n this.down_ = null;\n }\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @return {boolean} If the left mouse button was pressed.\n * @private\n */\n isMouseActionButton_(pointerEvent) {\n return pointerEvent.button === 0;\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n handlePointerDown_(pointerEvent) {\n this.emulateClicks_ = this.activePointers_.length === 0;\n this.updateActivePointers_(pointerEvent);\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.POINTERDOWN,\n this.map_,\n pointerEvent,\n undefined,\n undefined,\n this.activePointers_\n );\n this.dispatchEvent(newEvent);\n\n this.down_ = new PointerEvent(pointerEvent.type, pointerEvent);\n Object.defineProperty(this.down_, 'target', {\n writable: false,\n value: pointerEvent.target,\n });\n\n if (this.dragListenerKeys_.length === 0) {\n const doc = this.map_.getOwnerDocument();\n this.dragListenerKeys_.push(\n listen(\n doc,\n MapBrowserEventType.POINTERMOVE,\n this.handlePointerMove_,\n this\n ),\n listen(doc, MapBrowserEventType.POINTERUP, this.handlePointerUp_, this),\n /* Note that the listener for `pointercancel is set up on\n * `pointerEventHandler_` and not `documentPointerEventHandler_` like\n * the `pointerup` and `pointermove` listeners.\n *\n * The reason for this is the following: `TouchSource.vacuumTouches_()`\n * issues `pointercancel` events, when there was no `touchend` for a\n * `touchstart`. Now, let's say a first `touchstart` is registered on\n * `pointerEventHandler_`. The `documentPointerEventHandler_` is set up.\n * But `documentPointerEventHandler_` doesn't know about the first\n * `touchstart`. If there is no `touchend` for the `touchstart`, we can\n * only receive a `touchcancel` from `pointerEventHandler_`, because it is\n * only registered there.\n */\n listen(\n this.element_,\n MapBrowserEventType.POINTERCANCEL,\n this.handlePointerUp_,\n this\n )\n );\n if (this.element_.getRootNode && this.element_.getRootNode() !== doc) {\n this.dragListenerKeys_.push(\n listen(\n this.element_.getRootNode(),\n MapBrowserEventType.POINTERUP,\n this.handlePointerUp_,\n this\n )\n );\n }\n }\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n handlePointerMove_(pointerEvent) {\n // Between pointerdown and pointerup, pointermove events are triggered.\n // To avoid a 'false' touchmove event to be dispatched, we test if the pointer\n // moved a significant distance.\n if (this.isMoving_(pointerEvent)) {\n this.updateActivePointers_(pointerEvent);\n this.dragging_ = true;\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.POINTERDRAG,\n this.map_,\n pointerEvent,\n this.dragging_,\n undefined,\n this.activePointers_\n );\n this.dispatchEvent(newEvent);\n }\n }\n\n /**\n * Wrap and relay a pointermove event.\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n relayMoveEvent_(pointerEvent) {\n this.originalPointerMoveEvent_ = pointerEvent;\n const dragging = !!(this.down_ && this.isMoving_(pointerEvent));\n this.dispatchEvent(\n new MapBrowserEvent(\n MapBrowserEventType.POINTERMOVE,\n this.map_,\n pointerEvent,\n dragging\n )\n );\n }\n\n /**\n * Flexible handling of a `touch-action: none` css equivalent: because calling\n * `preventDefault()` on a `pointermove` event does not stop native page scrolling\n * and zooming, we also listen for `touchmove` and call `preventDefault()` on it\n * when an interaction (currently `DragPan` handles the event.\n * @param {TouchEvent} event Event.\n * @private\n */\n handleTouchMove_(event) {\n // Due to https://github.com/mpizenberg/elm-pep/issues/2, `this.originalPointerMoveEvent_`\n // may not be initialized yet when we get here on a platform without native pointer events,\n // when elm-pep is used as pointer events polyfill.\n const originalEvent = this.originalPointerMoveEvent_;\n if (\n (!originalEvent || originalEvent.defaultPrevented) &&\n (typeof event.cancelable !== 'boolean' || event.cancelable === true)\n ) {\n event.preventDefault();\n }\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @return {boolean} Is moving.\n * @private\n */\n isMoving_(pointerEvent) {\n return (\n this.dragging_ ||\n Math.abs(pointerEvent.clientX - this.down_.clientX) >\n this.moveTolerance_ ||\n Math.abs(pointerEvent.clientY - this.down_.clientY) > this.moveTolerance_\n );\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n if (this.relayedListenerKey_) {\n unlistenByKey(this.relayedListenerKey_);\n this.relayedListenerKey_ = null;\n }\n this.element_.removeEventListener(\n EventType.TOUCHMOVE,\n this.boundHandleTouchMove_\n );\n\n if (this.pointerdownListenerKey_) {\n unlistenByKey(this.pointerdownListenerKey_);\n this.pointerdownListenerKey_ = null;\n }\n\n this.dragListenerKeys_.forEach(unlistenByKey);\n this.dragListenerKeys_.length = 0;\n\n this.element_ = null;\n super.disposeInternal();\n }\n}\n\nexport default MapBrowserEventHandler;\n","/**\n * @module ol/MapEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered after a map frame is rendered.\n * @event module:ol/MapEvent~MapEvent#postrender\n * @api\n */\n POSTRENDER: 'postrender',\n\n /**\n * Triggered when the map starts moving.\n * @event module:ol/MapEvent~MapEvent#movestart\n * @api\n */\n MOVESTART: 'movestart',\n\n /**\n * Triggered after the map is moved.\n * @event module:ol/MapEvent~MapEvent#moveend\n * @api\n */\n MOVEEND: 'moveend',\n\n /**\n * Triggered when loading of additional map data (tiles, images, features) starts.\n * @event module:ol/MapEvent~MapEvent#loadstart\n * @api\n */\n LOADSTART: 'loadstart',\n\n /**\n * Triggered when loading of additional map data has completed.\n * @event module:ol/MapEvent~MapEvent#loadend\n * @api\n */\n LOADEND: 'loadend',\n};\n\n/***\n * @typedef {'postrender'|'movestart'|'moveend'|'loadstart'|'loadend'} Types\n */\n","/**\n * @module ol/MapProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n LAYERGROUP: 'layergroup',\n SIZE: 'size',\n TARGET: 'target',\n VIEW: 'view',\n};\n","/**\n * @module ol/structs/PriorityQueue\n */\nimport {assert} from '../asserts.js';\nimport {clear} from '../obj.js';\n\n/**\n * @type {number}\n */\nexport const DROP = Infinity;\n\n/**\n * @classdesc\n * Priority queue.\n *\n * The implementation is inspired from the Closure Library's Heap class and\n * Python's heapq module.\n *\n * See https://github.com/google/closure-library/blob/master/closure/goog/structs/heap.js\n * and https://hg.python.org/cpython/file/2.7/Lib/heapq.py.\n *\n * @template T\n */\nclass PriorityQueue {\n /**\n * @param {function(T): number} priorityFunction Priority function.\n * @param {function(T): string} keyFunction Key function.\n */\n constructor(priorityFunction, keyFunction) {\n /**\n * @type {function(T): number}\n * @private\n */\n this.priorityFunction_ = priorityFunction;\n\n /**\n * @type {function(T): string}\n * @private\n */\n this.keyFunction_ = keyFunction;\n\n /**\n * @type {Array}\n * @private\n */\n this.elements_ = [];\n\n /**\n * @type {Array}\n * @private\n */\n this.priorities_ = [];\n\n /**\n * @type {!Object}\n * @private\n */\n this.queuedElements_ = {};\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n clear() {\n this.elements_.length = 0;\n this.priorities_.length = 0;\n clear(this.queuedElements_);\n }\n\n /**\n * Remove and return the highest-priority element. O(log N).\n * @return {T} Element.\n */\n dequeue() {\n const elements = this.elements_;\n const priorities = this.priorities_;\n const element = elements[0];\n if (elements.length == 1) {\n elements.length = 0;\n priorities.length = 0;\n } else {\n elements[0] = elements.pop();\n priorities[0] = priorities.pop();\n this.siftUp_(0);\n }\n const elementKey = this.keyFunction_(element);\n delete this.queuedElements_[elementKey];\n return element;\n }\n\n /**\n * Enqueue an element. O(log N).\n * @param {T} element Element.\n * @return {boolean} The element was added to the queue.\n */\n enqueue(element) {\n assert(\n !(this.keyFunction_(element) in this.queuedElements_),\n 'Tried to enqueue an `element` that was already added to the queue'\n );\n const priority = this.priorityFunction_(element);\n if (priority != DROP) {\n this.elements_.push(element);\n this.priorities_.push(priority);\n this.queuedElements_[this.keyFunction_(element)] = true;\n this.siftDown_(0, this.elements_.length - 1);\n return true;\n }\n return false;\n }\n\n /**\n * @return {number} Count.\n */\n getCount() {\n return this.elements_.length;\n }\n\n /**\n * Gets the index of the left child of the node at the given index.\n * @param {number} index The index of the node to get the left child for.\n * @return {number} The index of the left child.\n * @private\n */\n getLeftChildIndex_(index) {\n return index * 2 + 1;\n }\n\n /**\n * Gets the index of the right child of the node at the given index.\n * @param {number} index The index of the node to get the right child for.\n * @return {number} The index of the right child.\n * @private\n */\n getRightChildIndex_(index) {\n return index * 2 + 2;\n }\n\n /**\n * Gets the index of the parent of the node at the given index.\n * @param {number} index The index of the node to get the parent for.\n * @return {number} The index of the parent.\n * @private\n */\n getParentIndex_(index) {\n return (index - 1) >> 1;\n }\n\n /**\n * Make this a heap. O(N).\n * @private\n */\n heapify_() {\n let i;\n for (i = (this.elements_.length >> 1) - 1; i >= 0; i--) {\n this.siftUp_(i);\n }\n }\n\n /**\n * @return {boolean} Is empty.\n */\n isEmpty() {\n return this.elements_.length === 0;\n }\n\n /**\n * @param {string} key Key.\n * @return {boolean} Is key queued.\n */\n isKeyQueued(key) {\n return key in this.queuedElements_;\n }\n\n /**\n * @param {T} element Element.\n * @return {boolean} Is queued.\n */\n isQueued(element) {\n return this.isKeyQueued(this.keyFunction_(element));\n }\n\n /**\n * @param {number} index The index of the node to move down.\n * @private\n */\n siftUp_(index) {\n const elements = this.elements_;\n const priorities = this.priorities_;\n const count = elements.length;\n const element = elements[index];\n const priority = priorities[index];\n const startIndex = index;\n\n while (index < count >> 1) {\n const lIndex = this.getLeftChildIndex_(index);\n const rIndex = this.getRightChildIndex_(index);\n\n const smallerChildIndex =\n rIndex < count && priorities[rIndex] < priorities[lIndex]\n ? rIndex\n : lIndex;\n\n elements[index] = elements[smallerChildIndex];\n priorities[index] = priorities[smallerChildIndex];\n index = smallerChildIndex;\n }\n\n elements[index] = element;\n priorities[index] = priority;\n this.siftDown_(startIndex, index);\n }\n\n /**\n * @param {number} startIndex The index of the root.\n * @param {number} index The index of the node to move up.\n * @private\n */\n siftDown_(startIndex, index) {\n const elements = this.elements_;\n const priorities = this.priorities_;\n const element = elements[index];\n const priority = priorities[index];\n\n while (index > startIndex) {\n const parentIndex = this.getParentIndex_(index);\n if (priorities[parentIndex] > priority) {\n elements[index] = elements[parentIndex];\n priorities[index] = priorities[parentIndex];\n index = parentIndex;\n } else {\n break;\n }\n }\n elements[index] = element;\n priorities[index] = priority;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n reprioritize() {\n const priorityFunction = this.priorityFunction_;\n const elements = this.elements_;\n const priorities = this.priorities_;\n let index = 0;\n const n = elements.length;\n let element, i, priority;\n for (i = 0; i < n; ++i) {\n element = elements[i];\n priority = priorityFunction(element);\n if (priority == DROP) {\n delete this.queuedElements_[this.keyFunction_(element)];\n } else {\n priorities[index] = priority;\n elements[index++] = element;\n }\n }\n elements.length = index;\n priorities.length = index;\n this.heapify_();\n }\n}\n\nexport default PriorityQueue;\n","/**\n * @module ol/TileState\n */\n\n/**\n * @enum {number}\n */\nexport default {\n IDLE: 0,\n LOADING: 1,\n LOADED: 2,\n /**\n * Indicates that tile loading failed\n * @type {number}\n */\n ERROR: 3,\n EMPTY: 4,\n};\n","/**\n * @module ol/TileQueue\n */\nimport EventType from './events/EventType.js';\nimport PriorityQueue, {DROP} from './structs/PriorityQueue.js';\nimport TileState from './TileState.js';\n\n/**\n * @typedef {function(import(\"./Tile.js\").default, string, import(\"./coordinate.js\").Coordinate, number): number} PriorityFunction\n */\n\nclass TileQueue extends PriorityQueue {\n /**\n * @param {PriorityFunction} tilePriorityFunction Tile priority function.\n * @param {function(): ?} tileChangeCallback Function called on each tile change event.\n */\n constructor(tilePriorityFunction, tileChangeCallback) {\n super(\n /**\n * @param {Array} element Element.\n * @return {number} Priority.\n */\n function (element) {\n return tilePriorityFunction.apply(null, element);\n },\n /**\n * @param {Array} element Element.\n * @return {string} Key.\n */\n function (element) {\n return /** @type {import(\"./Tile.js\").default} */ (element[0]).getKey();\n }\n );\n\n /** @private */\n this.boundHandleTileChange_ = this.handleTileChange.bind(this);\n\n /**\n * @private\n * @type {function(): ?}\n */\n this.tileChangeCallback_ = tileChangeCallback;\n\n /**\n * @private\n * @type {number}\n */\n this.tilesLoading_ = 0;\n\n /**\n * @private\n * @type {!Object}\n */\n this.tilesLoadingKeys_ = {};\n }\n\n /**\n * @param {Array} element Element.\n * @return {boolean} The element was added to the queue.\n */\n enqueue(element) {\n const added = super.enqueue(element);\n if (added) {\n const tile = element[0];\n tile.addEventListener(EventType.CHANGE, this.boundHandleTileChange_);\n }\n return added;\n }\n\n /**\n * @return {number} Number of tiles loading.\n */\n getTilesLoading() {\n return this.tilesLoading_;\n }\n\n /**\n * @param {import(\"./events/Event.js\").default} event Event.\n * @protected\n */\n handleTileChange(event) {\n const tile = /** @type {import(\"./Tile.js\").default} */ (event.target);\n const state = tile.getState();\n if (\n state === TileState.LOADED ||\n state === TileState.ERROR ||\n state === TileState.EMPTY\n ) {\n if (state !== TileState.ERROR) {\n tile.removeEventListener(EventType.CHANGE, this.boundHandleTileChange_);\n }\n const tileKey = tile.getKey();\n if (tileKey in this.tilesLoadingKeys_) {\n delete this.tilesLoadingKeys_[tileKey];\n --this.tilesLoading_;\n }\n this.tileChangeCallback_();\n }\n }\n\n /**\n * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.\n * @param {number} maxNewLoads Maximum number of new tiles to load.\n */\n loadMoreTiles(maxTotalLoading, maxNewLoads) {\n let newLoads = 0;\n let state, tile, tileKey;\n while (\n this.tilesLoading_ < maxTotalLoading &&\n newLoads < maxNewLoads &&\n this.getCount() > 0\n ) {\n tile = /** @type {import(\"./Tile.js\").default} */ (this.dequeue()[0]);\n tileKey = tile.getKey();\n state = tile.getState();\n if (state === TileState.IDLE && !(tileKey in this.tilesLoadingKeys_)) {\n this.tilesLoadingKeys_[tileKey] = true;\n ++this.tilesLoading_;\n ++newLoads;\n tile.load();\n }\n }\n }\n}\n\nexport default TileQueue;\n\n/**\n * @param {import('./Map.js').FrameState} frameState Frame state.\n * @param {import(\"./Tile.js\").default} tile Tile.\n * @param {string} tileSourceKey Tile source key.\n * @param {import(\"./coordinate.js\").Coordinate} tileCenter Tile center.\n * @param {number} tileResolution Tile resolution.\n * @return {number} Tile priority.\n */\nexport function getTilePriority(\n frameState,\n tile,\n tileSourceKey,\n tileCenter,\n tileResolution\n) {\n // Filter out tiles at higher zoom levels than the current zoom level, or that\n // are outside the visible extent.\n if (!frameState || !(tileSourceKey in frameState.wantedTiles)) {\n return DROP;\n }\n if (!frameState.wantedTiles[tileSourceKey][tile.getKey()]) {\n return DROP;\n }\n // Prioritize the highest zoom level tiles closest to the focus.\n // Tiles at higher zoom levels are prioritized using Math.log(tileResolution).\n // Within a zoom level, tiles are prioritized by the distance in pixels between\n // the center of the tile and the center of the viewport. The factor of 65536\n // means that the prioritization should behave as desired for tiles up to\n // 65536 * Math.log(2) = 45426 pixels from the focus.\n const center = frameState.viewState.center;\n const deltaX = tileCenter[0] - center[0];\n const deltaY = tileCenter[1] - center[1];\n return (\n 65536 * Math.log(tileResolution) +\n Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution\n );\n}\n","/**\n * @module ol/control/Control\n */\nimport BaseObject from '../Object.js';\nimport MapEventType from '../MapEventType.js';\nimport {VOID} from '../functions.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {removeNode} from '../dom.js';\n\n/**\n * @typedef {Object} Options\n * @property {HTMLElement} [element] The element is the control's\n * container element. This only needs to be specified if you're developing\n * a custom control.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when\n * the control should be re-rendered. This is called in a `requestAnimationFrame`\n * callback.\n * @property {HTMLElement|string} [target] Specify a target if you want\n * the control to be rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A control is a visible widget with a DOM element in a fixed position on the\n * screen. They can involve user input (buttons), or be informational only;\n * the position is determined using CSS. By default these are placed in the\n * container with CSS class name `ol-overlaycontainer-stopevent`, but can use\n * any outside DOM element.\n *\n * This is the base class for controls. You can use it for simple custom\n * controls by creating the element with listeners, creating an instance:\n * ```js\n * const myControl = new Control({element: myElement});\n * ```\n * and then adding this to the map.\n *\n * The main advantage of having this as a control rather than a simple separate\n * DOM element is that preventing propagation is handled for you. Controls\n * will also be objects in a {@link module:ol/Collection~Collection}, so you can use their methods.\n *\n * You can also extend this base for your own control class. See\n * examples/custom-controls for an example of how to do this.\n *\n * @api\n */\nclass Control extends BaseObject {\n /**\n * @param {Options} options Control options.\n */\n constructor(options) {\n super();\n\n const element = options.element;\n if (element && !options.target && !element.style.pointerEvents) {\n element.style.pointerEvents = 'auto';\n }\n\n /**\n * @protected\n * @type {HTMLElement}\n */\n this.element = element ? element : null;\n\n /**\n * @private\n * @type {HTMLElement}\n */\n this.target_ = null;\n\n /**\n * @private\n * @type {import(\"../Map.js\").default|null}\n */\n this.map_ = null;\n\n /**\n * @protected\n * @type {!Array}\n */\n this.listenerKeys = [];\n\n if (options.render) {\n this.render = options.render;\n }\n\n if (options.target) {\n this.setTarget(options.target);\n }\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n removeNode(this.element);\n super.disposeInternal();\n }\n\n /**\n * Get the map associated with this control.\n * @return {import(\"../Map.js\").default|null} Map.\n * @api\n */\n getMap() {\n return this.map_;\n }\n\n /**\n * Remove the control from its current map and attach it to the new map.\n * Pass `null` to just remove the control from the current map.\n * Subclasses may set up event handlers to get notified about changes to\n * the map here.\n * @param {import(\"../Map.js\").default|null} map Map.\n * @api\n */\n setMap(map) {\n if (this.map_) {\n removeNode(this.element);\n }\n for (let i = 0, ii = this.listenerKeys.length; i < ii; ++i) {\n unlistenByKey(this.listenerKeys[i]);\n }\n this.listenerKeys.length = 0;\n this.map_ = map;\n if (map) {\n const target = this.target_\n ? this.target_\n : map.getOverlayContainerStopEvent();\n target.appendChild(this.element);\n if (this.render !== VOID) {\n this.listenerKeys.push(\n listen(map, MapEventType.POSTRENDER, this.render, this)\n );\n }\n map.render();\n }\n }\n\n /**\n * Renders the control.\n * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n * @api\n */\n render(mapEvent) {}\n\n /**\n * This function is used to set a target element for the control. It has no\n * effect if it is called after the control has been added to the map (i.e.\n * after `setMap` is called on the control). If no `target` is set in the\n * options passed to the control constructor and if `setTarget` is not called\n * then the control is added to the map's overlay container.\n * @param {HTMLElement|string} target Target.\n * @api\n */\n setTarget(target) {\n this.target_ =\n typeof target === 'string' ? document.getElementById(target) : target;\n }\n}\n\nexport default Control;\n","/**\n * @module ol/control/Attribution\n */\nimport Control from './Control.js';\nimport EventType from '../events/EventType.js';\nimport {CLASS_COLLAPSED, CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';\nimport {equals} from '../array.js';\nimport {removeChildren, replaceNode} from '../dom.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-attribution'] CSS class name.\n * @property {HTMLElement|string} [target] Specify a target if you\n * want the control to be rendered outside of the map's\n * viewport.\n * @property {boolean} [collapsible] Specify if attributions can\n * be collapsed. If not specified, sources control this behavior with their\n * `attributionsCollapsible` setting.\n * @property {boolean} [collapsed=true] Specify if attributions should\n * be collapsed at startup.\n * @property {string} [tipLabel='Attributions'] Text label to use for the button tip.\n * @property {string|HTMLElement} [label='i'] Text label to use for the\n * collapsed attributions button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [expandClassName=className + '-expand'] CSS class name for the\n * collapsed attributions button.\n * @property {string|HTMLElement} [collapseLabel='›'] Text label to use\n * for the expanded attributions button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [collapseClassName=className + '-collapse'] CSS class name for the\n * expanded attributions button.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when\n * the control should be re-rendered. This is called in a `requestAnimationFrame`\n * callback.\n */\n\n/**\n * @classdesc\n * Control to show all the attributions associated with the layer sources\n * in the map. This control is one of the default controls included in maps.\n * By default it will show in the bottom right portion of the map, but this can\n * be changed by using a css selector for `.ol-attribution`.\n *\n * @api\n */\nclass Attribution extends Control {\n /**\n * @param {Options} [options] Attribution options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n element: document.createElement('div'),\n render: options.render,\n target: options.target,\n });\n\n /**\n * @private\n * @type {HTMLElement}\n */\n this.ulElement_ = document.createElement('ul');\n\n /**\n * @private\n * @type {boolean}\n */\n this.collapsed_ =\n options.collapsed !== undefined ? options.collapsed : true;\n\n /**\n * @private\n * @type {boolean}\n */\n this.userCollapsed_ = this.collapsed_;\n\n /**\n * @private\n * @type {boolean}\n */\n this.overrideCollapsible_ = options.collapsible !== undefined;\n\n /**\n * @private\n * @type {boolean}\n */\n this.collapsible_ =\n options.collapsible !== undefined ? options.collapsible : true;\n\n if (!this.collapsible_) {\n this.collapsed_ = false;\n }\n\n const className =\n options.className !== undefined ? options.className : 'ol-attribution';\n\n const tipLabel =\n options.tipLabel !== undefined ? options.tipLabel : 'Attributions';\n\n const expandClassName =\n options.expandClassName !== undefined\n ? options.expandClassName\n : className + '-expand';\n\n const collapseLabel =\n options.collapseLabel !== undefined ? options.collapseLabel : '\\u203A';\n\n const collapseClassName =\n options.collapseClassName !== undefined\n ? options.collapseClassName\n : className + '-collapse';\n\n if (typeof collapseLabel === 'string') {\n /**\n * @private\n * @type {HTMLElement}\n */\n this.collapseLabel_ = document.createElement('span');\n this.collapseLabel_.textContent = collapseLabel;\n this.collapseLabel_.className = collapseClassName;\n } else {\n this.collapseLabel_ = collapseLabel;\n }\n\n const label = options.label !== undefined ? options.label : 'i';\n\n if (typeof label === 'string') {\n /**\n * @private\n * @type {HTMLElement}\n */\n this.label_ = document.createElement('span');\n this.label_.textContent = label;\n this.label_.className = expandClassName;\n } else {\n this.label_ = label;\n }\n\n const activeLabel =\n this.collapsible_ && !this.collapsed_ ? this.collapseLabel_ : this.label_;\n\n /**\n * @private\n * @type {HTMLElement}\n */\n this.toggleButton_ = document.createElement('button');\n this.toggleButton_.setAttribute('type', 'button');\n this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));\n this.toggleButton_.title = tipLabel;\n this.toggleButton_.appendChild(activeLabel);\n\n this.toggleButton_.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this),\n false\n );\n\n const cssClasses =\n className +\n ' ' +\n CLASS_UNSELECTABLE +\n ' ' +\n CLASS_CONTROL +\n (this.collapsed_ && this.collapsible_ ? ' ' + CLASS_COLLAPSED : '') +\n (this.collapsible_ ? '' : ' ol-uncollapsible');\n const element = this.element;\n element.className = cssClasses;\n element.appendChild(this.toggleButton_);\n element.appendChild(this.ulElement_);\n\n /**\n * A list of currently rendered resolutions.\n * @type {Array}\n * @private\n */\n this.renderedAttributions_ = [];\n\n /**\n * @private\n * @type {boolean}\n */\n this.renderedVisible_ = true;\n }\n\n /**\n * Collect a list of visible attributions and set the collapsible state.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @return {Array} Attributions.\n * @private\n */\n collectSourceAttributions_(frameState) {\n const visibleAttributions = Array.from(\n new Set(\n this.getMap()\n .getAllLayers()\n .flatMap((layer) => layer.getAttributions(frameState))\n )\n );\n\n const collapsible = !this.getMap()\n .getAllLayers()\n .some(\n (layer) =>\n layer.getSource() &&\n layer.getSource().getAttributionsCollapsible() === false\n );\n if (!this.overrideCollapsible_) {\n this.setCollapsible(collapsible);\n }\n return visibleAttributions;\n }\n\n /**\n * @private\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n */\n updateElement_(frameState) {\n if (!frameState) {\n if (this.renderedVisible_) {\n this.element.style.display = 'none';\n this.renderedVisible_ = false;\n }\n return;\n }\n\n const attributions = this.collectSourceAttributions_(frameState);\n\n const visible = attributions.length > 0;\n if (this.renderedVisible_ != visible) {\n this.element.style.display = visible ? '' : 'none';\n this.renderedVisible_ = visible;\n }\n\n if (equals(attributions, this.renderedAttributions_)) {\n return;\n }\n\n removeChildren(this.ulElement_);\n\n // append the attributions\n for (let i = 0, ii = attributions.length; i < ii; ++i) {\n const element = document.createElement('li');\n element.innerHTML = attributions[i];\n this.ulElement_.appendChild(element);\n }\n\n this.renderedAttributions_ = attributions;\n }\n\n /**\n * @param {MouseEvent} event The event to handle\n * @private\n */\n handleClick_(event) {\n event.preventDefault();\n this.handleToggle_();\n this.userCollapsed_ = this.collapsed_;\n }\n\n /**\n * @private\n */\n handleToggle_() {\n this.element.classList.toggle(CLASS_COLLAPSED);\n if (this.collapsed_) {\n replaceNode(this.collapseLabel_, this.label_);\n } else {\n replaceNode(this.label_, this.collapseLabel_);\n }\n this.collapsed_ = !this.collapsed_;\n this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));\n }\n\n /**\n * Return `true` if the attribution is collapsible, `false` otherwise.\n * @return {boolean} True if the widget is collapsible.\n * @api\n */\n getCollapsible() {\n return this.collapsible_;\n }\n\n /**\n * Set whether the attribution should be collapsible.\n * @param {boolean} collapsible True if the widget is collapsible.\n * @api\n */\n setCollapsible(collapsible) {\n if (this.collapsible_ === collapsible) {\n return;\n }\n this.collapsible_ = collapsible;\n this.element.classList.toggle('ol-uncollapsible');\n if (this.userCollapsed_) {\n this.handleToggle_();\n }\n }\n\n /**\n * Collapse or expand the attribution according to the passed parameter. Will\n * not do anything if the attribution isn't collapsible or if the current\n * collapsed state is already the one requested.\n * @param {boolean} collapsed True if the widget is collapsed.\n * @api\n */\n setCollapsed(collapsed) {\n this.userCollapsed_ = collapsed;\n if (!this.collapsible_ || this.collapsed_ === collapsed) {\n return;\n }\n this.handleToggle_();\n }\n\n /**\n * Return `true` when the attribution is currently collapsed or `false`\n * otherwise.\n * @return {boolean} True if the widget is collapsed.\n * @api\n */\n getCollapsed() {\n return this.collapsed_;\n }\n\n /**\n * Update the attribution element.\n * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n * @override\n */\n render(mapEvent) {\n this.updateElement_(mapEvent.frameState);\n }\n}\n\nexport default Attribution;\n","/**\n * @module ol/control/Rotate\n */\nimport Control from './Control.js';\nimport EventType from '../events/EventType.js';\nimport {CLASS_CONTROL, CLASS_HIDDEN, CLASS_UNSELECTABLE} from '../css.js';\nimport {easeOut} from '../easing.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-rotate'] CSS class name.\n * @property {string|HTMLElement} [label='⇧'] Text label to use for the rotate button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [tipLabel='Reset rotation'] Text label to use for the rotate tip.\n * @property {string} [compassClassName='ol-compass'] CSS class name for the compass.\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {boolean} [autoHide=true] Hide the control when rotation is 0.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when the control should\n * be re-rendered. This is called in a `requestAnimationFrame` callback.\n * @property {function():void} [resetNorth] Function called when the control is clicked.\n * This will override the default `resetNorth`.\n * @property {HTMLElement|string} [target] Specify a target if you want the control to be\n * rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A button control to reset rotation to 0.\n * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css\n * selector is added to the button when the rotation is 0.\n *\n * @api\n */\nclass Rotate extends Control {\n /**\n * @param {Options} [options] Rotate options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n element: document.createElement('div'),\n render: options.render,\n target: options.target,\n });\n\n const className =\n options.className !== undefined ? options.className : 'ol-rotate';\n\n const label = options.label !== undefined ? options.label : '\\u21E7';\n\n const compassClassName =\n options.compassClassName !== undefined\n ? options.compassClassName\n : 'ol-compass';\n\n /**\n * @type {HTMLElement}\n * @private\n */\n this.label_ = null;\n\n if (typeof label === 'string') {\n this.label_ = document.createElement('span');\n this.label_.className = compassClassName;\n this.label_.textContent = label;\n } else {\n this.label_ = label;\n this.label_.classList.add(compassClassName);\n }\n\n const tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation';\n\n const button = document.createElement('button');\n button.className = className + '-reset';\n button.setAttribute('type', 'button');\n button.title = tipLabel;\n button.appendChild(this.label_);\n\n button.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this),\n false\n );\n\n const cssClasses =\n className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;\n const element = this.element;\n element.className = cssClasses;\n element.appendChild(button);\n\n this.callResetNorth_ = options.resetNorth ? options.resetNorth : undefined;\n\n /**\n * @type {number}\n * @private\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n\n /**\n * @type {boolean}\n * @private\n */\n this.autoHide_ = options.autoHide !== undefined ? options.autoHide : true;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.rotation_ = undefined;\n\n if (this.autoHide_) {\n this.element.classList.add(CLASS_HIDDEN);\n }\n }\n\n /**\n * @param {MouseEvent} event The event to handle\n * @private\n */\n handleClick_(event) {\n event.preventDefault();\n if (this.callResetNorth_ !== undefined) {\n this.callResetNorth_();\n } else {\n this.resetNorth_();\n }\n }\n\n /**\n * @private\n */\n resetNorth_() {\n const map = this.getMap();\n const view = map.getView();\n if (!view) {\n // the map does not have a view, so we can't act\n // upon it\n return;\n }\n const rotation = view.getRotation();\n if (rotation !== undefined) {\n if (this.duration_ > 0 && rotation % (2 * Math.PI) !== 0) {\n view.animate({\n rotation: 0,\n duration: this.duration_,\n easing: easeOut,\n });\n } else {\n view.setRotation(0);\n }\n }\n }\n\n /**\n * Update the rotate control element.\n * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n * @override\n */\n render(mapEvent) {\n const frameState = mapEvent.frameState;\n if (!frameState) {\n return;\n }\n const rotation = frameState.viewState.rotation;\n if (rotation != this.rotation_) {\n const transform = 'rotate(' + rotation + 'rad)';\n if (this.autoHide_) {\n const contains = this.element.classList.contains(CLASS_HIDDEN);\n if (!contains && rotation === 0) {\n this.element.classList.add(CLASS_HIDDEN);\n } else if (contains && rotation !== 0) {\n this.element.classList.remove(CLASS_HIDDEN);\n }\n }\n this.label_.style.transform = transform;\n }\n this.rotation_ = rotation;\n }\n}\n\nexport default Rotate;\n","/**\n * @module ol/control/Zoom\n */\nimport Control from './Control.js';\nimport EventType from '../events/EventType.js';\nimport {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';\nimport {easeOut} from '../easing.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {string} [className='ol-zoom'] CSS class name.\n * @property {string} [zoomInClassName=className + '-in'] CSS class name for the zoom-in button.\n * @property {string} [zoomOutClassName=className + '-out'] CSS class name for the zoom-out button.\n * @property {string|HTMLElement} [zoomInLabel='+'] Text label to use for the zoom-in\n * button. Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string|HTMLElement} [zoomOutLabel='–'] Text label to use for the zoom-out button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [zoomInTipLabel='Zoom in'] Text label to use for the button tip.\n * @property {string} [zoomOutTipLabel='Zoom out'] Text label to use for the button tip.\n * @property {number} [delta=1] The zoom delta applied on each click.\n * @property {HTMLElement|string} [target] Specify a target if you want the control to be\n * rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A control with 2 buttons, one for zoom in and one for zoom out.\n * This control is one of the default controls of a map. To style this control\n * use css selectors `.ol-zoom-in` and `.ol-zoom-out`.\n *\n * @api\n */\nclass Zoom extends Control {\n /**\n * @param {Options} [options] Zoom options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n element: document.createElement('div'),\n target: options.target,\n });\n\n const className =\n options.className !== undefined ? options.className : 'ol-zoom';\n\n const delta = options.delta !== undefined ? options.delta : 1;\n\n const zoomInClassName =\n options.zoomInClassName !== undefined\n ? options.zoomInClassName\n : className + '-in';\n\n const zoomOutClassName =\n options.zoomOutClassName !== undefined\n ? options.zoomOutClassName\n : className + '-out';\n\n const zoomInLabel =\n options.zoomInLabel !== undefined ? options.zoomInLabel : '+';\n const zoomOutLabel =\n options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\\u2013';\n\n const zoomInTipLabel =\n options.zoomInTipLabel !== undefined ? options.zoomInTipLabel : 'Zoom in';\n const zoomOutTipLabel =\n options.zoomOutTipLabel !== undefined\n ? options.zoomOutTipLabel\n : 'Zoom out';\n\n const inElement = document.createElement('button');\n inElement.className = zoomInClassName;\n inElement.setAttribute('type', 'button');\n inElement.title = zoomInTipLabel;\n inElement.appendChild(\n typeof zoomInLabel === 'string'\n ? document.createTextNode(zoomInLabel)\n : zoomInLabel\n );\n\n inElement.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this, delta),\n false\n );\n\n const outElement = document.createElement('button');\n outElement.className = zoomOutClassName;\n outElement.setAttribute('type', 'button');\n outElement.title = zoomOutTipLabel;\n outElement.appendChild(\n typeof zoomOutLabel === 'string'\n ? document.createTextNode(zoomOutLabel)\n : zoomOutLabel\n );\n\n outElement.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this, -delta),\n false\n );\n\n const cssClasses =\n className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;\n const element = this.element;\n element.className = cssClasses;\n element.appendChild(inElement);\n element.appendChild(outElement);\n\n /**\n * @type {number}\n * @private\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * @param {number} delta Zoom delta.\n * @param {MouseEvent} event The event to handle\n * @private\n */\n handleClick_(delta, event) {\n event.preventDefault();\n this.zoomByDelta_(delta);\n }\n\n /**\n * @param {number} delta Zoom delta.\n * @private\n */\n zoomByDelta_(delta) {\n const map = this.getMap();\n const view = map.getView();\n if (!view) {\n // the map does not have a view, so we can't act\n // upon it\n return;\n }\n const currentZoom = view.getZoom();\n if (currentZoom !== undefined) {\n const newZoom = view.getConstrainedZoom(currentZoom + delta);\n if (this.duration_ > 0) {\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n view.animate({\n zoom: newZoom,\n duration: this.duration_,\n easing: easeOut,\n });\n } else {\n view.setZoom(newZoom);\n }\n }\n }\n}\n\nexport default Zoom;\n","/**\n * @module ol/control/defaults\n */\nimport Attribution from './Attribution.js';\nimport Collection from '../Collection.js';\nimport Rotate from './Rotate.js';\nimport Zoom from './Zoom.js';\n\n/**\n * @typedef {Object} DefaultsOptions\n * @property {boolean} [attribution=true] Include\n * {@link module:ol/control/Attribution~Attribution}.\n * @property {import(\"./Attribution.js\").Options} [attributionOptions]\n * Options for {@link module:ol/control/Attribution~Attribution}.\n * @property {boolean} [rotate=true] Include\n * {@link module:ol/control/Rotate~Rotate}.\n * @property {import(\"./Rotate.js\").Options} [rotateOptions] Options\n * for {@link module:ol/control/Rotate~Rotate}.\n * @property {boolean} [zoom] Include {@link module:ol/control/Zoom~Zoom}.\n * @property {import(\"./Zoom.js\").Options} [zoomOptions] Options for\n * {@link module:ol/control/Zoom~Zoom}.\n */\n\n/**\n * Set of controls included in maps by default. Unless configured otherwise,\n * this returns a collection containing an instance of each of the following\n * controls:\n * * {@link module:ol/control/Zoom~Zoom}\n * * {@link module:ol/control/Rotate~Rotate}\n * * {@link module:ol/control/Attribution~Attribution}\n *\n * @param {DefaultsOptions} [options] Options for the default controls.\n * @return {Collection} A collection of controls\n * to be used with the {@link module:ol/Map~Map} constructor's `controls` option.\n * @api\n */\nexport function defaults(options) {\n options = options ? options : {};\n\n /** @type {Collection} */\n const controls = new Collection();\n\n const zoomControl = options.zoom !== undefined ? options.zoom : true;\n if (zoomControl) {\n controls.push(new Zoom(options.zoomOptions));\n }\n\n const rotateControl = options.rotate !== undefined ? options.rotate : true;\n if (rotateControl) {\n controls.push(new Rotate(options.rotateOptions));\n }\n\n const attributionControl =\n options.attribution !== undefined ? options.attribution : true;\n if (attributionControl) {\n controls.push(new Attribution(options.attributionOptions));\n }\n\n return controls;\n}\n","/**\n * @module ol/interaction/Property\n */\n\n/**\n * @enum {string}\n */\nexport default {\n ACTIVE: 'active',\n};\n","/**\n * @module ol/interaction/Interaction\n */\nimport BaseObject from '../Object.js';\nimport InteractionProperty from './Property.js';\nimport {easeOut, linear} from '../easing.js';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} InteractionOnSignature\n */\n\n/**\n * Object literal with config options for interactions.\n * @typedef {Object} InteractionOptions\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} handleEvent\n * Method called by the map to notify the interaction that a browser event was\n * dispatched to the map. If the function returns a falsy value, propagation of\n * the event to other interactions in the map's interactions chain will be\n * prevented (this includes functions with no explicit return). The interactions\n * are traversed in reverse order of the interactions collection of the map.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * User actions that change the state of the map. Some are similar to controls,\n * but are not associated with a DOM element.\n * For example, {@link module:ol/interaction/KeyboardZoom~KeyboardZoom} is\n * functionally the same as {@link module:ol/control/Zoom~Zoom}, but triggered\n * by a keyboard event not a button element event.\n * Although interactions do not have a DOM element, some of them do render\n * vectors and so are visible on the screen.\n * @api\n */\nclass Interaction extends BaseObject {\n /**\n * @param {InteractionOptions} [options] Options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {InteractionOnSignature}\n */\n this.on;\n\n /***\n * @type {InteractionOnSignature}\n */\n this.once;\n\n /***\n * @type {InteractionOnSignature}\n */\n this.un;\n\n if (options && options.handleEvent) {\n this.handleEvent = options.handleEvent;\n }\n\n /**\n * @private\n * @type {import(\"../Map.js\").default|null}\n */\n this.map_ = null;\n\n this.setActive(true);\n }\n\n /**\n * Return whether the interaction is currently active.\n * @return {boolean} `true` if the interaction is active, `false` otherwise.\n * @observable\n * @api\n */\n getActive() {\n return /** @type {boolean} */ (this.get(InteractionProperty.ACTIVE));\n }\n\n /**\n * Get the map associated with this interaction.\n * @return {import(\"../Map.js\").default|null} Map.\n * @api\n */\n getMap() {\n return this.map_;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event}.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n * @api\n */\n handleEvent(mapBrowserEvent) {\n return true;\n }\n\n /**\n * Activate or deactivate the interaction.\n * @param {boolean} active Active.\n * @observable\n * @api\n */\n setActive(active) {\n this.set(InteractionProperty.ACTIVE, active);\n }\n\n /**\n * Remove the interaction from its current map and attach it to the new map.\n * Subclasses may set up event handlers to get notified about changes to\n * the map here.\n * @param {import(\"../Map.js\").default|null} map Map.\n */\n setMap(map) {\n this.map_ = map;\n }\n}\n\n/**\n * @param {import(\"../View.js\").default} view View.\n * @param {import(\"../coordinate.js\").Coordinate} delta Delta.\n * @param {number} [duration] Duration.\n */\nexport function pan(view, delta, duration) {\n const currentCenter = view.getCenterInternal();\n if (currentCenter) {\n const center = [currentCenter[0] + delta[0], currentCenter[1] + delta[1]];\n view.animateInternal({\n duration: duration !== undefined ? duration : 250,\n easing: linear,\n center: view.getConstrainedCenter(center),\n });\n }\n}\n\n/**\n * @param {import(\"../View.js\").default} view View.\n * @param {number} delta Delta from previous zoom level.\n * @param {import(\"../coordinate.js\").Coordinate} [anchor] Anchor coordinate in the user projection.\n * @param {number} [duration] Duration.\n */\nexport function zoomByDelta(view, delta, anchor, duration) {\n const currentZoom = view.getZoom();\n\n if (currentZoom === undefined) {\n return;\n }\n\n const newZoom = view.getConstrainedZoom(currentZoom + delta);\n const newResolution = view.getResolutionForZoom(newZoom);\n\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n view.animate({\n resolution: newResolution,\n anchor: anchor,\n duration: duration !== undefined ? duration : 250,\n easing: easeOut,\n });\n}\n\nexport default Interaction;\n","/**\n * @module ol/interaction/DoubleClickZoom\n */\nimport Interaction, {zoomByDelta} from './Interaction.js';\nimport MapBrowserEventType from '../MapBrowserEventType.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {number} [delta=1] The zoom delta applied on each double click.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom by double-clicking on the map.\n * @api\n */\nclass DoubleClickZoom extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n options = options ? options : {};\n\n /**\n * @private\n * @type {number}\n */\n this.delta_ = options.delta ? options.delta : 1;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a\n * doubleclick) and eventually zooms the map.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n let stopEvent = false;\n if (mapBrowserEvent.type == MapBrowserEventType.DBLCLICK) {\n const browserEvent = /** @type {MouseEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const map = mapBrowserEvent.map;\n const anchor = mapBrowserEvent.coordinate;\n const delta = browserEvent.shiftKey ? -this.delta_ : this.delta_;\n const view = map.getView();\n zoomByDelta(view, delta, anchor, this.duration_);\n browserEvent.preventDefault();\n stopEvent = true;\n }\n return !stopEvent;\n }\n}\n\nexport default DoubleClickZoom;\n","/**\n * @module ol/interaction/Pointer\n */\nimport Interaction from './Interaction.js';\nimport MapBrowserEventType from '../MapBrowserEventType.js';\n\n/**\n * @typedef {Object} Options\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleDownEvent]\n * Function handling \"down\" events. If the function returns `true` then a drag\n * sequence is started.\n * @property {function(import(\"../MapBrowserEvent.js\").default):void} [handleDragEvent]\n * Function handling \"drag\" events. This function is called on \"move\" events\n * during a drag sequence.\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleEvent]\n * Method called by the map to notify the interaction that a browser event was\n * dispatched to the map. The function may return `false` to prevent the\n * propagation of the event to other interactions in the map's interactions\n * chain.\n * @property {function(import(\"../MapBrowserEvent.js\").default):void} [handleMoveEvent]\n * Function handling \"move\" events. This function is called on \"move\" events.\n * This functions is also called during a drag sequence, so during a drag\n * sequence both the `handleDragEvent` function and this function are called.\n * If `handleDownEvent` is defined and it returns true this function will not\n * be called during a drag sequence.\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleUpEvent]\n * Function handling \"up\" events. If the function returns `false` then the\n * current drag sequence is stopped.\n * @property {function(boolean):boolean} [stopDown]\n * Should the down event be propagated to other interactions, or should be\n * stopped?\n */\n\n/**\n * @classdesc\n * Base class that calls user-defined functions on `down`, `move` and `up`\n * events. This class also manages \"drag sequences\".\n *\n * When the `handleDownEvent` user function returns `true` a drag sequence is\n * started. During a drag sequence the `handleDragEvent` user function is\n * called on `move` events. The drag sequence ends when the `handleUpEvent`\n * user function is called and returns `false`.\n * @api\n */\nclass PointerInteraction extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super(\n /** @type {import(\"./Interaction.js\").InteractionOptions} */ (options)\n );\n\n if (options.handleDownEvent) {\n this.handleDownEvent = options.handleDownEvent;\n }\n\n if (options.handleDragEvent) {\n this.handleDragEvent = options.handleDragEvent;\n }\n\n if (options.handleMoveEvent) {\n this.handleMoveEvent = options.handleMoveEvent;\n }\n\n if (options.handleUpEvent) {\n this.handleUpEvent = options.handleUpEvent;\n }\n\n if (options.stopDown) {\n this.stopDown = options.stopDown;\n }\n\n /**\n * @type {boolean}\n * @protected\n */\n this.handlingDownUpSequence = false;\n\n /**\n * @type {Array}\n * @protected\n */\n this.targetPointers = [];\n }\n\n /**\n * Returns the current number of pointers involved in the interaction,\n * e.g. `2` when two fingers are used.\n * @return {number} The number of pointers.\n * @api\n */\n getPointerCount() {\n return this.targetPointers.length;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n * @protected\n */\n handleDownEvent(mapBrowserEvent) {\n return false;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @protected\n */\n handleDragEvent(mapBrowserEvent) {}\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may call into\n * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are\n * detected.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n * @api\n */\n handleEvent(mapBrowserEvent) {\n if (!mapBrowserEvent.originalEvent) {\n return true;\n }\n\n let stopEvent = false;\n this.updateTrackedPointers_(mapBrowserEvent);\n if (this.handlingDownUpSequence) {\n if (mapBrowserEvent.type == MapBrowserEventType.POINTERDRAG) {\n this.handleDragEvent(mapBrowserEvent);\n // prevent page scrolling during dragging\n mapBrowserEvent.originalEvent.preventDefault();\n } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) {\n const handledUp = this.handleUpEvent(mapBrowserEvent);\n this.handlingDownUpSequence =\n handledUp && this.targetPointers.length > 0;\n }\n } else {\n if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) {\n const handled = this.handleDownEvent(mapBrowserEvent);\n this.handlingDownUpSequence = handled;\n stopEvent = this.stopDown(handled);\n } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE) {\n this.handleMoveEvent(mapBrowserEvent);\n }\n }\n return !stopEvent;\n }\n\n /**\n * Handle pointer move events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @protected\n */\n handleMoveEvent(mapBrowserEvent) {}\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n * @protected\n */\n handleUpEvent(mapBrowserEvent) {\n return false;\n }\n\n /**\n * This function is used to determine if \"down\" events should be propagated\n * to other interactions or should be stopped.\n * @param {boolean} handled Was the event handled by the interaction?\n * @return {boolean} Should the `down` event be stopped?\n */\n stopDown(handled) {\n return handled;\n }\n\n /**\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @private\n */\n updateTrackedPointers_(mapBrowserEvent) {\n if (mapBrowserEvent.activePointers) {\n this.targetPointers = mapBrowserEvent.activePointers;\n }\n }\n}\n\n/**\n * @param {Array} pointerEvents List of events.\n * @return {{clientX: number, clientY: number}} Centroid pixel.\n */\nexport function centroid(pointerEvents) {\n const length = pointerEvents.length;\n let clientX = 0;\n let clientY = 0;\n for (let i = 0; i < length; i++) {\n clientX += pointerEvents[i].clientX;\n clientY += pointerEvents[i].clientY;\n }\n return {clientX: clientX / length, clientY: clientY / length};\n}\n\nexport default PointerInteraction;\n","/**\n * @module ol/events/condition\n */\nimport MapBrowserEventType from '../MapBrowserEventType.js';\nimport {FALSE, TRUE} from '../functions.js';\nimport {MAC, WEBKIT} from '../has.js';\nimport {assert} from '../asserts.js';\n\n/**\n * A function that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * `{boolean}`. If the condition is met, true should be returned.\n *\n * @typedef {function(this: ?, import(\"../MapBrowserEvent.js\").default): boolean} Condition\n */\n\n/**\n * Creates a condition function that passes when all provided conditions pass.\n * @param {...Condition} var_args Conditions to check.\n * @return {Condition} Condition function.\n */\nexport function all(var_args) {\n const conditions = arguments;\n /**\n * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n * @return {boolean} All conditions passed.\n */\n return function (event) {\n let pass = true;\n for (let i = 0, ii = conditions.length; i < ii; ++i) {\n pass = pass && conditions[i](event);\n if (!pass) {\n break;\n }\n }\n return pass;\n };\n}\n\n/**\n * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when\n * additionally the shift-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the alt key is pressed.\n * @api\n */\nexport const altKeyOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n !originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise\n * (e.g. when additionally the platform-modifier-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the alt and shift keys are pressed.\n * @api\n */\nexport const altShiftKeysOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if the map has the focus. This condition requires a map target\n * element with a `tabindex` attribute, e.g. `
`.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} event Map browser event.\n * @return {boolean} The map has the focus.\n * @api\n */\nexport const focus = function (event) {\n const targetElement = event.map.getTargetElement();\n const activeElement = event.map.getOwnerDocument().activeElement;\n return targetElement.contains(activeElement);\n};\n\n/**\n * Return `true` if the map has the focus or no 'tabindex' attribute set.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} event Map browser event.\n * @return {boolean} The map container has the focus or no 'tabindex' attribute.\n */\nexport const focusWithTabindex = function (event) {\n return event.map.getTargetElement().hasAttribute('tabindex')\n ? focus(event)\n : true;\n};\n\n/**\n * Return always true.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True.\n * @api\n */\nexport const always = TRUE;\n\n/**\n * Return `true` if the event is a `click` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `click` event.\n * @api\n */\nexport const click = function (mapBrowserEvent) {\n return mapBrowserEvent.type == MapBrowserEventType.CLICK;\n};\n\n/**\n * Return `true` if the event has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} The result.\n */\nexport const mouseActionButton = function (mapBrowserEvent) {\n const originalEvent = /** @type {MouseEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return originalEvent.button == 0 && !(WEBKIT && MAC && originalEvent.ctrlKey);\n};\n\n/**\n * Return always false.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} False.\n * @api\n */\nexport const never = FALSE;\n\n/**\n * Return `true` if the browser event is a `pointermove` event, `false`\n * otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the browser event is a `pointermove` event.\n * @api\n */\nexport const pointerMove = function (mapBrowserEvent) {\n return mapBrowserEvent.type == 'pointermove';\n};\n\n/**\n * Return `true` if the event is a map `singleclick` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `singleclick` event.\n * @api\n */\nexport const singleClick = function (mapBrowserEvent) {\n return mapBrowserEvent.type == MapBrowserEventType.SINGLECLICK;\n};\n\n/**\n * Return `true` if the event is a map `dblclick` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `dblclick` event.\n * @api\n */\nexport const doubleClick = function (mapBrowserEvent) {\n return mapBrowserEvent.type == MapBrowserEventType.DBLCLICK;\n};\n\n/**\n * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is\n * pressed.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True only if there no modifier keys are pressed.\n * @api\n */\nexport const noModifierKeys = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n !originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n !originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if only the platform-modifier-key (the meta-key on Mac,\n * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally\n * the shift-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the platform modifier key is pressed.\n * @api\n */\nexport const platformModifierKeyOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n !originalEvent.altKey &&\n (MAC ? originalEvent.metaKey : originalEvent.ctrlKey) &&\n !originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if the platform-modifier-key (the meta-key on Mac,\n * ctrl-key otherwise) is pressed.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the platform modifier key is pressed.\n * @api\n */\nexport const platformModifierKey = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return MAC ? originalEvent.metaKey : originalEvent.ctrlKey;\n};\n\n/**\n * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when\n * additionally the alt-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the shift key is pressed.\n * @api\n */\nexport const shiftKeyOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n !originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if the target element is not editable, i.e. not an `input`,\n * `select`, or `textarea` element and no `contenteditable` attribute is\n * set or inherited, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True only if the target element is not editable.\n * @api\n */\nexport const targetNotEditable = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const tagName = /** @type {Element} */ (originalEvent.target).tagName;\n return (\n tagName !== 'INPUT' &&\n tagName !== 'SELECT' &&\n tagName !== 'TEXTAREA' &&\n // `isContentEditable` is only available on `HTMLElement`, but it may also be a\n // different type like `SVGElement`.\n // @ts-ignore\n !originalEvent.target.isContentEditable\n );\n};\n\n/**\n * Return `true` if the event originates from a mouse device.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a mouse device.\n * @api\n */\nexport const mouseOnly = function (mapBrowserEvent) {\n const pointerEvent = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(\n pointerEvent !== undefined,\n 'mapBrowserEvent must originate from a pointer event'\n );\n // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n return pointerEvent.pointerType == 'mouse';\n};\n\n/**\n * Return `true` if the event originates from a touchable device.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a touchable device.\n * @api\n */\nexport const touchOnly = function (mapBrowserEvent) {\n const pointerEvt = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(\n pointerEvt !== undefined,\n 'mapBrowserEvent must originate from a pointer event'\n );\n // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n return pointerEvt.pointerType === 'touch';\n};\n\n/**\n * Return `true` if the event originates from a digital pen.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a digital pen.\n * @api\n */\nexport const penOnly = function (mapBrowserEvent) {\n const pointerEvt = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(\n pointerEvt !== undefined,\n 'mapBrowserEvent must originate from a pointer event'\n );\n // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n return pointerEvt.pointerType === 'pen';\n};\n\n/**\n * Return `true` if the event originates from a primary pointer in\n * contact with the surface or if the left mouse button is pressed.\n * See https://www.w3.org/TR/pointerevents/#button-states.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a primary pointer.\n * @api\n */\nexport const primaryAction = function (mapBrowserEvent) {\n const pointerEvent = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(\n pointerEvent !== undefined,\n 'mapBrowserEvent must originate from a pointer event'\n );\n return pointerEvent.isPrimary && pointerEvent.button === 0;\n};\n","/**\n * @module ol/interaction/DragPan\n */\nimport PointerInteraction, {\n centroid as centroidFromPointers,\n} from './Pointer.js';\nimport {FALSE} from '../functions.js';\nimport {\n all,\n focusWithTabindex,\n noModifierKeys,\n primaryAction,\n} from '../events/condition.js';\nimport {easeOut} from '../easing.js';\nimport {\n rotate as rotateCoordinate,\n scale as scaleCoordinate,\n} from '../coordinate.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.noModifierKeys} and {@link module:ol/events/condition.primaryAction}.\n * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,\n * the interaction will only handle events when the map has the focus.\n * @property {import(\"../Kinetic.js\").default} [kinetic] Kinetic inertia to apply to the pan.\n */\n\n/**\n * @classdesc\n * Allows the user to pan the map by dragging the map.\n * @api\n */\nclass DragPan extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super({\n stopDown: FALSE,\n });\n\n options = options ? options : {};\n\n /**\n * @private\n * @type {import(\"../Kinetic.js\").default|undefined}\n */\n this.kinetic_ = options.kinetic;\n\n /**\n * @type {import(\"../pixel.js\").Pixel}\n */\n this.lastCentroid = null;\n\n /**\n * @type {number}\n */\n this.lastPointersCount_;\n\n /**\n * @type {boolean}\n */\n this.panning_ = false;\n\n const condition = options.condition\n ? options.condition\n : all(noModifierKeys, primaryAction);\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.onFocusOnly\n ? all(focusWithTabindex, condition)\n : condition;\n\n /**\n * @private\n * @type {boolean}\n */\n this.noKinetic_ = false;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n const map = mapBrowserEvent.map;\n if (!this.panning_) {\n this.panning_ = true;\n map.getView().beginInteraction();\n }\n const targetPointers = this.targetPointers;\n const centroid = map.getEventPixel(centroidFromPointers(targetPointers));\n if (targetPointers.length == this.lastPointersCount_) {\n if (this.kinetic_) {\n this.kinetic_.update(centroid[0], centroid[1]);\n }\n if (this.lastCentroid) {\n const delta = [\n this.lastCentroid[0] - centroid[0],\n centroid[1] - this.lastCentroid[1],\n ];\n const map = mapBrowserEvent.map;\n const view = map.getView();\n scaleCoordinate(delta, view.getResolution());\n rotateCoordinate(delta, view.getRotation());\n view.adjustCenterInternal(delta);\n }\n } else if (this.kinetic_) {\n // reset so we don't overestimate the kinetic energy after\n // after one finger down, tiny drag, second finger down\n this.kinetic_.begin();\n }\n this.lastCentroid = centroid;\n this.lastPointersCount_ = targetPointers.length;\n mapBrowserEvent.originalEvent.preventDefault();\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n if (this.targetPointers.length === 0) {\n if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) {\n const distance = this.kinetic_.getDistance();\n const angle = this.kinetic_.getAngle();\n const center = view.getCenterInternal();\n const centerpx = map.getPixelFromCoordinateInternal(center);\n const dest = map.getCoordinateFromPixelInternal([\n centerpx[0] - distance * Math.cos(angle),\n centerpx[1] - distance * Math.sin(angle),\n ]);\n view.animateInternal({\n center: view.getConstrainedCenter(dest),\n duration: 500,\n easing: easeOut,\n });\n }\n if (this.panning_) {\n this.panning_ = false;\n view.endInteraction();\n }\n return false;\n }\n if (this.kinetic_) {\n // reset so we don't overestimate the kinetic energy after\n // after one finger up, tiny drag, second finger up\n this.kinetic_.begin();\n }\n this.lastCentroid = null;\n return true;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n this.lastCentroid = null;\n // stop any current animation\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n if (this.kinetic_) {\n this.kinetic_.begin();\n }\n // No kinetic as soon as more than one pointer on the screen is\n // detected. This is to prevent nasty pans after pinch.\n this.noKinetic_ = this.targetPointers.length > 1;\n return true;\n }\n return false;\n }\n}\n\nexport default DragPan;\n","/**\n * @module ol/interaction/DragRotate\n */\nimport PointerInteraction from './Pointer.js';\nimport {FALSE} from '../functions.js';\nimport {\n altShiftKeysOnly,\n mouseActionButton,\n mouseOnly,\n} from '../events/condition.js';\nimport {disable} from '../rotationconstraint.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes an\n * {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.altShiftKeysOnly}.\n * @property {number} [duration=250] Animation duration in milliseconds.\n */\n\n/**\n * @classdesc\n * Allows the user to rotate the map by clicking and dragging on the map,\n * normally combined with an {@link module:ol/events/condition} that limits\n * it to when the alt and shift keys are held down.\n *\n * This interaction is only supported for mouse devices.\n * @api\n */\nclass DragRotate extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n stopDown: FALSE,\n });\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.condition ? options.condition : altShiftKeysOnly;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lastAngle_ = undefined;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n if (!mouseOnly(mapBrowserEvent)) {\n return;\n }\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n if (view.getConstraints().rotation === disable) {\n return;\n }\n const size = map.getSize();\n const offset = mapBrowserEvent.pixel;\n const theta = Math.atan2(size[1] / 2 - offset[1], offset[0] - size[0] / 2);\n if (this.lastAngle_ !== undefined) {\n const delta = theta - this.lastAngle_;\n view.adjustRotationInternal(-delta);\n }\n this.lastAngle_ = theta;\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n if (!mouseOnly(mapBrowserEvent)) {\n return true;\n }\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n view.endInteraction(this.duration_);\n return false;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (!mouseOnly(mapBrowserEvent)) {\n return false;\n }\n\n if (\n mouseActionButton(mapBrowserEvent) &&\n this.condition_(mapBrowserEvent)\n ) {\n const map = mapBrowserEvent.map;\n map.getView().beginInteraction();\n this.lastAngle_ = undefined;\n return true;\n }\n return false;\n }\n}\n\nexport default DragRotate;\n","/**\n * @module ol/render/Box\n */\n\nimport Disposable from '../Disposable.js';\nimport Polygon from '../geom/Polygon.js';\n\nclass RenderBox extends Disposable {\n /**\n * @param {string} className CSS class name.\n */\n constructor(className) {\n super();\n\n /**\n * @type {import(\"../geom/Polygon.js\").default}\n * @private\n */\n this.geometry_ = null;\n\n /**\n * @type {HTMLDivElement}\n * @private\n */\n this.element_ = document.createElement('div');\n this.element_.style.position = 'absolute';\n this.element_.style.pointerEvents = 'auto';\n this.element_.className = 'ol-box ' + className;\n\n /**\n * @private\n * @type {import(\"../Map.js\").default|null}\n */\n this.map_ = null;\n\n /**\n * @private\n * @type {import(\"../pixel.js\").Pixel}\n */\n this.startPixel_ = null;\n\n /**\n * @private\n * @type {import(\"../pixel.js\").Pixel}\n */\n this.endPixel_ = null;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n this.setMap(null);\n }\n\n /**\n * @private\n */\n render_() {\n const startPixel = this.startPixel_;\n const endPixel = this.endPixel_;\n const px = 'px';\n const style = this.element_.style;\n style.left = Math.min(startPixel[0], endPixel[0]) + px;\n style.top = Math.min(startPixel[1], endPixel[1]) + px;\n style.width = Math.abs(endPixel[0] - startPixel[0]) + px;\n style.height = Math.abs(endPixel[1] - startPixel[1]) + px;\n }\n\n /**\n * @param {import(\"../Map.js\").default|null} map Map.\n */\n setMap(map) {\n if (this.map_) {\n this.map_.getOverlayContainer().removeChild(this.element_);\n const style = this.element_.style;\n style.left = 'inherit';\n style.top = 'inherit';\n style.width = 'inherit';\n style.height = 'inherit';\n }\n this.map_ = map;\n if (this.map_) {\n this.map_.getOverlayContainer().appendChild(this.element_);\n }\n }\n\n /**\n * @param {import(\"../pixel.js\").Pixel} startPixel Start pixel.\n * @param {import(\"../pixel.js\").Pixel} endPixel End pixel.\n */\n setPixels(startPixel, endPixel) {\n this.startPixel_ = startPixel;\n this.endPixel_ = endPixel;\n this.createOrUpdateGeometry();\n this.render_();\n }\n\n /**\n * Creates or updates the cached geometry.\n */\n createOrUpdateGeometry() {\n const startPixel = this.startPixel_;\n const endPixel = this.endPixel_;\n const pixels = [\n startPixel,\n [startPixel[0], endPixel[1]],\n endPixel,\n [endPixel[0], startPixel[1]],\n ];\n const coordinates = pixels.map(\n this.map_.getCoordinateFromPixelInternal,\n this.map_\n );\n // close the polygon\n coordinates[4] = coordinates[0].slice();\n if (!this.geometry_) {\n this.geometry_ = new Polygon([coordinates]);\n } else {\n this.geometry_.setCoordinates([coordinates]);\n }\n }\n\n /**\n * @return {import(\"../geom/Polygon.js\").default} Geometry.\n */\n getGeometry() {\n return this.geometry_;\n }\n}\n\nexport default RenderBox;\n","/**\n * @module ol/interaction/DragBox\n */\n// FIXME draw drag box\nimport Event from '../events/Event.js';\nimport PointerInteraction from './Pointer.js';\nimport RenderBox from '../render/Box.js';\nimport {mouseActionButton} from '../events/condition.js';\n\n/**\n * A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two\n * {@link module:ol/pixel~Pixel}s and returns a `{boolean}`. If the condition is met,\n * true should be returned.\n * @typedef {function(this: ?, import(\"../MapBrowserEvent.js\").default, import(\"../pixel.js\").Pixel, import(\"../pixel.js\").Pixel):boolean} EndCondition\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-dragbox'] CSS class name for styling the box.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link ol/events/condition~mouseActionButton}.\n * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the default\n * `boxEndCondition` function.\n * @property {EndCondition} [boxEndCondition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two\n * {@link module:ol/pixel~Pixel}s to indicate whether a `boxend` event should be fired.\n * Default is `true` if the area of the box is bigger than the `minArea` option.\n * @property {function(this:DragBox, import(\"../MapBrowserEvent.js\").default):void} [onBoxEnd] Code to execute just\n * before `boxend` is fired.\n */\n\n/**\n * @enum {string}\n */\nconst DragBoxEventType = {\n /**\n * Triggered upon drag box start.\n * @event DragBoxEvent#boxstart\n * @api\n */\n BOXSTART: 'boxstart',\n\n /**\n * Triggered on drag when box is active.\n * @event DragBoxEvent#boxdrag\n * @api\n */\n BOXDRAG: 'boxdrag',\n\n /**\n * Triggered upon drag box end.\n * @event DragBoxEvent#boxend\n * @api\n */\n BOXEND: 'boxend',\n\n /**\n * Triggered upon drag box canceled.\n * @event DragBoxEvent#boxcancel\n * @api\n */\n BOXCANCEL: 'boxcancel',\n};\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/interaction/DragBox~DragBox} instances are instances of\n * this type.\n */\nexport class DragBoxEvent extends Event {\n /**\n * @param {string} type The event type.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate The event coordinate.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Originating event.\n */\n constructor(type, coordinate, mapBrowserEvent) {\n super(type);\n\n /**\n * The coordinate of the drag event.\n * @const\n * @type {import(\"../coordinate.js\").Coordinate}\n * @api\n */\n this.coordinate = coordinate;\n\n /**\n * @const\n * @type {import(\"../MapBrowserEvent.js\").default}\n * @api\n */\n this.mapBrowserEvent = mapBrowserEvent;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature<'boxcancel'|'boxdrag'|'boxend'|'boxstart', DragBoxEvent, Return> &\n * import(\"../Observable\").CombinedOnSignature} DragBoxOnSignature\n */\n\n/**\n * @classdesc\n * Allows the user to draw a vector box by clicking and dragging on the map,\n * normally combined with an {@link module:ol/events/condition} that limits\n * it to when the shift or other key is held down. This is used, for example,\n * for zooming to a specific area of the map\n * (see {@link module:ol/interaction/DragZoom~DragZoom} and\n * {@link module:ol/interaction/DragRotateAndZoom~DragRotateAndZoom}).\n *\n * @fires DragBoxEvent\n * @api\n */\nclass DragBox extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {DragBoxOnSignature}\n */\n this.on;\n\n /***\n * @type {DragBoxOnSignature}\n */\n this.once;\n\n /***\n * @type {DragBoxOnSignature}\n */\n this.un;\n\n options = options ? options : {};\n\n /**\n * @type {import(\"../render/Box.js\").default}\n * @private\n */\n this.box_ = new RenderBox(options.className || 'ol-dragbox');\n\n /**\n * @type {number}\n * @private\n */\n this.minArea_ = options.minArea !== undefined ? options.minArea : 64;\n\n if (options.onBoxEnd) {\n this.onBoxEnd = options.onBoxEnd;\n }\n\n /**\n * @type {import(\"../pixel.js\").Pixel}\n * @private\n */\n this.startPixel_ = null;\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.condition ? options.condition : mouseActionButton;\n\n /**\n * @private\n * @type {EndCondition}\n */\n this.boxEndCondition_ = options.boxEndCondition\n ? options.boxEndCondition\n : this.defaultBoxEndCondition;\n }\n\n /**\n * The default condition for determining whether the boxend event\n * should fire.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent The originating MapBrowserEvent\n * leading to the box end.\n * @param {import(\"../pixel.js\").Pixel} startPixel The starting pixel of the box.\n * @param {import(\"../pixel.js\").Pixel} endPixel The end pixel of the box.\n * @return {boolean} Whether or not the boxend condition should be fired.\n */\n defaultBoxEndCondition(mapBrowserEvent, startPixel, endPixel) {\n const width = endPixel[0] - startPixel[0];\n const height = endPixel[1] - startPixel[1];\n return width * width + height * height >= this.minArea_;\n }\n\n /**\n * Returns geometry of last drawn box.\n * @return {import(\"../geom/Polygon.js\").default} Geometry.\n * @api\n */\n getGeometry() {\n return this.box_.getGeometry();\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);\n\n this.dispatchEvent(\n new DragBoxEvent(\n DragBoxEventType.BOXDRAG,\n mapBrowserEvent.coordinate,\n mapBrowserEvent\n )\n );\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n this.box_.setMap(null);\n\n const completeBox = this.boxEndCondition_(\n mapBrowserEvent,\n this.startPixel_,\n mapBrowserEvent.pixel\n );\n if (completeBox) {\n this.onBoxEnd(mapBrowserEvent);\n }\n this.dispatchEvent(\n new DragBoxEvent(\n completeBox ? DragBoxEventType.BOXEND : DragBoxEventType.BOXCANCEL,\n mapBrowserEvent.coordinate,\n mapBrowserEvent\n )\n );\n return false;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.condition_(mapBrowserEvent)) {\n this.startPixel_ = mapBrowserEvent.pixel;\n this.box_.setMap(mapBrowserEvent.map);\n this.box_.setPixels(this.startPixel_, this.startPixel_);\n this.dispatchEvent(\n new DragBoxEvent(\n DragBoxEventType.BOXSTART,\n mapBrowserEvent.coordinate,\n mapBrowserEvent\n )\n );\n return true;\n }\n return false;\n }\n\n /**\n * Function to execute just before `onboxend` is fired\n * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n */\n onBoxEnd(event) {}\n}\n\nexport default DragBox;\n","/**\n * @module ol/interaction/DragZoom\n */\nimport DragBox from './DragBox.js';\nimport {easeOut} from '../easing.js';\nimport {shiftKeyOnly} from '../events/condition.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-dragzoom'] CSS class name for styling the\n * box.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.shiftKeyOnly}.\n * @property {number} [duration=200] Animation duration in milliseconds.\n * @property {boolean} [out=false] Use interaction for zooming out.\n * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the parent default\n * `boxEndCondition` function.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by clicking and dragging on the map,\n * normally combined with an {@link module:ol/events/condition} that limits\n * it to when a key, shift by default, is held down.\n *\n * To change the style of the box, use CSS and the `.ol-dragzoom` selector, or\n * your custom one configured with `className`.\n * @api\n */\nclass DragZoom extends DragBox {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n const condition = options.condition ? options.condition : shiftKeyOnly;\n\n super({\n condition: condition,\n className: options.className || 'ol-dragzoom',\n minArea: options.minArea,\n });\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 200;\n\n /**\n * @private\n * @type {boolean}\n */\n this.out_ = options.out !== undefined ? options.out : false;\n }\n\n /**\n * Function to execute just before `onboxend` is fired\n * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n */\n onBoxEnd(event) {\n const map = this.getMap();\n const view = /** @type {!import(\"../View.js\").default} */ (map.getView());\n let geometry = this.getGeometry();\n\n if (this.out_) {\n const rotatedExtent = view.rotatedExtentForGeometry(geometry);\n const resolution = view.getResolutionForExtentInternal(rotatedExtent);\n const factor = view.getResolution() / resolution;\n geometry = geometry.clone();\n geometry.scale(factor * factor);\n }\n\n view.fitInternal(geometry, {\n duration: this.duration_,\n easing: easeOut,\n });\n }\n}\n\nexport default DragZoom;\n","/**\n * @module ol/events/Key\n */\n\n/**\n * @enum {string}\n * @const\n */\nexport default {\n LEFT: 'ArrowLeft',\n UP: 'ArrowUp',\n RIGHT: 'ArrowRight',\n DOWN: 'ArrowDown',\n};\n","/**\n * @module ol/interaction/KeyboardPan\n */\nimport EventType from '../events/EventType.js';\nimport Interaction, {pan} from './Interaction.js';\nimport Key from '../events/Key.js';\nimport {noModifierKeys, targetNotEditable} from '../events/condition.js';\nimport {rotate as rotateCoordinate} from '../coordinate.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. Default is\n * {@link module:ol/events/condition.noModifierKeys} and\n * {@link module:ol/events/condition.targetNotEditable}.\n * @property {number} [duration=100] Animation duration in milliseconds.\n * @property {number} [pixelDelta=128] The amount of pixels to pan on each key\n * press.\n */\n\n/**\n * @classdesc\n * Allows the user to pan the map using keyboard arrows.\n * Note that, although this interaction is by default included in maps,\n * the keys can only be used when browser focus is on the element to which\n * the keyboard events are attached. By default, this is the map div,\n * though you can change this with the `keyboardEventTarget` in\n * {@link module:ol/Map~Map}. `document` never loses focus but, for any other\n * element, focus will have to be on, and returned to, this element if the keys\n * are to function.\n * See also {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}.\n * @api\n */\nclass KeyboardPan extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n options = options || {};\n\n /**\n * @private\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Browser event.\n * @return {boolean} Combined condition result.\n */\n this.defaultCondition_ = function (mapBrowserEvent) {\n return (\n noModifierKeys(mapBrowserEvent) && targetNotEditable(mapBrowserEvent)\n );\n };\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ =\n options.condition !== undefined\n ? options.condition\n : this.defaultCondition_;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 100;\n\n /**\n * @private\n * @type {number}\n */\n this.pixelDelta_ =\n options.pixelDelta !== undefined ? options.pixelDelta : 128;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a\n * `KeyEvent`, and decides the direction to pan to (if an arrow key was\n * pressed).\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n let stopEvent = false;\n if (mapBrowserEvent.type == EventType.KEYDOWN) {\n const keyEvent = /** @type {KeyboardEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const key = keyEvent.key;\n if (\n this.condition_(mapBrowserEvent) &&\n (key == Key.DOWN ||\n key == Key.LEFT ||\n key == Key.RIGHT ||\n key == Key.UP)\n ) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n const mapUnitsDelta = view.getResolution() * this.pixelDelta_;\n let deltaX = 0,\n deltaY = 0;\n if (key == Key.DOWN) {\n deltaY = -mapUnitsDelta;\n } else if (key == Key.LEFT) {\n deltaX = -mapUnitsDelta;\n } else if (key == Key.RIGHT) {\n deltaX = mapUnitsDelta;\n } else {\n deltaY = mapUnitsDelta;\n }\n const delta = [deltaX, deltaY];\n rotateCoordinate(delta, view.getRotation());\n pan(view, delta, this.duration_);\n keyEvent.preventDefault();\n stopEvent = true;\n }\n }\n return !stopEvent;\n }\n}\n\nexport default KeyboardPan;\n","/**\n * @module ol/interaction/KeyboardZoom\n */\nimport EventType from '../events/EventType.js';\nimport Interaction, {zoomByDelta} from './Interaction.js';\nimport {platformModifierKey, targetNotEditable} from '../events/condition.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=100] Animation duration in milliseconds.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. The default condition is\n * that {@link module:ol/events/condition.targetNotEditable} is fulfilled and that\n * the platform modifier key isn't pressed\n * (!{@link module:ol/events/condition.platformModifierKey}).\n * @property {number} [delta=1] The zoom level delta on each key press.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map using keyboard + and -.\n * Note that, although this interaction is by default included in maps,\n * the keys can only be used when browser focus is on the element to which\n * the keyboard events are attached. By default, this is the map div,\n * though you can change this with the `keyboardEventTarget` in\n * {@link module:ol/Map~Map}. `document` never loses focus but, for any other\n * element, focus will have to be on, and returned to, this element if the keys\n * are to function.\n * See also {@link module:ol/interaction/KeyboardPan~KeyboardPan}.\n * @api\n */\nclass KeyboardZoom extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n options = options ? options : {};\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.condition\n ? options.condition\n : function (mapBrowserEvent) {\n return (\n !platformModifierKey(mapBrowserEvent) &&\n targetNotEditable(mapBrowserEvent)\n );\n };\n\n /**\n * @private\n * @type {number}\n */\n this.delta_ = options.delta ? options.delta : 1;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 100;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a\n * `KeyEvent`, and decides whether to zoom in or out (depending on whether the\n * key pressed was '+' or '-').\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n let stopEvent = false;\n if (\n mapBrowserEvent.type == EventType.KEYDOWN ||\n mapBrowserEvent.type == EventType.KEYPRESS\n ) {\n const keyEvent = /** @type {KeyboardEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const key = keyEvent.key;\n if (this.condition_(mapBrowserEvent) && (key === '+' || key === '-')) {\n const map = mapBrowserEvent.map;\n const delta = key === '+' ? this.delta_ : -this.delta_;\n const view = map.getView();\n zoomByDelta(view, delta, undefined, this.duration_);\n keyEvent.preventDefault();\n stopEvent = true;\n }\n }\n return !stopEvent;\n }\n}\n\nexport default KeyboardZoom;\n","/**\n * @module ol/Kinetic\n */\n\n/**\n * @classdesc\n * Implementation of inertial deceleration for map movement.\n *\n * @api\n */\nclass Kinetic {\n /**\n * @param {number} decay Rate of decay (must be negative).\n * @param {number} minVelocity Minimum velocity (pixels/millisecond).\n * @param {number} delay Delay to consider to calculate the kinetic\n * initial values (milliseconds).\n */\n constructor(decay, minVelocity, delay) {\n /**\n * @private\n * @type {number}\n */\n this.decay_ = decay;\n\n /**\n * @private\n * @type {number}\n */\n this.minVelocity_ = minVelocity;\n\n /**\n * @private\n * @type {number}\n */\n this.delay_ = delay;\n\n /**\n * @private\n * @type {Array}\n */\n this.points_ = [];\n\n /**\n * @private\n * @type {number}\n */\n this.angle_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.initialVelocity_ = 0;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n begin() {\n this.points_.length = 0;\n this.angle_ = 0;\n this.initialVelocity_ = 0;\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n */\n update(x, y) {\n this.points_.push(x, y, Date.now());\n }\n\n /**\n * @return {boolean} Whether we should do kinetic animation.\n */\n end() {\n if (this.points_.length < 6) {\n // at least 2 points are required (i.e. there must be at least 6 elements\n // in the array)\n return false;\n }\n const delay = Date.now() - this.delay_;\n const lastIndex = this.points_.length - 3;\n if (this.points_[lastIndex + 2] < delay) {\n // the last tracked point is too old, which means that the user stopped\n // panning before releasing the map\n return false;\n }\n\n // get the first point which still falls into the delay time\n let firstIndex = lastIndex - 3;\n while (firstIndex > 0 && this.points_[firstIndex + 2] > delay) {\n firstIndex -= 3;\n }\n\n const duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2];\n // we don't want a duration of 0 (divide by zero)\n // we also make sure the user panned for a duration of at least one frame\n // (1/60s) to compute sane displacement values\n if (duration < 1000 / 60) {\n return false;\n }\n\n const dx = this.points_[lastIndex] - this.points_[firstIndex];\n const dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1];\n this.angle_ = Math.atan2(dy, dx);\n this.initialVelocity_ = Math.sqrt(dx * dx + dy * dy) / duration;\n return this.initialVelocity_ > this.minVelocity_;\n }\n\n /**\n * @return {number} Total distance travelled (pixels).\n */\n getDistance() {\n return (this.minVelocity_ - this.initialVelocity_) / this.decay_;\n }\n\n /**\n * @return {number} Angle of the kinetic panning animation (radians).\n */\n getAngle() {\n return this.angle_;\n }\n}\n\nexport default Kinetic;\n","/**\n * @module ol/interaction/MouseWheelZoom\n */\nimport EventType from '../events/EventType.js';\nimport Interaction, {zoomByDelta} from './Interaction.js';\nimport {DEVICE_PIXEL_RATIO, FIREFOX} from '../has.js';\nimport {all, always, focusWithTabindex} from '../events/condition.js';\nimport {clamp} from '../math.js';\n\n/**\n * @typedef {'trackpad' | 'wheel'} Mode\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. Default is\n * {@link module:ol/events/condition.always}.\n * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,\n * the interaction will only handle events when the map has the focus.\n * @property {number} [maxDelta=1] Maximum mouse wheel delta.\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {number} [timeout=80] Mouse wheel timeout duration in milliseconds.\n * @property {boolean} [useAnchor=true] Enable zooming using the mouse's\n * location as the anchor. When set to `false`, zooming in and out will zoom to\n * the center of the screen instead of zooming on the mouse's location.\n * @property {boolean} [constrainResolution=false] If true, the mouse wheel zoom\n * event will always animate to the closest zoom level after an interaction;\n * false means intermediary zoom levels are allowed.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by scrolling the mouse wheel.\n * @api\n */\nclass MouseWheelZoom extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super(\n /** @type {import(\"./Interaction.js\").InteractionOptions} */ (options)\n );\n\n /**\n * @private\n * @type {number}\n */\n this.totalDelta_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.lastDelta_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDelta_ = options.maxDelta !== undefined ? options.maxDelta : 1;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n\n /**\n * @private\n * @type {number}\n */\n this.timeout_ = options.timeout !== undefined ? options.timeout : 80;\n\n /**\n * @private\n * @type {boolean}\n */\n this.useAnchor_ =\n options.useAnchor !== undefined ? options.useAnchor : true;\n\n /**\n * @private\n * @type {boolean}\n */\n this.constrainResolution_ =\n options.constrainResolution !== undefined\n ? options.constrainResolution\n : false;\n\n const condition = options.condition ? options.condition : always;\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.onFocusOnly\n ? all(focusWithTabindex, condition)\n : condition;\n\n /**\n * @private\n * @type {?import(\"../coordinate.js\").Coordinate}\n */\n this.lastAnchor_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.startTime_ = undefined;\n\n /**\n * @private\n * @type {ReturnType}\n */\n this.timeoutId_;\n\n /**\n * @private\n * @type {Mode|undefined}\n */\n this.mode_ = undefined;\n\n /**\n * Trackpad events separated by this delay will be considered separate\n * interactions.\n * @private\n * @type {number}\n */\n this.trackpadEventGap_ = 400;\n\n /**\n * @private\n * @type {ReturnType}\n */\n this.trackpadTimeoutId_;\n\n /**\n * The number of delta values per zoom level\n * @private\n * @type {number}\n */\n this.deltaPerZoom_ = 300;\n }\n\n /**\n * @private\n */\n endInteraction_() {\n this.trackpadTimeoutId_ = undefined;\n const map = this.getMap();\n if (!map) {\n return;\n }\n const view = map.getView();\n view.endInteraction(\n undefined,\n this.lastDelta_ ? (this.lastDelta_ > 0 ? 1 : -1) : 0,\n this.lastAnchor_\n );\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a mousewheel-event) and eventually\n * zooms the map.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n if (!this.condition_(mapBrowserEvent)) {\n return true;\n }\n const type = mapBrowserEvent.type;\n if (type !== EventType.WHEEL) {\n return true;\n }\n\n const map = mapBrowserEvent.map;\n const wheelEvent = /** @type {WheelEvent} */ (\n mapBrowserEvent.originalEvent\n );\n wheelEvent.preventDefault();\n\n if (this.useAnchor_) {\n this.lastAnchor_ = mapBrowserEvent.coordinate;\n }\n\n // Delta normalisation inspired by\n // https://github.com/mapbox/mapbox-gl-js/blob/001c7b9/js/ui/handler/scroll_zoom.js\n let delta;\n if (mapBrowserEvent.type == EventType.WHEEL) {\n delta = wheelEvent.deltaY;\n if (FIREFOX && wheelEvent.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n delta /= DEVICE_PIXEL_RATIO;\n }\n if (wheelEvent.deltaMode === WheelEvent.DOM_DELTA_LINE) {\n delta *= 40;\n }\n }\n\n if (delta === 0) {\n return false;\n }\n this.lastDelta_ = delta;\n\n const now = Date.now();\n\n if (this.startTime_ === undefined) {\n this.startTime_ = now;\n }\n\n if (!this.mode_ || now - this.startTime_ > this.trackpadEventGap_) {\n this.mode_ = Math.abs(delta) < 4 ? 'trackpad' : 'wheel';\n }\n\n const view = map.getView();\n if (\n this.mode_ === 'trackpad' &&\n !(view.getConstrainResolution() || this.constrainResolution_)\n ) {\n if (this.trackpadTimeoutId_) {\n clearTimeout(this.trackpadTimeoutId_);\n } else {\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n view.beginInteraction();\n }\n this.trackpadTimeoutId_ = setTimeout(\n this.endInteraction_.bind(this),\n this.timeout_\n );\n view.adjustZoom(-delta / this.deltaPerZoom_, this.lastAnchor_);\n this.startTime_ = now;\n return false;\n }\n\n this.totalDelta_ += delta;\n\n const timeLeft = Math.max(this.timeout_ - (now - this.startTime_), 0);\n\n clearTimeout(this.timeoutId_);\n this.timeoutId_ = setTimeout(\n this.handleWheelZoom_.bind(this, map),\n timeLeft\n );\n\n return false;\n }\n\n /**\n * @private\n * @param {import(\"../Map.js\").default} map Map.\n */\n handleWheelZoom_(map) {\n const view = map.getView();\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n let delta =\n -clamp(\n this.totalDelta_,\n -this.maxDelta_ * this.deltaPerZoom_,\n this.maxDelta_ * this.deltaPerZoom_\n ) / this.deltaPerZoom_;\n if (view.getConstrainResolution() || this.constrainResolution_) {\n // view has a zoom constraint, zoom by 1\n delta = delta ? (delta > 0 ? 1 : -1) : 0;\n }\n zoomByDelta(view, delta, this.lastAnchor_, this.duration_);\n\n this.mode_ = undefined;\n this.totalDelta_ = 0;\n this.lastAnchor_ = null;\n this.startTime_ = undefined;\n this.timeoutId_ = undefined;\n }\n\n /**\n * Enable or disable using the mouse's location as an anchor when zooming\n * @param {boolean} useAnchor true to zoom to the mouse's location, false\n * to zoom to the center of the map\n * @api\n */\n setMouseAnchor(useAnchor) {\n this.useAnchor_ = useAnchor;\n if (!useAnchor) {\n this.lastAnchor_ = null;\n }\n }\n}\n\nexport default MouseWheelZoom;\n","/**\n * @module ol/interaction/PinchRotate\n */\nimport PointerInteraction, {\n centroid as centroidFromPointers,\n} from './Pointer.js';\nimport {FALSE} from '../functions.js';\nimport {disable} from '../rotationconstraint.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] The duration of the animation in\n * milliseconds.\n * @property {number} [threshold=0.3] Minimal angle in radians to start a rotation.\n */\n\n/**\n * @classdesc\n * Allows the user to rotate the map by twisting with two fingers\n * on a touch screen.\n * @api\n */\nclass PinchRotate extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n const pointerOptions = /** @type {import(\"./Pointer.js\").Options} */ (\n options\n );\n\n if (!pointerOptions.stopDown) {\n pointerOptions.stopDown = FALSE;\n }\n\n super(pointerOptions);\n\n /**\n * @private\n * @type {import(\"../coordinate.js\").Coordinate}\n */\n this.anchor_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lastAngle_ = undefined;\n\n /**\n * @private\n * @type {boolean}\n */\n this.rotating_ = false;\n\n /**\n * @private\n * @type {number}\n */\n this.rotationDelta_ = 0.0;\n\n /**\n * @private\n * @type {number}\n */\n this.threshold_ = options.threshold !== undefined ? options.threshold : 0.3;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n let rotationDelta = 0.0;\n\n const touch0 = this.targetPointers[0];\n const touch1 = this.targetPointers[1];\n\n // angle between touches\n const angle = Math.atan2(\n touch1.clientY - touch0.clientY,\n touch1.clientX - touch0.clientX\n );\n\n if (this.lastAngle_ !== undefined) {\n const delta = angle - this.lastAngle_;\n this.rotationDelta_ += delta;\n if (!this.rotating_ && Math.abs(this.rotationDelta_) > this.threshold_) {\n this.rotating_ = true;\n }\n rotationDelta = delta;\n }\n this.lastAngle_ = angle;\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n if (view.getConstraints().rotation === disable) {\n return;\n }\n\n // rotate anchor point.\n // FIXME: should be the intersection point between the lines:\n // touch0,touch1 and previousTouch0,previousTouch1\n this.anchor_ = map.getCoordinateFromPixelInternal(\n map.getEventPixel(centroidFromPointers(this.targetPointers))\n );\n\n // rotate\n if (this.rotating_) {\n map.render();\n view.adjustRotationInternal(rotationDelta, this.anchor_);\n }\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n if (this.targetPointers.length < 2) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n view.endInteraction(this.duration_);\n return false;\n }\n return true;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.targetPointers.length >= 2) {\n const map = mapBrowserEvent.map;\n this.anchor_ = null;\n this.lastAngle_ = undefined;\n this.rotating_ = false;\n this.rotationDelta_ = 0.0;\n if (!this.handlingDownUpSequence) {\n map.getView().beginInteraction();\n }\n return true;\n }\n return false;\n }\n}\n\nexport default PinchRotate;\n","/**\n * @module ol/interaction/PinchZoom\n */\nimport PointerInteraction, {\n centroid as centroidFromPointers,\n} from './Pointer.js';\nimport {FALSE} from '../functions.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=400] Animation duration in milliseconds.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by pinching with two fingers\n * on a touch screen.\n * @api\n */\nclass PinchZoom extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n const pointerOptions = /** @type {import(\"./Pointer.js\").Options} */ (\n options\n );\n\n if (!pointerOptions.stopDown) {\n pointerOptions.stopDown = FALSE;\n }\n\n super(pointerOptions);\n\n /**\n * @private\n * @type {import(\"../coordinate.js\").Coordinate}\n */\n this.anchor_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 400;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lastDistance_ = undefined;\n\n /**\n * @private\n * @type {number}\n */\n this.lastScaleDelta_ = 1;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n let scaleDelta = 1.0;\n\n const touch0 = this.targetPointers[0];\n const touch1 = this.targetPointers[1];\n const dx = touch0.clientX - touch1.clientX;\n const dy = touch0.clientY - touch1.clientY;\n\n // distance between touches\n const distance = Math.sqrt(dx * dx + dy * dy);\n\n if (this.lastDistance_ !== undefined) {\n scaleDelta = this.lastDistance_ / distance;\n }\n this.lastDistance_ = distance;\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n\n if (scaleDelta != 1.0) {\n this.lastScaleDelta_ = scaleDelta;\n }\n\n // scale anchor point.\n this.anchor_ = map.getCoordinateFromPixelInternal(\n map.getEventPixel(centroidFromPointers(this.targetPointers))\n );\n\n // scale, bypass the resolution constraint\n map.render();\n view.adjustResolutionInternal(scaleDelta, this.anchor_);\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n if (this.targetPointers.length < 2) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n const direction = this.lastScaleDelta_ > 1 ? 1 : -1;\n view.endInteraction(this.duration_, direction);\n return false;\n }\n return true;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.targetPointers.length >= 2) {\n const map = mapBrowserEvent.map;\n this.anchor_ = null;\n this.lastDistance_ = undefined;\n this.lastScaleDelta_ = 1;\n if (!this.handlingDownUpSequence) {\n map.getView().beginInteraction();\n }\n return true;\n }\n return false;\n }\n}\n\nexport default PinchZoom;\n","/**\n * @module ol/interaction/defaults\n */\nimport Collection from '../Collection.js';\nimport DoubleClickZoom from './DoubleClickZoom.js';\nimport DragPan from './DragPan.js';\nimport DragRotate from './DragRotate.js';\nimport DragZoom from './DragZoom.js';\nimport KeyboardPan from './KeyboardPan.js';\nimport KeyboardZoom from './KeyboardZoom.js';\nimport Kinetic from '../Kinetic.js';\nimport MouseWheelZoom from './MouseWheelZoom.js';\nimport PinchRotate from './PinchRotate.js';\nimport PinchZoom from './PinchZoom.js';\n\n/**\n * @typedef {Object} DefaultsOptions\n * @property {boolean} [altShiftDragRotate=true] Whether Alt-Shift-drag rotate is\n * desired.\n * @property {boolean} [onFocusOnly=false] Interact only when the map has the\n * focus. This affects the `MouseWheelZoom` and `DragPan` interactions and is\n * useful when page scroll is desired for maps that do not have the browser's\n * focus.\n * @property {boolean} [doubleClickZoom=true] Whether double click zoom is\n * desired.\n * @property {boolean} [keyboard=true] Whether keyboard interaction is desired.\n * @property {boolean} [mouseWheelZoom=true] Whether mousewheel zoom is desired.\n * @property {boolean} [shiftDragZoom=true] Whether Shift-drag zoom is desired.\n * @property {boolean} [dragPan=true] Whether drag pan is desired.\n * @property {boolean} [pinchRotate=true] Whether pinch rotate is desired.\n * @property {boolean} [pinchZoom=true] Whether pinch zoom is desired.\n * @property {number} [zoomDelta] Zoom level delta when using keyboard or double click zoom.\n * @property {number} [zoomDuration] Duration of the zoom animation in\n * milliseconds.\n */\n\n/**\n * Set of interactions included in maps by default. Specific interactions can be\n * excluded by setting the appropriate option to false in the constructor\n * options, but the order of the interactions is fixed. If you want to specify\n * a different order for interactions, you will need to create your own\n * {@link module:ol/interaction/Interaction~Interaction} instances and insert\n * them into a {@link module:ol/Collection~Collection} in the order you want\n * before creating your {@link module:ol/Map~Map} instance. Changing the order can\n * be of interest if the event propagation needs to be stopped at a point.\n * The default set of interactions, in sequence, is:\n * * {@link module:ol/interaction/DragRotate~DragRotate}\n * * {@link module:ol/interaction/DoubleClickZoom~DoubleClickZoom}\n * * {@link module:ol/interaction/DragPan~DragPan}\n * * {@link module:ol/interaction/PinchRotate~PinchRotate}\n * * {@link module:ol/interaction/PinchZoom~PinchZoom}\n * * {@link module:ol/interaction/KeyboardPan~KeyboardPan}\n * * {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}\n * * {@link module:ol/interaction/MouseWheelZoom~MouseWheelZoom}\n * * {@link module:ol/interaction/DragZoom~DragZoom}\n *\n * @param {DefaultsOptions} [options] Defaults options.\n * @return {Collection}\n * A collection of interactions to be used with the {@link module:ol/Map~Map}\n * constructor's `interactions` option.\n * @api\n */\nexport function defaults(options) {\n options = options ? options : {};\n\n /** @type {Collection} */\n const interactions = new Collection();\n\n const kinetic = new Kinetic(-0.005, 0.05, 100);\n\n const altShiftDragRotate =\n options.altShiftDragRotate !== undefined\n ? options.altShiftDragRotate\n : true;\n if (altShiftDragRotate) {\n interactions.push(new DragRotate());\n }\n\n const doubleClickZoom =\n options.doubleClickZoom !== undefined ? options.doubleClickZoom : true;\n if (doubleClickZoom) {\n interactions.push(\n new DoubleClickZoom({\n delta: options.zoomDelta,\n duration: options.zoomDuration,\n })\n );\n }\n\n const dragPan = options.dragPan !== undefined ? options.dragPan : true;\n if (dragPan) {\n interactions.push(\n new DragPan({\n onFocusOnly: options.onFocusOnly,\n kinetic: kinetic,\n })\n );\n }\n\n const pinchRotate =\n options.pinchRotate !== undefined ? options.pinchRotate : true;\n if (pinchRotate) {\n interactions.push(new PinchRotate());\n }\n\n const pinchZoom = options.pinchZoom !== undefined ? options.pinchZoom : true;\n if (pinchZoom) {\n interactions.push(\n new PinchZoom({\n duration: options.zoomDuration,\n })\n );\n }\n\n const keyboard = options.keyboard !== undefined ? options.keyboard : true;\n if (keyboard) {\n interactions.push(new KeyboardPan());\n interactions.push(\n new KeyboardZoom({\n delta: options.zoomDelta,\n duration: options.zoomDuration,\n })\n );\n }\n\n const mouseWheelZoom =\n options.mouseWheelZoom !== undefined ? options.mouseWheelZoom : true;\n if (mouseWheelZoom) {\n interactions.push(\n new MouseWheelZoom({\n onFocusOnly: options.onFocusOnly,\n duration: options.zoomDuration,\n })\n );\n }\n\n const shiftDragZoom =\n options.shiftDragZoom !== undefined ? options.shiftDragZoom : true;\n if (shiftDragZoom) {\n interactions.push(\n new DragZoom({\n duration: options.zoomDuration,\n })\n );\n }\n\n return interactions;\n}\n","/**\n * @module ol/size\n */\n\n/**\n * An array of numbers representing a size: `[width, height]`.\n * @typedef {Array} Size\n * @api\n */\n\n/**\n * Returns a buffered size.\n * @param {Size} size Size.\n * @param {number} num The amount by which to buffer.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} The buffered size.\n */\nexport function buffer(size, num, dest) {\n if (dest === undefined) {\n dest = [0, 0];\n }\n dest[0] = size[0] + 2 * num;\n dest[1] = size[1] + 2 * num;\n return dest;\n}\n\n/**\n * Determines if a size has a positive area.\n * @param {Size} size The size to test.\n * @return {boolean} The size has a positive area.\n */\nexport function hasArea(size) {\n return size[0] > 0 && size[1] > 0;\n}\n\n/**\n * Returns a size scaled by a ratio. The result will be an array of integers.\n * @param {Size} size Size.\n * @param {number} ratio Ratio.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} The scaled size.\n */\nexport function scale(size, ratio, dest) {\n if (dest === undefined) {\n dest = [0, 0];\n }\n dest[0] = (size[0] * ratio + 0.5) | 0;\n dest[1] = (size[1] * ratio + 0.5) | 0;\n return dest;\n}\n\n/**\n * Returns an `Size` array for the passed in number (meaning: square) or\n * `Size` array.\n * (meaning: non-square),\n * @param {number|Size} size Width and height.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} Size.\n * @api\n */\nexport function toSize(size, dest) {\n if (Array.isArray(size)) {\n return size;\n }\n if (dest === undefined) {\n dest = [size, size];\n } else {\n dest[0] = size;\n dest[1] = size;\n }\n return dest;\n}\n","/**\n * @module ol/Map\n */\nimport BaseObject from './Object.js';\nimport Collection from './Collection.js';\nimport CollectionEventType from './CollectionEventType.js';\nimport CompositeMapRenderer from './renderer/Composite.js';\nimport EventType from './events/EventType.js';\nimport Layer from './layer/Layer.js';\nimport LayerGroup, {GroupEvent} from './layer/Group.js';\nimport MapBrowserEvent from './MapBrowserEvent.js';\nimport MapBrowserEventHandler from './MapBrowserEventHandler.js';\nimport MapBrowserEventType from './MapBrowserEventType.js';\nimport MapEvent from './MapEvent.js';\nimport MapEventType from './MapEventType.js';\nimport MapProperty from './MapProperty.js';\nimport ObjectEventType from './ObjectEventType.js';\nimport PointerEventType from './pointer/EventType.js';\nimport RenderEventType from './render/EventType.js';\nimport TileQueue, {getTilePriority} from './TileQueue.js';\nimport View from './View.js';\nimport ViewHint from './ViewHint.js';\nimport {DEVICE_PIXEL_RATIO, PASSIVE_EVENT_LISTENERS} from './has.js';\nimport {TRUE} from './functions.js';\nimport {\n apply as applyTransform,\n create as createTransform,\n} from './transform.js';\nimport {assert} from './asserts.js';\nimport {\n clone,\n createOrUpdateEmpty,\n equals as equalsExtent,\n getForViewAndSize,\n isEmpty,\n} from './extent.js';\nimport {defaults as defaultControls} from './control/defaults.js';\nimport {defaults as defaultInteractions} from './interaction/defaults.js';\nimport {equals} from './array.js';\nimport {fromUserCoordinate, toUserCoordinate} from './proj.js';\nimport {getUid} from './util.js';\nimport {hasArea} from './size.js';\nimport {listen, unlistenByKey} from './events.js';\nimport {removeNode} from './dom.js';\nimport {warn} from './console.js';\n\n/**\n * State of the current frame. Only `pixelRatio`, `time` and `viewState` should\n * be used in applications.\n * @typedef {Object} FrameState\n * @property {number} pixelRatio The pixel ratio of the frame.\n * @property {number} time The time when rendering of the frame was requested.\n * @property {import(\"./View.js\").State} viewState The state of the current view.\n * @property {boolean} animate Animate.\n * @property {import(\"./transform.js\").Transform} coordinateToPixelTransform CoordinateToPixelTransform.\n * @property {import(\"rbush\").default} declutterTree DeclutterTree.\n * @property {null|import(\"./extent.js\").Extent} extent Extent (in view projection coordinates).\n * @property {import(\"./extent.js\").Extent} [nextExtent] Next extent during an animation series.\n * @property {number} index Index.\n * @property {Array} layerStatesArray LayerStatesArray.\n * @property {number} layerIndex LayerIndex.\n * @property {import(\"./transform.js\").Transform} pixelToCoordinateTransform PixelToCoordinateTransform.\n * @property {Array} postRenderFunctions PostRenderFunctions.\n * @property {import(\"./size.js\").Size} size Size.\n * @property {TileQueue} tileQueue TileQueue.\n * @property {!Object>} usedTiles UsedTiles.\n * @property {Array} viewHints ViewHints.\n * @property {!Object>} wantedTiles WantedTiles.\n * @property {string} mapId The id of the map.\n * @property {Object} renderTargets Identifiers of previously rendered elements.\n */\n\n/**\n * @typedef {function(Map, ?FrameState): any} PostRenderFunction\n */\n\n/**\n * @typedef {Object} AtPixelOptions\n * @property {undefined|function(import(\"./layer/Layer.js\").default): boolean} [layerFilter] Layer filter\n * function. The filter function will receive one argument, the\n * {@link module:ol/layer/Layer~Layer layer-candidate} and it should return a boolean value.\n * Only layers which are visible and for which this function returns `true`\n * will be tested for features. By default, all visible layers will be tested.\n * @property {number} [hitTolerance=0] Hit-detection tolerance in css pixels. Pixels\n * inside the radius around the given position will be checked for features.\n * @property {boolean} [checkWrapped=true] Check-Wrapped Will check for wrapped geometries inside the range of\n * +/- 1 world width. Works only if a projection is used that can be wrapped.\n */\n\n/**\n * @typedef {Object} MapOptionsInternal\n * @property {Collection} [controls] Controls.\n * @property {Collection} [interactions] Interactions.\n * @property {HTMLElement|Document} keyboardEventTarget KeyboardEventTarget.\n * @property {Collection} overlays Overlays.\n * @property {Object} values Values.\n */\n\n/**\n * @typedef {import(\"./ObjectEventType\").Types|'change:layergroup'|'change:size'|'change:target'|'change:view'} MapObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} MapEventHandler\n */\n\n/**\n * Object literal with config options for the map.\n * @typedef {Object} MapOptions\n * @property {Collection|Array} [controls]\n * Controls initially added to the map. If not specified,\n * {@link module:ol/control/defaults.defaults} is used.\n * @property {number} [pixelRatio=window.devicePixelRatio] The ratio between\n * physical pixels and device-independent pixels (dips) on the device.\n * @property {Collection|Array} [interactions]\n * Interactions that are initially added to the map. If not specified,\n * {@link module:ol/interaction/defaults.defaults} is used.\n * @property {HTMLElement|Document|string} [keyboardEventTarget] The element to\n * listen to keyboard events on. This determines when the `KeyboardPan` and\n * `KeyboardZoom` interactions trigger. For example, if this option is set to\n * `document` the keyboard interactions will always trigger. If this option is\n * not specified, the element the library listens to keyboard events on is the\n * map target (i.e. the user-provided div for the map). If this is not\n * `document`, the target element needs to be focused for key events to be\n * emitted, requiring that the target element has a `tabindex` attribute.\n * @property {Array|Collection|LayerGroup} [layers]\n * Layers. If this is not defined, a map with no layers will be rendered. Note\n * that layers are rendered in the order supplied, so if you want, for example,\n * a vector layer to appear on top of a tile layer, it must come after the tile\n * layer.\n * @property {number} [maxTilesLoading=16] Maximum number tiles to load\n * simultaneously.\n * @property {number} [moveTolerance=1] The minimum distance in pixels the\n * cursor must move to be detected as a map move event instead of a click.\n * Increasing this value can make it easier to click on the map.\n * @property {Collection|Array} [overlays]\n * Overlays initially added to the map. By default, no overlays are added.\n * @property {HTMLElement|string} [target] The container for the map, either the\n * element itself or the `id` of the element. If not specified at construction\n * time, {@link module:ol/Map~Map#setTarget} must be called for the map to be\n * rendered. If passed by element, the container can be in a secondary document.\n * **Note:** CSS `transform` support for the target element is limited to `scale`.\n * @property {View|Promise} [view] The map's view. No layer sources will be\n * fetched unless this is specified at construction time or through\n * {@link module:ol/Map~Map#setView}.\n */\n\n/**\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n */\nfunction removeLayerMapProperty(layer) {\n if (layer instanceof Layer) {\n layer.setMapInternal(null);\n return;\n }\n if (layer instanceof LayerGroup) {\n layer.getLayers().forEach(removeLayerMapProperty);\n }\n}\n\n/**\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n * @param {Map} map Map.\n */\nfunction setLayerMapProperty(layer, map) {\n if (layer instanceof Layer) {\n layer.setMapInternal(map);\n return;\n }\n if (layer instanceof LayerGroup) {\n const layers = layer.getLayers().getArray();\n for (let i = 0, ii = layers.length; i < ii; ++i) {\n setLayerMapProperty(layers[i], map);\n }\n }\n}\n\n/**\n * @classdesc\n * The map is the core component of OpenLayers. For a map to render, a view,\n * one or more layers, and a target container are needed:\n *\n * import Map from 'ol/Map.js';\n * import View from 'ol/View.js';\n * import TileLayer from 'ol/layer/Tile.js';\n * import OSM from 'ol/source/OSM.js';\n *\n * const map = new Map({\n * view: new View({\n * center: [0, 0],\n * zoom: 1,\n * }),\n * layers: [\n * new TileLayer({\n * source: new OSM(),\n * }),\n * ],\n * target: 'map',\n * });\n *\n * The above snippet creates a map using a {@link module:ol/layer/Tile~TileLayer} to\n * display {@link module:ol/source/OSM~OSM} OSM data and render it to a DOM\n * element with the id `map`.\n *\n * The constructor places a viewport container (with CSS class name\n * `ol-viewport`) in the target element (see `getViewport()`), and then two\n * further elements within the viewport: one with CSS class name\n * `ol-overlaycontainer-stopevent` for controls and some overlays, and one with\n * CSS class name `ol-overlaycontainer` for other overlays (see the `stopEvent`\n * option of {@link module:ol/Overlay~Overlay} for the difference). The map\n * itself is placed in a further element within the viewport.\n *\n * Layers are stored as a {@link module:ol/Collection~Collection} in\n * layerGroups. A top-level group is provided by the library. This is what is\n * accessed by `getLayerGroup` and `setLayerGroup`. Layers entered in the\n * options are added to this group, and `addLayer` and `removeLayer` change the\n * layer collection in the group. `getLayers` is a convenience function for\n * `getLayerGroup().getLayers()`. Note that {@link module:ol/layer/Group~LayerGroup}\n * is a subclass of {@link module:ol/layer/Base~BaseLayer}, so layers entered in the\n * options or added with `addLayer` can be groups, which can contain further\n * groups, and so on.\n *\n * @fires import(\"./MapBrowserEvent.js\").MapBrowserEvent\n * @fires import(\"./MapEvent.js\").MapEvent\n * @fires import(\"./render/Event.js\").default#precompose\n * @fires import(\"./render/Event.js\").default#postcompose\n * @fires import(\"./render/Event.js\").default#rendercomplete\n * @api\n */\nclass Map extends BaseObject {\n /**\n * @param {MapOptions} [options] Map options.\n */\n constructor(options) {\n super();\n\n options = options || {};\n\n /***\n * @type {MapEventHandler}\n */\n this.on;\n\n /***\n * @type {MapEventHandler}\n */\n this.once;\n\n /***\n * @type {MapEventHandler}\n */\n this.un;\n\n const optionsInternal = createOptionsInternal(options);\n\n /**\n * @private\n * @type {boolean|undefined}\n */\n this.renderComplete_;\n\n /**\n * @private\n * @type {boolean}\n */\n this.loaded_ = true;\n\n /** @private */\n this.boundHandleBrowserEvent_ = this.handleBrowserEvent.bind(this);\n\n /**\n * @type {number}\n * @private\n */\n this.maxTilesLoading_ =\n options.maxTilesLoading !== undefined ? options.maxTilesLoading : 16;\n\n /**\n * @private\n * @type {number}\n */\n this.pixelRatio_ =\n options.pixelRatio !== undefined\n ? options.pixelRatio\n : DEVICE_PIXEL_RATIO;\n\n /**\n * @private\n * @type {ReturnType}\n */\n this.postRenderTimeoutHandle_;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.animationDelayKey_;\n\n /**\n * @private\n */\n this.animationDelay_ = this.animationDelay_.bind(this);\n\n /**\n * @private\n * @type {import(\"./transform.js\").Transform}\n */\n this.coordinateToPixelTransform_ = createTransform();\n\n /**\n * @private\n * @type {import(\"./transform.js\").Transform}\n */\n this.pixelToCoordinateTransform_ = createTransform();\n\n /**\n * @private\n * @type {number}\n */\n this.frameIndex_ = 0;\n\n /**\n * @private\n * @type {?FrameState}\n */\n this.frameState_ = null;\n\n /**\n * The extent at the previous 'moveend' event.\n * @private\n * @type {import(\"./extent.js\").Extent}\n */\n this.previousExtent_ = null;\n\n /**\n * @private\n * @type {?import(\"./events.js\").EventsKey}\n */\n this.viewPropertyListenerKey_ = null;\n\n /**\n * @private\n * @type {?import(\"./events.js\").EventsKey}\n */\n this.viewChangeListenerKey_ = null;\n\n /**\n * @private\n * @type {?Array}\n */\n this.layerGroupPropertyListenerKeys_ = null;\n\n /**\n * @private\n * @type {!HTMLElement}\n */\n this.viewport_ = document.createElement('div');\n this.viewport_.className =\n 'ol-viewport' + ('ontouchstart' in window ? ' ol-touch' : '');\n this.viewport_.style.position = 'relative';\n this.viewport_.style.overflow = 'hidden';\n this.viewport_.style.width = '100%';\n this.viewport_.style.height = '100%';\n\n /**\n * @private\n * @type {!HTMLElement}\n */\n this.overlayContainer_ = document.createElement('div');\n this.overlayContainer_.style.position = 'absolute';\n this.overlayContainer_.style.zIndex = '0';\n this.overlayContainer_.style.width = '100%';\n this.overlayContainer_.style.height = '100%';\n this.overlayContainer_.style.pointerEvents = 'none';\n this.overlayContainer_.className = 'ol-overlaycontainer';\n this.viewport_.appendChild(this.overlayContainer_);\n\n /**\n * @private\n * @type {!HTMLElement}\n */\n this.overlayContainerStopEvent_ = document.createElement('div');\n this.overlayContainerStopEvent_.style.position = 'absolute';\n this.overlayContainerStopEvent_.style.zIndex = '0';\n this.overlayContainerStopEvent_.style.width = '100%';\n this.overlayContainerStopEvent_.style.height = '100%';\n this.overlayContainerStopEvent_.style.pointerEvents = 'none';\n this.overlayContainerStopEvent_.className = 'ol-overlaycontainer-stopevent';\n this.viewport_.appendChild(this.overlayContainerStopEvent_);\n\n /**\n * @private\n * @type {MapBrowserEventHandler}\n */\n this.mapBrowserEventHandler_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.moveTolerance_ = options.moveTolerance;\n\n /**\n * @private\n * @type {HTMLElement|Document}\n */\n this.keyboardEventTarget_ = optionsInternal.keyboardEventTarget;\n\n /**\n * @private\n * @type {?Array}\n */\n this.targetChangeHandlerKeys_ = null;\n\n /**\n * @private\n * @type {HTMLElement|null}\n */\n this.targetElement_ = null;\n\n /**\n * @type {ResizeObserver}\n */\n this.resizeObserver_ = new ResizeObserver(() => this.updateSize());\n\n /**\n * @type {Collection}\n * @protected\n */\n this.controls = optionsInternal.controls || defaultControls();\n\n /**\n * @type {Collection}\n * @protected\n */\n this.interactions =\n optionsInternal.interactions ||\n defaultInteractions({\n onFocusOnly: true,\n });\n\n /**\n * @type {Collection}\n * @private\n */\n this.overlays_ = optionsInternal.overlays;\n\n /**\n * A lookup of overlays by id.\n * @private\n * @type {Object}\n */\n this.overlayIdIndex_ = {};\n\n /**\n * @type {import(\"./renderer/Map.js\").default|null}\n * @private\n */\n this.renderer_ = null;\n\n /**\n * @private\n * @type {!Array}\n */\n this.postRenderFunctions_ = [];\n\n /**\n * @private\n * @type {TileQueue}\n */\n this.tileQueue_ = new TileQueue(\n this.getTilePriority.bind(this),\n this.handleTileChange_.bind(this)\n );\n\n this.addChangeListener(\n MapProperty.LAYERGROUP,\n this.handleLayerGroupChanged_\n );\n this.addChangeListener(MapProperty.VIEW, this.handleViewChanged_);\n this.addChangeListener(MapProperty.SIZE, this.handleSizeChanged_);\n this.addChangeListener(MapProperty.TARGET, this.handleTargetChanged_);\n\n // setProperties will trigger the rendering of the map if the map\n // is \"defined\" already.\n this.setProperties(optionsInternal.values);\n\n const map = this;\n if (options.view && !(options.view instanceof View)) {\n options.view.then(function (viewOptions) {\n map.setView(new View(viewOptions));\n });\n }\n\n this.controls.addEventListener(\n CollectionEventType.ADD,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent\n */\n (event) => {\n event.element.setMap(this);\n }\n );\n\n this.controls.addEventListener(\n CollectionEventType.REMOVE,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n event.element.setMap(null);\n }\n );\n\n this.interactions.addEventListener(\n CollectionEventType.ADD,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n event.element.setMap(this);\n }\n );\n\n this.interactions.addEventListener(\n CollectionEventType.REMOVE,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n event.element.setMap(null);\n }\n );\n\n this.overlays_.addEventListener(\n CollectionEventType.ADD,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n this.addOverlayInternal_(event.element);\n }\n );\n\n this.overlays_.addEventListener(\n CollectionEventType.REMOVE,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n const id = event.element.getId();\n if (id !== undefined) {\n delete this.overlayIdIndex_[id.toString()];\n }\n event.element.setMap(null);\n }\n );\n\n this.controls.forEach(\n /**\n * @param {import(\"./control/Control.js\").default} control Control.\n */\n (control) => {\n control.setMap(this);\n }\n );\n\n this.interactions.forEach(\n /**\n * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction.\n */\n (interaction) => {\n interaction.setMap(this);\n }\n );\n\n this.overlays_.forEach(this.addOverlayInternal_.bind(this));\n }\n\n /**\n * Add the given control to the map.\n * @param {import(\"./control/Control.js\").default} control Control.\n * @api\n */\n addControl(control) {\n this.getControls().push(control);\n }\n\n /**\n * Add the given interaction to the map. If you want to add an interaction\n * at another point of the collection use `getInteractions()` and the methods\n * available on {@link module:ol/Collection~Collection}. This can be used to\n * stop the event propagation from the handleEvent function. The interactions\n * get to handle the events in the reverse order of this collection.\n * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction to add.\n * @api\n */\n addInteraction(interaction) {\n this.getInteractions().push(interaction);\n }\n\n /**\n * Adds the given layer to the top of this map. If you want to add a layer\n * elsewhere in the stack, use `getLayers()` and the methods available on\n * {@link module:ol/Collection~Collection}.\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n * @api\n */\n addLayer(layer) {\n const layers = this.getLayerGroup().getLayers();\n layers.push(layer);\n }\n\n /**\n * @param {import(\"./layer/Group.js\").GroupEvent} event The layer add event.\n * @private\n */\n handleLayerAdd_(event) {\n setLayerMapProperty(event.layer, this);\n }\n\n /**\n * Add the given overlay to the map.\n * @param {import(\"./Overlay.js\").default} overlay Overlay.\n * @api\n */\n addOverlay(overlay) {\n this.getOverlays().push(overlay);\n }\n\n /**\n * This deals with map's overlay collection changes.\n * @param {import(\"./Overlay.js\").default} overlay Overlay.\n * @private\n */\n addOverlayInternal_(overlay) {\n const id = overlay.getId();\n if (id !== undefined) {\n this.overlayIdIndex_[id.toString()] = overlay;\n }\n overlay.setMap(this);\n }\n\n /**\n *\n * Clean up.\n */\n disposeInternal() {\n this.controls.clear();\n this.interactions.clear();\n this.overlays_.clear();\n this.resizeObserver_.disconnect();\n this.setTarget(null);\n super.disposeInternal();\n }\n\n /**\n * Detect features that intersect a pixel on the viewport, and execute a\n * callback with each intersecting feature. Layers included in the detection can\n * be configured through the `layerFilter` option in `options`.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n * @param {function(import(\"./Feature.js\").FeatureLike, import(\"./layer/Layer.js\").default, import(\"./geom/SimpleGeometry.js\").default): T} callback Feature callback. The callback will be\n * called with two arguments. The first argument is one\n * {@link module:ol/Feature~Feature feature} or\n * {@link module:ol/render/Feature~RenderFeature render feature} at the pixel, the second is\n * the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for\n * unmanaged layers. To stop detection, callback functions can return a\n * truthy value.\n * @param {AtPixelOptions} [options] Optional options.\n * @return {T|undefined} Callback result, i.e. the return value of last\n * callback execution, or the first truthy callback return value.\n * @template T\n * @api\n */\n forEachFeatureAtPixel(pixel, callback, options) {\n if (!this.frameState_ || !this.renderer_) {\n return;\n }\n const coordinate = this.getCoordinateFromPixelInternal(pixel);\n options = options !== undefined ? options : {};\n const hitTolerance =\n options.hitTolerance !== undefined ? options.hitTolerance : 0;\n const layerFilter =\n options.layerFilter !== undefined ? options.layerFilter : TRUE;\n const checkWrapped = options.checkWrapped !== false;\n return this.renderer_.forEachFeatureAtCoordinate(\n coordinate,\n this.frameState_,\n hitTolerance,\n checkWrapped,\n callback,\n null,\n layerFilter,\n null\n );\n }\n\n /**\n * Get all features that intersect a pixel on the viewport.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n * @param {AtPixelOptions} [options] Optional options.\n * @return {Array} The detected features or\n * an empty array if none were found.\n * @api\n */\n getFeaturesAtPixel(pixel, options) {\n const features = [];\n this.forEachFeatureAtPixel(\n pixel,\n function (feature) {\n features.push(feature);\n },\n options\n );\n return features;\n }\n\n /**\n * Get all layers from all layer groups.\n * @return {Array} Layers.\n * @api\n */\n getAllLayers() {\n const layers = [];\n function addLayersFrom(layerGroup) {\n layerGroup.forEach(function (layer) {\n if (layer instanceof LayerGroup) {\n addLayersFrom(layer.getLayers());\n } else {\n layers.push(layer);\n }\n });\n }\n addLayersFrom(this.getLayers());\n return layers;\n }\n\n /**\n * Detect if features intersect a pixel on the viewport. Layers included in the\n * detection can be configured through the `layerFilter` option.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n * @param {AtPixelOptions} [options] Optional options.\n * @return {boolean} Is there a feature at the given pixel?\n * @api\n */\n hasFeatureAtPixel(pixel, options) {\n if (!this.frameState_ || !this.renderer_) {\n return false;\n }\n const coordinate = this.getCoordinateFromPixelInternal(pixel);\n options = options !== undefined ? options : {};\n const layerFilter =\n options.layerFilter !== undefined ? options.layerFilter : TRUE;\n const hitTolerance =\n options.hitTolerance !== undefined ? options.hitTolerance : 0;\n const checkWrapped = options.checkWrapped !== false;\n return this.renderer_.hasFeatureAtCoordinate(\n coordinate,\n this.frameState_,\n hitTolerance,\n checkWrapped,\n layerFilter,\n null\n );\n }\n\n /**\n * Returns the coordinate in user projection for a browser event.\n * @param {MouseEvent} event Event.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n * @api\n */\n getEventCoordinate(event) {\n return this.getCoordinateFromPixel(this.getEventPixel(event));\n }\n\n /**\n * Returns the coordinate in view projection for a browser event.\n * @param {MouseEvent} event Event.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n */\n getEventCoordinateInternal(event) {\n return this.getCoordinateFromPixelInternal(this.getEventPixel(event));\n }\n\n /**\n * Returns the map pixel position for a browser event relative to the viewport.\n * @param {UIEvent|{clientX: number, clientY: number}} event Event.\n * @return {import(\"./pixel.js\").Pixel} Pixel.\n * @api\n */\n getEventPixel(event) {\n const viewport = this.viewport_;\n const viewportPosition = viewport.getBoundingClientRect();\n const viewportSize = this.getSize();\n const scaleX = viewportPosition.width / viewportSize[0];\n const scaleY = viewportPosition.height / viewportSize[1];\n const eventPosition =\n //FIXME Are we really calling this with a TouchEvent anywhere?\n 'changedTouches' in event\n ? /** @type {TouchEvent} */ (event).changedTouches[0]\n : /** @type {MouseEvent} */ (event);\n\n return [\n (eventPosition.clientX - viewportPosition.left) / scaleX,\n (eventPosition.clientY - viewportPosition.top) / scaleY,\n ];\n }\n\n /**\n * Get the target in which this map is rendered.\n * Note that this returns what is entered as an option or in setTarget:\n * if that was an element, it returns an element; if a string, it returns that.\n * @return {HTMLElement|string|undefined} The Element or id of the Element that the\n * map is rendered in.\n * @observable\n * @api\n */\n getTarget() {\n return /** @type {HTMLElement|string|undefined} */ (\n this.get(MapProperty.TARGET)\n );\n }\n\n /**\n * Get the DOM element into which this map is rendered. In contrast to\n * `getTarget` this method always return an `Element`, or `null` if the\n * map has no target.\n * @return {HTMLElement} The element that the map is rendered in.\n * @api\n */\n getTargetElement() {\n return this.targetElement_;\n }\n\n /**\n * Get the coordinate for a given pixel. This returns a coordinate in the\n * user projection.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel position in the map viewport.\n * @return {import(\"./coordinate.js\").Coordinate} The coordinate for the pixel position.\n * @api\n */\n getCoordinateFromPixel(pixel) {\n return toUserCoordinate(\n this.getCoordinateFromPixelInternal(pixel),\n this.getView().getProjection()\n );\n }\n\n /**\n * Get the coordinate for a given pixel. This returns a coordinate in the\n * map view projection.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel position in the map viewport.\n * @return {import(\"./coordinate.js\").Coordinate} The coordinate for the pixel position.\n */\n getCoordinateFromPixelInternal(pixel) {\n const frameState = this.frameState_;\n if (!frameState) {\n return null;\n }\n return applyTransform(frameState.pixelToCoordinateTransform, pixel.slice());\n }\n\n /**\n * Get the map controls. Modifying this collection changes the controls\n * associated with the map.\n * @return {Collection} Controls.\n * @api\n */\n getControls() {\n return this.controls;\n }\n\n /**\n * Get the map overlays. Modifying this collection changes the overlays\n * associated with the map.\n * @return {Collection} Overlays.\n * @api\n */\n getOverlays() {\n return this.overlays_;\n }\n\n /**\n * Get an overlay by its identifier (the value returned by overlay.getId()).\n * Note that the index treats string and numeric identifiers as the same. So\n * `map.getOverlayById(2)` will return an overlay with id `'2'` or `2`.\n * @param {string|number} id Overlay identifier.\n * @return {import(\"./Overlay.js\").default} Overlay.\n * @api\n */\n getOverlayById(id) {\n const overlay = this.overlayIdIndex_[id.toString()];\n return overlay !== undefined ? overlay : null;\n }\n\n /**\n * Get the map interactions. Modifying this collection changes the interactions\n * associated with the map.\n *\n * Interactions are used for e.g. pan, zoom and rotate.\n * @return {Collection} Interactions.\n * @api\n */\n getInteractions() {\n return this.interactions;\n }\n\n /**\n * Get the layergroup associated with this map.\n * @return {LayerGroup} A layer group containing the layers in this map.\n * @observable\n * @api\n */\n getLayerGroup() {\n return /** @type {LayerGroup} */ (this.get(MapProperty.LAYERGROUP));\n }\n\n /**\n * Clear any existing layers and add layers to the map.\n * @param {Array|Collection} layers The layers to be added to the map.\n * @api\n */\n setLayers(layers) {\n const group = this.getLayerGroup();\n if (layers instanceof Collection) {\n group.setLayers(layers);\n return;\n }\n\n const collection = group.getLayers();\n collection.clear();\n collection.extend(layers);\n }\n\n /**\n * Get the collection of layers associated with this map.\n * @return {!Collection} Layers.\n * @api\n */\n getLayers() {\n const layers = this.getLayerGroup().getLayers();\n return layers;\n }\n\n /**\n * @return {boolean} Layers have sources that are still loading.\n */\n getLoadingOrNotReady() {\n const layerStatesArray = this.getLayerGroup().getLayerStatesArray();\n for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {\n const state = layerStatesArray[i];\n if (!state.visible) {\n continue;\n }\n const renderer = state.layer.getRenderer();\n if (renderer && !renderer.ready) {\n return true;\n }\n const source = state.layer.getSource();\n if (source && source.loading) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the pixel for a coordinate. This takes a coordinate in the user\n * projection and returns the corresponding pixel.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate A map coordinate.\n * @return {import(\"./pixel.js\").Pixel} A pixel position in the map viewport.\n * @api\n */\n getPixelFromCoordinate(coordinate) {\n const viewCoordinate = fromUserCoordinate(\n coordinate,\n this.getView().getProjection()\n );\n return this.getPixelFromCoordinateInternal(viewCoordinate);\n }\n\n /**\n * Get the pixel for a coordinate. This takes a coordinate in the map view\n * projection and returns the corresponding pixel.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate A map coordinate.\n * @return {import(\"./pixel.js\").Pixel} A pixel position in the map viewport.\n */\n getPixelFromCoordinateInternal(coordinate) {\n const frameState = this.frameState_;\n if (!frameState) {\n return null;\n }\n return applyTransform(\n frameState.coordinateToPixelTransform,\n coordinate.slice(0, 2)\n );\n }\n\n /**\n * Get the map renderer.\n * @return {import(\"./renderer/Map.js\").default|null} Renderer\n */\n getRenderer() {\n return this.renderer_;\n }\n\n /**\n * Get the size of this map.\n * @return {import(\"./size.js\").Size|undefined} The size in pixels of the map in the DOM.\n * @observable\n * @api\n */\n getSize() {\n return /** @type {import(\"./size.js\").Size|undefined} */ (\n this.get(MapProperty.SIZE)\n );\n }\n\n /**\n * Get the view associated with this map. A view manages properties such as\n * center and resolution.\n * @return {View} The view that controls this map.\n * @observable\n * @api\n */\n getView() {\n return /** @type {View} */ (this.get(MapProperty.VIEW));\n }\n\n /**\n * Get the element that serves as the map viewport.\n * @return {HTMLElement} Viewport.\n * @api\n */\n getViewport() {\n return this.viewport_;\n }\n\n /**\n * Get the element that serves as the container for overlays. Elements added to\n * this container will let mousedown and touchstart events through to the map,\n * so clicks and gestures on an overlay will trigger {@link module:ol/MapBrowserEvent~MapBrowserEvent}\n * events.\n * @return {!HTMLElement} The map's overlay container.\n */\n getOverlayContainer() {\n return this.overlayContainer_;\n }\n\n /**\n * Get the element that serves as a container for overlays that don't allow\n * event propagation. Elements added to this container won't let mousedown and\n * touchstart events through to the map, so clicks and gestures on an overlay\n * don't trigger any {@link module:ol/MapBrowserEvent~MapBrowserEvent}.\n * @return {!HTMLElement} The map's overlay container that stops events.\n */\n getOverlayContainerStopEvent() {\n return this.overlayContainerStopEvent_;\n }\n\n /**\n * @return {!Document} The document where the map is displayed.\n */\n getOwnerDocument() {\n const targetElement = this.getTargetElement();\n return targetElement ? targetElement.ownerDocument : document;\n }\n\n /**\n * @param {import(\"./Tile.js\").default} tile Tile.\n * @param {string} tileSourceKey Tile source key.\n * @param {import(\"./coordinate.js\").Coordinate} tileCenter Tile center.\n * @param {number} tileResolution Tile resolution.\n * @return {number} Tile priority.\n */\n getTilePriority(tile, tileSourceKey, tileCenter, tileResolution) {\n return getTilePriority(\n this.frameState_,\n tile,\n tileSourceKey,\n tileCenter,\n tileResolution\n );\n }\n\n /**\n * @param {UIEvent} browserEvent Browser event.\n * @param {string} [type] Type.\n */\n handleBrowserEvent(browserEvent, type) {\n type = type || browserEvent.type;\n const mapBrowserEvent = new MapBrowserEvent(type, this, browserEvent);\n this.handleMapBrowserEvent(mapBrowserEvent);\n }\n\n /**\n * @param {MapBrowserEvent} mapBrowserEvent The event to handle.\n */\n handleMapBrowserEvent(mapBrowserEvent) {\n if (!this.frameState_) {\n // With no view defined, we cannot translate pixels into geographical\n // coordinates so interactions cannot be used.\n return;\n }\n const originalEvent = /** @type {PointerEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const eventType = originalEvent.type;\n if (\n eventType === PointerEventType.POINTERDOWN ||\n eventType === EventType.WHEEL ||\n eventType === EventType.KEYDOWN\n ) {\n const doc = this.getOwnerDocument();\n const rootNode = this.viewport_.getRootNode\n ? this.viewport_.getRootNode()\n : doc;\n const target = /** @type {Node} */ (originalEvent.target);\n if (\n // Abort if the target is a child of the container for elements whose events are not meant\n // to be handled by map interactions.\n this.overlayContainerStopEvent_.contains(target) ||\n // Abort if the event target is a child of the container that is no longer in the page.\n // It's possible for the target to no longer be in the page if it has been removed in an\n // event listener, this might happen in a Control that recreates it's content based on\n // user interaction either manually or via a render in something like https://reactjs.org/\n !(rootNode === doc ? doc.documentElement : rootNode).contains(target)\n ) {\n return;\n }\n }\n mapBrowserEvent.frameState = this.frameState_;\n if (this.dispatchEvent(mapBrowserEvent) !== false) {\n const interactionsArray = this.getInteractions().getArray().slice();\n for (let i = interactionsArray.length - 1; i >= 0; i--) {\n const interaction = interactionsArray[i];\n if (\n interaction.getMap() !== this ||\n !interaction.getActive() ||\n !this.getTargetElement()\n ) {\n continue;\n }\n const cont = interaction.handleEvent(mapBrowserEvent);\n if (!cont || mapBrowserEvent.propagationStopped) {\n break;\n }\n }\n }\n }\n\n /**\n * @protected\n */\n handlePostRender() {\n const frameState = this.frameState_;\n\n // Manage the tile queue\n // Image loads are expensive and a limited resource, so try to use them\n // efficiently:\n // * When the view is static we allow a large number of parallel tile loads\n // to complete the frame as quickly as possible.\n // * When animating or interacting, image loads can cause janks, so we reduce\n // the maximum number of loads per frame and limit the number of parallel\n // tile loads to remain reactive to view changes and to reduce the chance of\n // loading tiles that will quickly disappear from view.\n const tileQueue = this.tileQueue_;\n if (!tileQueue.isEmpty()) {\n let maxTotalLoading = this.maxTilesLoading_;\n let maxNewLoads = maxTotalLoading;\n if (frameState) {\n const hints = frameState.viewHints;\n if (hints[ViewHint.ANIMATING] || hints[ViewHint.INTERACTING]) {\n const lowOnFrameBudget = Date.now() - frameState.time > 8;\n maxTotalLoading = lowOnFrameBudget ? 0 : 8;\n maxNewLoads = lowOnFrameBudget ? 0 : 2;\n }\n }\n if (tileQueue.getTilesLoading() < maxTotalLoading) {\n tileQueue.reprioritize(); // FIXME only call if view has changed\n tileQueue.loadMoreTiles(maxTotalLoading, maxNewLoads);\n }\n }\n\n if (frameState && this.renderer_ && !frameState.animate) {\n if (this.renderComplete_ === true) {\n if (this.hasListener(RenderEventType.RENDERCOMPLETE)) {\n this.renderer_.dispatchRenderEvent(\n RenderEventType.RENDERCOMPLETE,\n frameState\n );\n }\n if (this.loaded_ === false) {\n this.loaded_ = true;\n this.dispatchEvent(\n new MapEvent(MapEventType.LOADEND, this, frameState)\n );\n }\n } else if (this.loaded_ === true) {\n this.loaded_ = false;\n this.dispatchEvent(\n new MapEvent(MapEventType.LOADSTART, this, frameState)\n );\n }\n }\n\n const postRenderFunctions = this.postRenderFunctions_;\n for (let i = 0, ii = postRenderFunctions.length; i < ii; ++i) {\n postRenderFunctions[i](this, frameState);\n }\n postRenderFunctions.length = 0;\n }\n\n /**\n * @private\n */\n handleSizeChanged_() {\n if (this.getView() && !this.getView().getAnimating()) {\n this.getView().resolveConstraints(0);\n }\n\n this.render();\n }\n\n /**\n * @private\n */\n handleTargetChanged_() {\n if (this.mapBrowserEventHandler_) {\n for (let i = 0, ii = this.targetChangeHandlerKeys_.length; i < ii; ++i) {\n unlistenByKey(this.targetChangeHandlerKeys_[i]);\n }\n this.targetChangeHandlerKeys_ = null;\n this.viewport_.removeEventListener(\n EventType.CONTEXTMENU,\n this.boundHandleBrowserEvent_\n );\n this.viewport_.removeEventListener(\n EventType.WHEEL,\n this.boundHandleBrowserEvent_\n );\n this.mapBrowserEventHandler_.dispose();\n this.mapBrowserEventHandler_ = null;\n removeNode(this.viewport_);\n }\n\n if (this.targetElement_) {\n this.resizeObserver_.unobserve(this.targetElement_);\n const rootNode = this.targetElement_.getRootNode();\n if (rootNode instanceof ShadowRoot) {\n this.resizeObserver_.unobserve(rootNode.host);\n }\n this.setSize(undefined);\n }\n\n // target may be undefined, null, a string or an Element.\n // If it's a string we convert it to an Element before proceeding.\n // If it's not now an Element we remove the viewport from the DOM.\n // If it's an Element we append the viewport element to it.\n\n const target = this.getTarget();\n const targetElement =\n typeof target === 'string' ? document.getElementById(target) : target;\n this.targetElement_ = targetElement;\n if (!targetElement) {\n if (this.renderer_) {\n clearTimeout(this.postRenderTimeoutHandle_);\n this.postRenderTimeoutHandle_ = undefined;\n this.postRenderFunctions_.length = 0;\n this.renderer_.dispose();\n this.renderer_ = null;\n }\n if (this.animationDelayKey_) {\n cancelAnimationFrame(this.animationDelayKey_);\n this.animationDelayKey_ = undefined;\n }\n } else {\n targetElement.appendChild(this.viewport_);\n if (!this.renderer_) {\n this.renderer_ = new CompositeMapRenderer(this);\n }\n\n this.mapBrowserEventHandler_ = new MapBrowserEventHandler(\n this,\n this.moveTolerance_\n );\n for (const key in MapBrowserEventType) {\n this.mapBrowserEventHandler_.addEventListener(\n MapBrowserEventType[key],\n this.handleMapBrowserEvent.bind(this)\n );\n }\n this.viewport_.addEventListener(\n EventType.CONTEXTMENU,\n this.boundHandleBrowserEvent_,\n false\n );\n this.viewport_.addEventListener(\n EventType.WHEEL,\n this.boundHandleBrowserEvent_,\n PASSIVE_EVENT_LISTENERS ? {passive: false} : false\n );\n\n const keyboardEventTarget = !this.keyboardEventTarget_\n ? targetElement\n : this.keyboardEventTarget_;\n this.targetChangeHandlerKeys_ = [\n listen(\n keyboardEventTarget,\n EventType.KEYDOWN,\n this.handleBrowserEvent,\n this\n ),\n listen(\n keyboardEventTarget,\n EventType.KEYPRESS,\n this.handleBrowserEvent,\n this\n ),\n ];\n const rootNode = targetElement.getRootNode();\n if (rootNode instanceof ShadowRoot) {\n this.resizeObserver_.observe(rootNode.host);\n }\n this.resizeObserver_.observe(targetElement);\n }\n\n this.updateSize();\n // updateSize calls setSize, so no need to call this.render\n // ourselves here.\n }\n\n /**\n * @private\n */\n handleTileChange_() {\n this.render();\n }\n\n /**\n * @private\n */\n handleViewPropertyChanged_() {\n this.render();\n }\n\n /**\n * @private\n */\n handleViewChanged_() {\n if (this.viewPropertyListenerKey_) {\n unlistenByKey(this.viewPropertyListenerKey_);\n this.viewPropertyListenerKey_ = null;\n }\n if (this.viewChangeListenerKey_) {\n unlistenByKey(this.viewChangeListenerKey_);\n this.viewChangeListenerKey_ = null;\n }\n const view = this.getView();\n if (view) {\n this.updateViewportSize_();\n\n this.viewPropertyListenerKey_ = listen(\n view,\n ObjectEventType.PROPERTYCHANGE,\n this.handleViewPropertyChanged_,\n this\n );\n this.viewChangeListenerKey_ = listen(\n view,\n EventType.CHANGE,\n this.handleViewPropertyChanged_,\n this\n );\n\n view.resolveConstraints(0);\n }\n this.render();\n }\n\n /**\n * @private\n */\n handleLayerGroupChanged_() {\n if (this.layerGroupPropertyListenerKeys_) {\n this.layerGroupPropertyListenerKeys_.forEach(unlistenByKey);\n this.layerGroupPropertyListenerKeys_ = null;\n }\n const layerGroup = this.getLayerGroup();\n if (layerGroup) {\n this.handleLayerAdd_(new GroupEvent('addlayer', layerGroup));\n this.layerGroupPropertyListenerKeys_ = [\n listen(layerGroup, ObjectEventType.PROPERTYCHANGE, this.render, this),\n listen(layerGroup, EventType.CHANGE, this.render, this),\n listen(layerGroup, 'addlayer', this.handleLayerAdd_, this),\n listen(layerGroup, 'removelayer', this.handleLayerRemove_, this),\n ];\n }\n this.render();\n }\n\n /**\n * @return {boolean} Is rendered.\n */\n isRendered() {\n return !!this.frameState_;\n }\n\n /**\n * @private\n */\n animationDelay_() {\n this.animationDelayKey_ = undefined;\n this.renderFrame_(Date.now());\n }\n\n /**\n * Requests an immediate render in a synchronous manner.\n * @api\n */\n renderSync() {\n if (this.animationDelayKey_) {\n cancelAnimationFrame(this.animationDelayKey_);\n }\n this.animationDelay_();\n }\n\n /**\n * Redraws all text after new fonts have loaded\n */\n redrawText() {\n const layerStates = this.getLayerGroup().getLayerStatesArray();\n for (let i = 0, ii = layerStates.length; i < ii; ++i) {\n const layer = layerStates[i].layer;\n if (layer.hasRenderer()) {\n layer.getRenderer().handleFontsChanged();\n }\n }\n }\n\n /**\n * Request a map rendering (at the next animation frame).\n * @api\n */\n render() {\n if (this.renderer_ && this.animationDelayKey_ === undefined) {\n this.animationDelayKey_ = requestAnimationFrame(this.animationDelay_);\n }\n }\n\n /**\n * This method is meant to be called in a layer's `prerender` listener. It causes all collected\n * declutter items to be decluttered and rendered on the map immediately. This is useful for\n * layers that need to appear entirely above the decluttered items of layers lower in the layer\n * stack.\n * @api\n */\n flushDeclutterItems() {\n const frameState = this.frameState_;\n if (!frameState) {\n return;\n }\n this.renderer_.flushDeclutterItems(frameState);\n }\n\n /**\n * Remove the given control from the map.\n * @param {import(\"./control/Control.js\").default} control Control.\n * @return {import(\"./control/Control.js\").default|undefined} The removed control (or undefined\n * if the control was not found).\n * @api\n */\n removeControl(control) {\n return this.getControls().remove(control);\n }\n\n /**\n * Remove the given interaction from the map.\n * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction to remove.\n * @return {import(\"./interaction/Interaction.js\").default|undefined} The removed interaction (or\n * undefined if the interaction was not found).\n * @api\n */\n removeInteraction(interaction) {\n return this.getInteractions().remove(interaction);\n }\n\n /**\n * Removes the given layer from the map.\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n * @return {import(\"./layer/Base.js\").default|undefined} The removed layer (or undefined if the\n * layer was not found).\n * @api\n */\n removeLayer(layer) {\n const layers = this.getLayerGroup().getLayers();\n return layers.remove(layer);\n }\n\n /**\n * @param {import(\"./layer/Group.js\").GroupEvent} event The layer remove event.\n * @private\n */\n handleLayerRemove_(event) {\n removeLayerMapProperty(event.layer);\n }\n\n /**\n * Remove the given overlay from the map.\n * @param {import(\"./Overlay.js\").default} overlay Overlay.\n * @return {import(\"./Overlay.js\").default|undefined} The removed overlay (or undefined\n * if the overlay was not found).\n * @api\n */\n removeOverlay(overlay) {\n return this.getOverlays().remove(overlay);\n }\n\n /**\n * @param {number} time Time.\n * @private\n */\n renderFrame_(time) {\n const size = this.getSize();\n const view = this.getView();\n const previousFrameState = this.frameState_;\n /** @type {?FrameState} */\n let frameState = null;\n if (size !== undefined && hasArea(size) && view && view.isDef()) {\n const viewHints = view.getHints(\n this.frameState_ ? this.frameState_.viewHints : undefined\n );\n const viewState = view.getState();\n frameState = {\n animate: false,\n coordinateToPixelTransform: this.coordinateToPixelTransform_,\n declutterTree: null,\n extent: getForViewAndSize(\n viewState.center,\n viewState.resolution,\n viewState.rotation,\n size\n ),\n index: this.frameIndex_++,\n layerIndex: 0,\n layerStatesArray: this.getLayerGroup().getLayerStatesArray(),\n pixelRatio: this.pixelRatio_,\n pixelToCoordinateTransform: this.pixelToCoordinateTransform_,\n postRenderFunctions: [],\n size: size,\n tileQueue: this.tileQueue_,\n time: time,\n usedTiles: {},\n viewState: viewState,\n viewHints: viewHints,\n wantedTiles: {},\n mapId: getUid(this),\n renderTargets: {},\n };\n if (viewState.nextCenter && viewState.nextResolution) {\n const rotation = isNaN(viewState.nextRotation)\n ? viewState.rotation\n : viewState.nextRotation;\n\n frameState.nextExtent = getForViewAndSize(\n viewState.nextCenter,\n viewState.nextResolution,\n rotation,\n size\n );\n }\n }\n\n this.frameState_ = frameState;\n this.renderer_.renderFrame(frameState);\n\n if (frameState) {\n if (frameState.animate) {\n this.render();\n }\n Array.prototype.push.apply(\n this.postRenderFunctions_,\n frameState.postRenderFunctions\n );\n\n if (previousFrameState) {\n const moveStart =\n !this.previousExtent_ ||\n (!isEmpty(this.previousExtent_) &&\n !equalsExtent(frameState.extent, this.previousExtent_));\n if (moveStart) {\n this.dispatchEvent(\n new MapEvent(MapEventType.MOVESTART, this, previousFrameState)\n );\n this.previousExtent_ = createOrUpdateEmpty(this.previousExtent_);\n }\n }\n\n const idle =\n this.previousExtent_ &&\n !frameState.viewHints[ViewHint.ANIMATING] &&\n !frameState.viewHints[ViewHint.INTERACTING] &&\n !equalsExtent(frameState.extent, this.previousExtent_);\n\n if (idle) {\n this.dispatchEvent(\n new MapEvent(MapEventType.MOVEEND, this, frameState)\n );\n clone(frameState.extent, this.previousExtent_);\n }\n }\n\n this.dispatchEvent(new MapEvent(MapEventType.POSTRENDER, this, frameState));\n\n this.renderComplete_ =\n this.hasListener(MapEventType.LOADSTART) ||\n this.hasListener(MapEventType.LOADEND) ||\n this.hasListener(RenderEventType.RENDERCOMPLETE)\n ? !this.tileQueue_.getTilesLoading() &&\n !this.tileQueue_.getCount() &&\n !this.getLoadingOrNotReady()\n : undefined;\n\n if (!this.postRenderTimeoutHandle_) {\n this.postRenderTimeoutHandle_ = setTimeout(() => {\n this.postRenderTimeoutHandle_ = undefined;\n this.handlePostRender();\n }, 0);\n }\n }\n\n /**\n * Sets the layergroup of this map.\n * @param {LayerGroup} layerGroup A layer group containing the layers in this map.\n * @observable\n * @api\n */\n setLayerGroup(layerGroup) {\n const oldLayerGroup = this.getLayerGroup();\n if (oldLayerGroup) {\n this.handleLayerRemove_(new GroupEvent('removelayer', oldLayerGroup));\n }\n this.set(MapProperty.LAYERGROUP, layerGroup);\n }\n\n /**\n * Set the size of this map.\n * @param {import(\"./size.js\").Size|undefined} size The size in pixels of the map in the DOM.\n * @observable\n * @api\n */\n setSize(size) {\n this.set(MapProperty.SIZE, size);\n }\n\n /**\n * Set the target element to render this map into.\n * @param {HTMLElement|string} [target] The Element or id of the Element\n * that the map is rendered in.\n * @observable\n * @api\n */\n setTarget(target) {\n this.set(MapProperty.TARGET, target);\n }\n\n /**\n * Set the view for this map.\n * @param {View|Promise} view The view that controls this map.\n * It is also possible to pass a promise that resolves to options for constructing a view. This\n * alternative allows view properties to be resolved by sources or other components that load\n * view-related metadata.\n * @observable\n * @api\n */\n setView(view) {\n if (!view || view instanceof View) {\n this.set(MapProperty.VIEW, view);\n return;\n }\n this.set(MapProperty.VIEW, new View());\n\n const map = this;\n view.then(function (viewOptions) {\n map.setView(new View(viewOptions));\n });\n }\n\n /**\n * Force a recalculation of the map viewport size. This should be called when\n * third-party code changes the size of the map viewport.\n * @api\n */\n updateSize() {\n const targetElement = this.getTargetElement();\n\n let size = undefined;\n if (targetElement) {\n const computedStyle = getComputedStyle(targetElement);\n const width =\n targetElement.offsetWidth -\n parseFloat(computedStyle['borderLeftWidth']) -\n parseFloat(computedStyle['paddingLeft']) -\n parseFloat(computedStyle['paddingRight']) -\n parseFloat(computedStyle['borderRightWidth']);\n const height =\n targetElement.offsetHeight -\n parseFloat(computedStyle['borderTopWidth']) -\n parseFloat(computedStyle['paddingTop']) -\n parseFloat(computedStyle['paddingBottom']) -\n parseFloat(computedStyle['borderBottomWidth']);\n if (!isNaN(width) && !isNaN(height)) {\n size = [width, height];\n if (\n !hasArea(size) &&\n !!(\n targetElement.offsetWidth ||\n targetElement.offsetHeight ||\n targetElement.getClientRects().length\n )\n ) {\n warn(\n \"No map visible because the map container's width or height are 0.\"\n );\n }\n }\n }\n\n const oldSize = this.getSize();\n if (size && (!oldSize || !equals(size, oldSize))) {\n this.setSize(size);\n this.updateViewportSize_();\n }\n }\n\n /**\n * Recomputes the viewport size and save it on the view object (if any)\n * @private\n */\n updateViewportSize_() {\n const view = this.getView();\n if (view) {\n let size = undefined;\n const computedStyle = getComputedStyle(this.viewport_);\n if (computedStyle.width && computedStyle.height) {\n size = [\n parseInt(computedStyle.width, 10),\n parseInt(computedStyle.height, 10),\n ];\n }\n view.setViewportSize(size);\n }\n }\n}\n\n/**\n * @param {MapOptions} options Map options.\n * @return {MapOptionsInternal} Internal map options.\n */\nfunction createOptionsInternal(options) {\n /**\n * @type {HTMLElement|Document}\n */\n let keyboardEventTarget = null;\n if (options.keyboardEventTarget !== undefined) {\n keyboardEventTarget =\n typeof options.keyboardEventTarget === 'string'\n ? document.getElementById(options.keyboardEventTarget)\n : options.keyboardEventTarget;\n }\n\n /**\n * @type {Object}\n */\n const values = {};\n\n const layerGroup =\n options.layers &&\n typeof (/** @type {?} */ (options.layers).getLayers) === 'function'\n ? /** @type {LayerGroup} */ (options.layers)\n : new LayerGroup({\n layers:\n /** @type {Collection|Array} */ (\n options.layers\n ),\n });\n values[MapProperty.LAYERGROUP] = layerGroup;\n\n values[MapProperty.TARGET] = options.target;\n\n values[MapProperty.VIEW] =\n options.view instanceof View ? options.view : new View();\n\n /** @type {Collection} */\n let controls;\n if (options.controls !== undefined) {\n if (Array.isArray(options.controls)) {\n controls = new Collection(options.controls.slice());\n } else {\n assert(\n typeof (/** @type {?} */ (options.controls).getArray) === 'function',\n 'Expected `controls` to be an array or an `ol/Collection.js`'\n );\n controls = options.controls;\n }\n }\n\n /** @type {Collection} */\n let interactions;\n if (options.interactions !== undefined) {\n if (Array.isArray(options.interactions)) {\n interactions = new Collection(options.interactions.slice());\n } else {\n assert(\n typeof (/** @type {?} */ (options.interactions).getArray) ===\n 'function',\n 'Expected `interactions` to be an array or an `ol/Collection.js`'\n );\n interactions = options.interactions;\n }\n }\n\n /** @type {Collection} */\n let overlays;\n if (options.overlays !== undefined) {\n if (Array.isArray(options.overlays)) {\n overlays = new Collection(options.overlays.slice());\n } else {\n assert(\n typeof (/** @type {?} */ (options.overlays).getArray) === 'function',\n 'Expected `overlays` to be an array or an `ol/Collection.js`'\n );\n overlays = options.overlays;\n }\n } else {\n overlays = new Collection();\n }\n\n return {\n controls: controls,\n interactions: interactions,\n keyboardEventTarget: keyboardEventTarget,\n overlays: overlays,\n values: values,\n };\n}\nexport default Map;\n","/**\n * @module ol/ImageState\n */\n\n/**\n * @enum {number}\n */\nexport default {\n IDLE: 0,\n LOADING: 1,\n LOADED: 2,\n ERROR: 3,\n EMPTY: 4,\n};\n","/**\n * @module ol/style/Image\n */\nimport {abstract} from '../util.js';\nimport {toSize} from '../size.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} opacity Opacity.\n * @property {boolean} rotateWithView If the image should get rotated with the view.\n * @property {number} rotation Rotation.\n * @property {number|import(\"../size.js\").Size} scale Scale.\n * @property {Array} displacement Displacement.\n * @property {\"declutter\"|\"obstacle\"|\"none\"|undefined} declutterMode Declutter mode: `declutter`, `obstacle`, 'none */\n\n/**\n * @classdesc\n * A base class used for creating subclasses and not instantiated in\n * apps. Base class for {@link module:ol/style/Icon~Icon}, {@link module:ol/style/Circle~CircleStyle} and\n * {@link module:ol/style/RegularShape~RegularShape}.\n * @abstract\n * @api\n */\nclass ImageStyle {\n /**\n * @param {Options} options Options.\n */\n constructor(options) {\n /**\n * @private\n * @type {number}\n */\n this.opacity_ = options.opacity;\n\n /**\n * @private\n * @type {boolean}\n */\n this.rotateWithView_ = options.rotateWithView;\n\n /**\n * @private\n * @type {number}\n */\n this.rotation_ = options.rotation;\n\n /**\n * @private\n * @type {number|import(\"../size.js\").Size}\n */\n this.scale_ = options.scale;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.scaleArray_ = toSize(options.scale);\n\n /**\n * @private\n * @type {Array}\n */\n this.displacement_ = options.displacement;\n\n /**\n * @private\n * @type {\"declutter\"|\"obstacle\"|\"none\"|undefined}\n */\n this.declutterMode_ = options.declutterMode;\n }\n\n /**\n * Clones the style.\n * @return {ImageStyle} The cloned style.\n * @api\n */\n clone() {\n const scale = this.getScale();\n return new ImageStyle({\n opacity: this.getOpacity(),\n scale: Array.isArray(scale) ? scale.slice() : scale,\n rotation: this.getRotation(),\n rotateWithView: this.getRotateWithView(),\n displacement: this.getDisplacement().slice(),\n declutterMode: this.getDeclutterMode(),\n });\n }\n\n /**\n * Get the symbolizer opacity.\n * @return {number} Opacity.\n * @api\n */\n getOpacity() {\n return this.opacity_;\n }\n\n /**\n * Determine whether the symbolizer rotates with the map.\n * @return {boolean} Rotate with map.\n * @api\n */\n getRotateWithView() {\n return this.rotateWithView_;\n }\n\n /**\n * Get the symoblizer rotation.\n * @return {number} Rotation.\n * @api\n */\n getRotation() {\n return this.rotation_;\n }\n\n /**\n * Get the symbolizer scale.\n * @return {number|import(\"../size.js\").Size} Scale.\n * @api\n */\n getScale() {\n return this.scale_;\n }\n\n /**\n * Get the symbolizer scale array.\n * @return {import(\"../size.js\").Size} Scale array.\n */\n getScaleArray() {\n return this.scaleArray_;\n }\n\n /**\n * Get the displacement of the shape\n * @return {Array} Shape's center displacement\n * @api\n */\n getDisplacement() {\n return this.displacement_;\n }\n\n /**\n * Get the declutter mode of the shape\n * @return {\"declutter\"|\"obstacle\"|\"none\"|undefined} Shape's declutter mode\n * @api\n */\n getDeclutterMode() {\n return this.declutterMode_;\n }\n\n /**\n * Get the anchor point in pixels. The anchor determines the center point for the\n * symbolizer.\n * @abstract\n * @return {Array} Anchor.\n */\n getAnchor() {\n return abstract();\n }\n\n /**\n * Get the image element for the symbolizer.\n * @abstract\n * @param {number} pixelRatio Pixel ratio.\n * @return {import('../DataTile.js').ImageLike} Image element.\n */\n getImage(pixelRatio) {\n return abstract();\n }\n\n /**\n * @abstract\n * @return {import('../DataTile.js').ImageLike} Image element.\n */\n getHitDetectionImage() {\n return abstract();\n }\n\n /**\n * Get the image pixel ratio.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Pixel ratio.\n */\n getPixelRatio(pixelRatio) {\n return 1;\n }\n\n /**\n * @abstract\n * @return {import(\"../ImageState.js\").default} Image state.\n */\n getImageState() {\n return abstract();\n }\n\n /**\n * @abstract\n * @return {import(\"../size.js\").Size} Image size.\n */\n getImageSize() {\n return abstract();\n }\n\n /**\n * Get the origin of the symbolizer.\n * @abstract\n * @return {Array} Origin.\n */\n getOrigin() {\n return abstract();\n }\n\n /**\n * Get the size of the symbolizer (in pixels).\n * @abstract\n * @return {import(\"../size.js\").Size} Size.\n */\n getSize() {\n return abstract();\n }\n\n /**\n * Set the displacement.\n *\n * @param {Array} displacement Displacement.\n * @api\n */\n setDisplacement(displacement) {\n this.displacement_ = displacement;\n }\n\n /**\n * Set the opacity.\n *\n * @param {number} opacity Opacity.\n * @api\n */\n setOpacity(opacity) {\n this.opacity_ = opacity;\n }\n\n /**\n * Set whether to rotate the style with the view.\n *\n * @param {boolean} rotateWithView Rotate with map.\n * @api\n */\n setRotateWithView(rotateWithView) {\n this.rotateWithView_ = rotateWithView;\n }\n\n /**\n * Set the rotation.\n *\n * @param {number} rotation Rotation.\n * @api\n */\n setRotation(rotation) {\n this.rotation_ = rotation;\n }\n\n /**\n * Set the scale.\n *\n * @param {number|import(\"../size.js\").Size} scale Scale.\n * @api\n */\n setScale(scale) {\n this.scale_ = scale;\n this.scaleArray_ = toSize(scale);\n }\n\n /**\n * @abstract\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n listenImageChange(listener) {\n abstract();\n }\n\n /**\n * Load not yet loaded URI.\n * @abstract\n */\n load() {\n abstract();\n }\n\n /**\n * @abstract\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n unlistenImageChange(listener) {\n abstract();\n }\n}\n\nexport default ImageStyle;\n","/**\n * @module ol/colorlike\n */\nimport {toString} from './color.js';\n\n/**\n * A type accepted by CanvasRenderingContext2D.fillStyle\n * or CanvasRenderingContext2D.strokeStyle.\n * Represents a color, pattern, or gradient. The origin for patterns and\n * gradients as fill style is an increment of 512 css pixels from map coordinate\n * `[0, 0]`. For seamless repeat patterns, width and height of the pattern image\n * must be a factor of two (2, 4, 8, ..., 512).\n *\n * @typedef {string|CanvasPattern|CanvasGradient} ColorLike\n * @api\n */\n\n/**\n * @param {import(\"./color.js\").Color|ColorLike} color Color.\n * @return {ColorLike} The color as an {@link ol/colorlike~ColorLike}.\n * @api\n */\nexport function asColorLike(color) {\n if (Array.isArray(color)) {\n return toString(color);\n }\n return color;\n}\n","/**\n * @module ol/style/RegularShape\n */\n\nimport ImageState from '../ImageState.js';\nimport ImageStyle from './Image.js';\nimport {asArray} from '../color.js';\nimport {asColorLike} from '../colorlike.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {\n defaultFillStyle,\n defaultLineCap,\n defaultLineJoin,\n defaultLineWidth,\n defaultMiterLimit,\n defaultStrokeStyle,\n} from '../render/canvas.js';\n\n/**\n * Specify radius for regular polygons, or radius1 and radius2 for stars.\n * @typedef {Object} Options\n * @property {import(\"./Fill.js\").default} [fill] Fill style.\n * @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points\n * is the number of sides.\n * @property {number} [radius] Radius of a regular polygon.\n * @property {number} [radius1] First radius of a star. Ignored if radius is set.\n * @property {number} [radius2] Second radius of a star.\n * @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's points facing up.\n * @property {Array} [displacement=[0, 0]] Displacement of the shape in pixels.\n * Positive values will shift the shape right and up.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).\n * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale. Unless two dimensional scaling is required a better\n * result may be obtained with appropriate settings for `radius`, `radius1` and `radius2`.\n * @property {\"declutter\"|\"obstacle\"|\"none\"|undefined} [declutterMode] Declutter mode.\n */\n\n/**\n * @typedef {Object} RenderOptions\n * @property {import(\"../colorlike.js\").ColorLike} [strokeStyle] StrokeStyle.\n * @property {number} strokeWidth StrokeWidth.\n * @property {number} size Size.\n * @property {CanvasLineCap} lineCap LineCap.\n * @property {Array|null} lineDash LineDash.\n * @property {number} lineDashOffset LineDashOffset.\n * @property {CanvasLineJoin} lineJoin LineJoin.\n * @property {number} miterLimit MiterLimit.\n */\n\n/**\n * @classdesc\n * Set regular shape style for vector features. The resulting shape will be\n * a regular polygon when `radius` is provided, or a star when `radius1` and\n * `radius2` are provided.\n * @api\n */\nclass RegularShape extends ImageStyle {\n /**\n * @param {Options} options Options.\n */\n constructor(options) {\n /**\n * @type {boolean}\n */\n const rotateWithView =\n options.rotateWithView !== undefined ? options.rotateWithView : false;\n\n super({\n opacity: 1,\n rotateWithView: rotateWithView,\n rotation: options.rotation !== undefined ? options.rotation : 0,\n scale: options.scale !== undefined ? options.scale : 1,\n displacement:\n options.displacement !== undefined ? options.displacement : [0, 0],\n declutterMode: options.declutterMode,\n });\n\n /**\n * @private\n * @type {Object}\n */\n this.canvas_ = undefined;\n\n /**\n * @private\n * @type {HTMLCanvasElement}\n */\n this.hitDetectionCanvas_ = null;\n\n /**\n * @private\n * @type {import(\"./Fill.js\").default}\n */\n this.fill_ = options.fill !== undefined ? options.fill : null;\n\n /**\n * @private\n * @type {Array}\n */\n this.origin_ = [0, 0];\n\n /**\n * @private\n * @type {number}\n */\n this.points_ = options.points;\n\n /**\n * @protected\n * @type {number}\n */\n this.radius_ =\n options.radius !== undefined ? options.radius : options.radius1;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.radius2_ = options.radius2;\n\n /**\n * @private\n * @type {number}\n */\n this.angle_ = options.angle !== undefined ? options.angle : 0;\n\n /**\n * @private\n * @type {import(\"./Stroke.js\").default}\n */\n this.stroke_ = options.stroke !== undefined ? options.stroke : null;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.size_ = null;\n\n /**\n * @private\n * @type {RenderOptions}\n */\n this.renderOptions_ = null;\n\n this.render();\n }\n\n /**\n * Clones the style.\n * @return {RegularShape} The cloned style.\n * @api\n */\n clone() {\n const scale = this.getScale();\n const style = new RegularShape({\n fill: this.getFill() ? this.getFill().clone() : undefined,\n points: this.getPoints(),\n radius: this.getRadius(),\n radius2: this.getRadius2(),\n angle: this.getAngle(),\n stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n rotation: this.getRotation(),\n rotateWithView: this.getRotateWithView(),\n scale: Array.isArray(scale) ? scale.slice() : scale,\n displacement: this.getDisplacement().slice(),\n declutterMode: this.getDeclutterMode(),\n });\n style.setOpacity(this.getOpacity());\n return style;\n }\n\n /**\n * Get the anchor point in pixels. The anchor determines the center point for the\n * symbolizer.\n * @return {Array} Anchor.\n * @api\n */\n getAnchor() {\n const size = this.size_;\n if (!size) {\n return null;\n }\n const displacement = this.getDisplacement();\n const scale = this.getScaleArray();\n // anchor is scaled by renderer but displacement should not be scaled\n // so divide by scale here\n return [\n size[0] / 2 - displacement[0] / scale[0],\n size[1] / 2 + displacement[1] / scale[1],\n ];\n }\n\n /**\n * Get the angle used in generating the shape.\n * @return {number} Shape's rotation in radians.\n * @api\n */\n getAngle() {\n return this.angle_;\n }\n\n /**\n * Get the fill style for the shape.\n * @return {import(\"./Fill.js\").default} Fill style.\n * @api\n */\n getFill() {\n return this.fill_;\n }\n\n /**\n * Set the fill style.\n * @param {import(\"./Fill.js\").default} fill Fill style.\n * @api\n */\n setFill(fill) {\n this.fill_ = fill;\n this.render();\n }\n\n /**\n * @return {HTMLCanvasElement} Image element.\n */\n getHitDetectionImage() {\n if (!this.hitDetectionCanvas_) {\n this.createHitDetectionCanvas_(this.renderOptions_);\n }\n return this.hitDetectionCanvas_;\n }\n\n /**\n * Get the image icon.\n * @param {number} pixelRatio Pixel ratio.\n * @return {HTMLCanvasElement} Image or Canvas element.\n * @api\n */\n getImage(pixelRatio) {\n let image = this.canvas_[pixelRatio];\n if (!image) {\n const renderOptions = this.renderOptions_;\n const context = createCanvasContext2D(\n renderOptions.size * pixelRatio,\n renderOptions.size * pixelRatio\n );\n this.draw_(renderOptions, context, pixelRatio);\n\n image = context.canvas;\n this.canvas_[pixelRatio] = image;\n }\n return image;\n }\n\n /**\n * Get the image pixel ratio.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Pixel ratio.\n */\n getPixelRatio(pixelRatio) {\n return pixelRatio;\n }\n\n /**\n * @return {import(\"../size.js\").Size} Image size.\n */\n getImageSize() {\n return this.size_;\n }\n\n /**\n * @return {import(\"../ImageState.js\").default} Image state.\n */\n getImageState() {\n return ImageState.LOADED;\n }\n\n /**\n * Get the origin of the symbolizer.\n * @return {Array} Origin.\n * @api\n */\n getOrigin() {\n return this.origin_;\n }\n\n /**\n * Get the number of points for generating the shape.\n * @return {number} Number of points for stars and regular polygons.\n * @api\n */\n getPoints() {\n return this.points_;\n }\n\n /**\n * Get the (primary) radius for the shape.\n * @return {number} Radius.\n * @api\n */\n getRadius() {\n return this.radius_;\n }\n\n /**\n * Get the secondary radius for the shape.\n * @return {number|undefined} Radius2.\n * @api\n */\n getRadius2() {\n return this.radius2_;\n }\n\n /**\n * Get the size of the symbolizer (in pixels).\n * @return {import(\"../size.js\").Size} Size.\n * @api\n */\n getSize() {\n return this.size_;\n }\n\n /**\n * Get the stroke style for the shape.\n * @return {import(\"./Stroke.js\").default} Stroke style.\n * @api\n */\n getStroke() {\n return this.stroke_;\n }\n\n /**\n * Set the stroke style.\n * @param {import(\"./Stroke.js\").default} stroke Stroke style.\n * @api\n */\n setStroke(stroke) {\n this.stroke_ = stroke;\n this.render();\n }\n\n /**\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n listenImageChange(listener) {}\n\n /**\n * Load not yet loaded URI.\n */\n load() {}\n\n /**\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n unlistenImageChange(listener) {}\n\n /**\n * Calculate additional canvas size needed for the miter.\n * @param {string} lineJoin Line join\n * @param {number} strokeWidth Stroke width\n * @param {number} miterLimit Miter limit\n * @return {number} Additional canvas size needed\n * @private\n */\n calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit) {\n if (\n strokeWidth === 0 ||\n this.points_ === Infinity ||\n (lineJoin !== 'bevel' && lineJoin !== 'miter')\n ) {\n return strokeWidth;\n }\n // m | ^\n // i | |\\ .\n // t >| #\\\n // e | |\\ \\ .\n // r \\s\\\n // | \\t\\ . .\n // \\r\\ . .\n // | \\o\\ . . . . .\n // e \\k\\ . . . .\n // | \\e\\ . . . . .\n // d \\ \\ . . . .\n // | _ _a_ _\\# . . .\n // r1 / ` . .\n // | . .\n // b / . .\n // | . .\n // / r2 . .\n // | . .\n // / . .\n // |α . .\n // / . .\n // ° center\n let r1 = this.radius_;\n let r2 = this.radius2_ === undefined ? r1 : this.radius2_;\n if (r1 < r2) {\n const tmp = r1;\n r1 = r2;\n r2 = tmp;\n }\n const points =\n this.radius2_ === undefined ? this.points_ : this.points_ * 2;\n const alpha = (2 * Math.PI) / points;\n const a = r2 * Math.sin(alpha);\n const b = Math.sqrt(r2 * r2 - a * a);\n const d = r1 - b;\n const e = Math.sqrt(a * a + d * d);\n const miterRatio = e / a;\n if (lineJoin === 'miter' && miterRatio <= miterLimit) {\n return miterRatio * strokeWidth;\n }\n // Calculate the distance from center to the stroke corner where\n // it was cut short because of the miter limit.\n // l\n // ----+---- <= distance from center to here is maxr\n // /####|k ##\\\n // /#####^#####\\\n // /#### /+\\# s #\\\n // /### h/+++\\# t #\\\n // /### t/+++++\\# r #\\\n // /### a/+++++++\\# o #\\\n // /### p/++ fill +\\# k #\\\n ///#### /+++++^+++++\\# e #\\\n //#####/+++++/+\\+++++\\#####\\\n const k = strokeWidth / 2 / miterRatio;\n const l = (strokeWidth / 2) * (d / e);\n const maxr = Math.sqrt((r1 + k) * (r1 + k) + l * l);\n const bevelAdd = maxr - r1;\n if (this.radius2_ === undefined || lineJoin === 'bevel') {\n return bevelAdd * 2;\n }\n // If outer miter is over the miter limit the inner miter may reach through the\n // center and be longer than the bevel, same calculation as above but swap r1 / r2.\n const aa = r1 * Math.sin(alpha);\n const bb = Math.sqrt(r1 * r1 - aa * aa);\n const dd = r2 - bb;\n const ee = Math.sqrt(aa * aa + dd * dd);\n const innerMiterRatio = ee / aa;\n if (innerMiterRatio <= miterLimit) {\n const innerLength = (innerMiterRatio * strokeWidth) / 2 - r2 - r1;\n return 2 * Math.max(bevelAdd, innerLength);\n }\n return bevelAdd * 2;\n }\n\n /**\n * @return {RenderOptions} The render options\n * @protected\n */\n createRenderOptions() {\n let lineCap = defaultLineCap;\n let lineJoin = defaultLineJoin;\n let miterLimit = 0;\n let lineDash = null;\n let lineDashOffset = 0;\n let strokeStyle;\n let strokeWidth = 0;\n\n if (this.stroke_) {\n strokeStyle = this.stroke_.getColor();\n if (strokeStyle === null) {\n strokeStyle = defaultStrokeStyle;\n }\n strokeStyle = asColorLike(strokeStyle);\n strokeWidth = this.stroke_.getWidth();\n if (strokeWidth === undefined) {\n strokeWidth = defaultLineWidth;\n }\n lineDash = this.stroke_.getLineDash();\n lineDashOffset = this.stroke_.getLineDashOffset();\n lineJoin = this.stroke_.getLineJoin();\n if (lineJoin === undefined) {\n lineJoin = defaultLineJoin;\n }\n lineCap = this.stroke_.getLineCap();\n if (lineCap === undefined) {\n lineCap = defaultLineCap;\n }\n miterLimit = this.stroke_.getMiterLimit();\n if (miterLimit === undefined) {\n miterLimit = defaultMiterLimit;\n }\n }\n\n const add = this.calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit);\n const maxRadius = Math.max(this.radius_, this.radius2_ || 0);\n const size = Math.ceil(2 * maxRadius + add);\n\n return {\n strokeStyle: strokeStyle,\n strokeWidth: strokeWidth,\n size: size,\n lineCap: lineCap,\n lineDash: lineDash,\n lineDashOffset: lineDashOffset,\n lineJoin: lineJoin,\n miterLimit: miterLimit,\n };\n }\n\n /**\n * @protected\n */\n render() {\n this.renderOptions_ = this.createRenderOptions();\n const size = this.renderOptions_.size;\n this.canvas_ = {};\n this.size_ = [size, size];\n }\n\n /**\n * @private\n * @param {RenderOptions} renderOptions Render options.\n * @param {CanvasRenderingContext2D} context The rendering context.\n * @param {number} pixelRatio The pixel ratio.\n */\n draw_(renderOptions, context, pixelRatio) {\n context.scale(pixelRatio, pixelRatio);\n // set origin to canvas center\n context.translate(renderOptions.size / 2, renderOptions.size / 2);\n\n this.createPath_(context);\n\n if (this.fill_) {\n let color = this.fill_.getColor();\n if (color === null) {\n color = defaultFillStyle;\n }\n context.fillStyle = asColorLike(color);\n context.fill();\n }\n if (this.stroke_) {\n context.strokeStyle = renderOptions.strokeStyle;\n context.lineWidth = renderOptions.strokeWidth;\n if (renderOptions.lineDash) {\n context.setLineDash(renderOptions.lineDash);\n context.lineDashOffset = renderOptions.lineDashOffset;\n }\n context.lineCap = renderOptions.lineCap;\n context.lineJoin = renderOptions.lineJoin;\n context.miterLimit = renderOptions.miterLimit;\n context.stroke();\n }\n }\n\n /**\n * @private\n * @param {RenderOptions} renderOptions Render options.\n */\n createHitDetectionCanvas_(renderOptions) {\n if (this.fill_) {\n let color = this.fill_.getColor();\n\n // determine if fill is transparent (or pattern or gradient)\n let opacity = 0;\n if (typeof color === 'string') {\n color = asArray(color);\n }\n if (color === null) {\n opacity = 1;\n } else if (Array.isArray(color)) {\n opacity = color.length === 4 ? color[3] : 1;\n }\n if (opacity === 0) {\n // if a transparent fill style is set, create an extra hit-detection image\n // with a default fill style\n const context = createCanvasContext2D(\n renderOptions.size,\n renderOptions.size\n );\n this.hitDetectionCanvas_ = context.canvas;\n\n this.drawHitDetectionCanvas_(renderOptions, context);\n }\n }\n if (!this.hitDetectionCanvas_) {\n this.hitDetectionCanvas_ = this.getImage(1);\n }\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} context The context to draw in.\n */\n createPath_(context) {\n let points = this.points_;\n const radius = this.radius_;\n if (points === Infinity) {\n context.arc(0, 0, radius, 0, 2 * Math.PI);\n } else {\n const radius2 = this.radius2_ === undefined ? radius : this.radius2_;\n if (this.radius2_ !== undefined) {\n points *= 2;\n }\n const startAngle = this.angle_ - Math.PI / 2;\n const step = (2 * Math.PI) / points;\n for (let i = 0; i < points; i++) {\n const angle0 = startAngle + i * step;\n const radiusC = i % 2 === 0 ? radius : radius2;\n context.lineTo(radiusC * Math.cos(angle0), radiusC * Math.sin(angle0));\n }\n context.closePath();\n }\n }\n\n /**\n * @private\n * @param {RenderOptions} renderOptions Render options.\n * @param {CanvasRenderingContext2D} context The context.\n */\n drawHitDetectionCanvas_(renderOptions, context) {\n // set origin to canvas center\n context.translate(renderOptions.size / 2, renderOptions.size / 2);\n\n this.createPath_(context);\n\n context.fillStyle = defaultFillStyle;\n context.fill();\n if (this.stroke_) {\n context.strokeStyle = renderOptions.strokeStyle;\n context.lineWidth = renderOptions.strokeWidth;\n if (renderOptions.lineDash) {\n context.setLineDash(renderOptions.lineDash);\n context.lineDashOffset = renderOptions.lineDashOffset;\n }\n context.lineJoin = renderOptions.lineJoin;\n context.miterLimit = renderOptions.miterLimit;\n context.stroke();\n }\n }\n}\n\nexport default RegularShape;\n","/**\n * @module ol/style/Circle\n */\n\nimport RegularShape from './RegularShape.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Fill.js\").default} [fill] Fill style.\n * @property {number} radius Circle radius.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {Array} [displacement=[0,0]] displacement\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale. A two dimensional scale will produce an ellipse.\n * Unless two dimensional scaling is required a better result may be obtained with an appropriate setting for `radius`.\n * @property {number} [rotation=0] Rotation in radians\n * (positive rotation clockwise, meaningful only when used in conjunction with a two dimensional scale).\n * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view\n * (meaningful only when used in conjunction with a two dimensional scale).\n * @property {\"declutter\"|\"obstacle\"|\"none\"|undefined} [declutterMode] Declutter mode\n */\n\n/**\n * @classdesc\n * Set circle style for vector features.\n * @api\n */\nclass CircleStyle extends RegularShape {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {radius: 5};\n\n super({\n points: Infinity,\n fill: options.fill,\n radius: options.radius,\n stroke: options.stroke,\n scale: options.scale !== undefined ? options.scale : 1,\n rotation: options.rotation !== undefined ? options.rotation : 0,\n rotateWithView:\n options.rotateWithView !== undefined ? options.rotateWithView : false,\n displacement:\n options.displacement !== undefined ? options.displacement : [0, 0],\n declutterMode: options.declutterMode,\n });\n }\n\n /**\n * Clones the style.\n * @return {CircleStyle} The cloned style.\n * @api\n */\n clone() {\n const scale = this.getScale();\n const style = new CircleStyle({\n fill: this.getFill() ? this.getFill().clone() : undefined,\n stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n radius: this.getRadius(),\n scale: Array.isArray(scale) ? scale.slice() : scale,\n rotation: this.getRotation(),\n rotateWithView: this.getRotateWithView(),\n displacement: this.getDisplacement().slice(),\n declutterMode: this.getDeclutterMode(),\n });\n style.setOpacity(this.getOpacity());\n return style;\n }\n\n /**\n * Set the circle radius.\n *\n * @param {number} radius Circle radius.\n * @api\n */\n setRadius(radius) {\n this.radius_ = radius;\n this.render();\n }\n}\n\nexport default CircleStyle;\n","/**\n * @module ol/style/Fill\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null} [color=null] A color, gradient or pattern.\n * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats.\n * Default null; if null, the Canvas/renderer default black will be used.\n */\n\n/**\n * @classdesc\n * Set fill style for vector features.\n * @api\n */\nclass Fill {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options || {};\n\n /**\n * @private\n * @type {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null}\n */\n this.color_ = options.color !== undefined ? options.color : null;\n }\n\n /**\n * Clones the style. The color is not cloned if it is an {@link module:ol/colorlike~ColorLike}.\n * @return {Fill} The cloned style.\n * @api\n */\n clone() {\n const color = this.getColor();\n return new Fill({\n color: Array.isArray(color) ? color.slice() : color || undefined,\n });\n }\n\n /**\n * Get the fill color.\n * @return {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null} Color.\n * @api\n */\n getColor() {\n return this.color_;\n }\n\n /**\n * Set the color.\n *\n * @param {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null} color Color.\n * @api\n */\n setColor(color) {\n this.color_ = color;\n }\n}\n\nexport default Fill;\n","/**\n * @module ol/style/Stroke\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} [color] A color, gradient or pattern.\n * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats.\n * Default null; if null, the Canvas/renderer default black will be used.\n * @property {CanvasLineCap} [lineCap='round'] Line cap style: `butt`, `round`, or `square`.\n * @property {CanvasLineJoin} [lineJoin='round'] Line join style: `bevel`, `round`, or `miter`.\n * @property {Array} [lineDash] Line dash pattern. Default is `null` (no dash).\n * @property {number} [lineDashOffset=0] Line dash offset.\n * @property {number} [miterLimit=10] Miter limit.\n * @property {number} [width] Width.\n */\n\n/**\n * @classdesc\n * Set stroke style for vector features.\n * Note that the defaults given are the Canvas defaults, which will be used if\n * option is not defined. The `get` functions return whatever was entered in\n * the options; they will not return the default.\n * @api\n */\nclass Stroke {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options || {};\n\n /**\n * @private\n * @type {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike}\n */\n this.color_ = options.color !== undefined ? options.color : null;\n\n /**\n * @private\n * @type {CanvasLineCap|undefined}\n */\n this.lineCap_ = options.lineCap;\n\n /**\n * @private\n * @type {Array|null}\n */\n this.lineDash_ = options.lineDash !== undefined ? options.lineDash : null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lineDashOffset_ = options.lineDashOffset;\n\n /**\n * @private\n * @type {CanvasLineJoin|undefined}\n */\n this.lineJoin_ = options.lineJoin;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.miterLimit_ = options.miterLimit;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.width_ = options.width;\n }\n\n /**\n * Clones the style.\n * @return {Stroke} The cloned style.\n * @api\n */\n clone() {\n const color = this.getColor();\n return new Stroke({\n color: Array.isArray(color) ? color.slice() : color || undefined,\n lineCap: this.getLineCap(),\n lineDash: this.getLineDash() ? this.getLineDash().slice() : undefined,\n lineDashOffset: this.getLineDashOffset(),\n lineJoin: this.getLineJoin(),\n miterLimit: this.getMiterLimit(),\n width: this.getWidth(),\n });\n }\n\n /**\n * Get the stroke color.\n * @return {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} Color.\n * @api\n */\n getColor() {\n return this.color_;\n }\n\n /**\n * Get the line cap type for the stroke.\n * @return {CanvasLineCap|undefined} Line cap.\n * @api\n */\n getLineCap() {\n return this.lineCap_;\n }\n\n /**\n * Get the line dash style for the stroke.\n * @return {Array|null} Line dash.\n * @api\n */\n getLineDash() {\n return this.lineDash_;\n }\n\n /**\n * Get the line dash offset for the stroke.\n * @return {number|undefined} Line dash offset.\n * @api\n */\n getLineDashOffset() {\n return this.lineDashOffset_;\n }\n\n /**\n * Get the line join type for the stroke.\n * @return {CanvasLineJoin|undefined} Line join.\n * @api\n */\n getLineJoin() {\n return this.lineJoin_;\n }\n\n /**\n * Get the miter limit for the stroke.\n * @return {number|undefined} Miter limit.\n * @api\n */\n getMiterLimit() {\n return this.miterLimit_;\n }\n\n /**\n * Get the stroke width.\n * @return {number|undefined} Width.\n * @api\n */\n getWidth() {\n return this.width_;\n }\n\n /**\n * Set the color.\n *\n * @param {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} color Color.\n * @api\n */\n setColor(color) {\n this.color_ = color;\n }\n\n /**\n * Set the line cap.\n *\n * @param {CanvasLineCap|undefined} lineCap Line cap.\n * @api\n */\n setLineCap(lineCap) {\n this.lineCap_ = lineCap;\n }\n\n /**\n * Set the line dash.\n *\n * @param {Array|null} lineDash Line dash.\n * @api\n */\n setLineDash(lineDash) {\n this.lineDash_ = lineDash;\n }\n\n /**\n * Set the line dash offset.\n *\n * @param {number|undefined} lineDashOffset Line dash offset.\n * @api\n */\n setLineDashOffset(lineDashOffset) {\n this.lineDashOffset_ = lineDashOffset;\n }\n\n /**\n * Set the line join.\n *\n * @param {CanvasLineJoin|undefined} lineJoin Line join.\n * @api\n */\n setLineJoin(lineJoin) {\n this.lineJoin_ = lineJoin;\n }\n\n /**\n * Set the miter limit.\n *\n * @param {number|undefined} miterLimit Miter limit.\n * @api\n */\n setMiterLimit(miterLimit) {\n this.miterLimit_ = miterLimit;\n }\n\n /**\n * Set the width.\n *\n * @param {number|undefined} width Width.\n * @api\n */\n setWidth(width) {\n this.width_ = width;\n }\n}\n\nexport default Stroke;\n","/**\n * @module ol/style/Style\n */\n\nimport CircleStyle from './Circle.js';\nimport Fill from './Fill.js';\nimport Stroke from './Stroke.js';\nimport {assert} from '../asserts.js';\n\n/**\n * A function that takes an {@link module:ol/Feature~Feature} and a `{number}`\n * representing the view's resolution. The function should return a\n * {@link module:ol/style/Style~Style} or an array of them. This way e.g. a\n * vector layer can be styled. If the function returns `undefined`, the\n * feature will not be rendered.\n *\n * @typedef {function(import(\"../Feature.js\").FeatureLike, number):(Style|Array