UNPKG

maplair

Version:

JavaScript library for mobile-friendly interactive maps

529 lines (528 loc) • 21.9 kB
import { falseFn, stamp } from "../core/Util.js"; import { disableClickPropagation, disableScrollPropagation, on, preventDefault } from "../dom/DomEvent.js"; import { create } from "../dom/DomUtil.js"; import { Control } from "./Control.js"; import { I18n } from "../core/I18n.js"; import { LatLngBounds } from "../geo/LatLngBounds.js"; import { LatLng } from "../geo/LatLng.js"; import { Marker } from "../layer/marker/Marker.js"; // src/control/SearchControl.js /** @import {ControlOptions} from './Control.js' */ /** @import {MaplairMap} from '../map/Map.js' */ /** @import {MaplairEvent} from '../core/Events.js' */ /** @import {LatLngExpression} from '../geo/LatLng.js' */ /** @import {LatLngBoundsExpression} from '../geo/LatLngBounds.js' */ /** @import {Layer} from '../layer/Layer.js' */ /** @import {LayerGroup} from '../layer/LayerGroup.js' */ const searchIcon = "<svg aria-hidden=\"true\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"6.5\" cy=\"6.5\" r=\"4.5\"/><path d=\"M10 10l4.5 4.5\"/></svg>"; const nextRequests = /* @__PURE__ */ new Map(); function delay(ms, signal) { return new Promise((resolve, reject) => { const timeout = setTimeout(resolve, ms); signal.addEventListener("abort", () => { clearTimeout(timeout); reject(signal.reason); }, { once: true }); }); } /** * A result of a search, returned by a [geocoder](#searchcontrol-geocoder). * @typedef {object} SearchResult * @property {string} label The text shown in the list of results, e.g. an address. * @property {LatLngExpression} latlng The position of the result. * @property {LatLngBoundsExpression} [bounds] The extent of the result, e.g. of a city, * which the map fits to instead of zooming to the position. * @property {any} [raw] The original result of the service, for use in event listeners. * @property {Layer} [layer] The found layer, by [`SearchControl.layers()`](#searchcontrol-layers), * e.g. to open its tooltip in a `searchresult` listener. */ /** * A function searching places for a query, see the [`geocoder`](#searchcontrol-geocoder) * option. It should pass the `signal` to `fetch()`: searches are aborted when the user * starts another one. Optional properties of the function: `attribution`, an attribution * text which the control adds to the map, and `autoComplete: false` if the service * forbids searching while typing (overriding the * [`autoComplete`](#searchcontrol-autocomplete) option). * @typedef {((query: string, options: {signal: AbortSignal}) => Promise<SearchResult[]>) & {attribution?: string, autoComplete?: boolean}} Geocoder */ /** * Options of `SearchControl`. * @typedef {object} SearchControlOptions * @property {string} [position='topleft'] The position of the control (one of the map * corners). Possible values are `'topleft'`, `'topright'`, `'bottomleft'` or * `'bottomright'`. * @property {Geocoder} geocoder The function searching places (required), e.g. * [Nominatim](#searchcontrol-nominatim). Coordinates (see * [`LatLng.parse()`](#latlng-parse)) are found without it. * @property {boolean} [collapsed=true] If `true`, the control is collapsed into a button * and expanded on click. * @property {boolean} [autoComplete=false] Whether to search while typing instead of * on <kbd>Enter</kbd>. Not with the public Nominatim service, its * [usage policy](https://operations.osmfoundation.org/policies/nominatim/) forbids * auto-complete. * @property {number} [autoCompleteDelay=250] The delay in milliseconds after typing * before searching with [`autoComplete`](#searchcontrol-autocomplete). * @property {number} [minLength=3] The minimum length of queries searched with * [`autoComplete`](#searchcontrol-autocomplete). * @property {number} [zoom=16] The zoom level for results without bounds, and the * maximum zoom level for fitting the bounds of results. * @property {boolean|((result: SearchResult) => Layer|null|undefined)} [marker=true] Whether * to show a marker at the selected result, or a function returning the layer to show * instead, e.g. a `CircleMarker` highlighting the result (or nothing for none). The * layer is removed when the search is cleared or another result is selected. * @property {boolean} [clearOnMapClick=false] If `true`, a click on the map clears the * search (the field, the results and the marker) and collapses the control. By * default, the click only hides the results and the marker stays. * @property {string} [placeholder] The placeholder of the search field, by default * the translation of "Search". * @property {string} [noResultsText] The message shown if nothing is found, by * default the translation of "No results". * @extends ControlOptions */ /** * The event object of `searchresult`. * @typedef {object} SearchResultEvent * @property {SearchResult} result The selected result. * @property {LatLng} latlng The position of the result. * @property {LatLngBounds|undefined} bounds The extent of the result, if any. * @extends MaplairEvent */ /** * A control with a search field for places, showing the results in a list to select * one with the pointer or the keyboard. The selected result is shown on the map with a * marker. It searches with a [`geocoder`](#searchcontrol-geocoder), e.g. * [Nominatim](#searchcontrol-nominatim) of OpenStreetMap or any other service. * Coordinates like `47.27, 11.4` or `geo:47.27,11.4` are found without a service. * * The public Nominatim service is free, but limited by its * [usage policy](https://operations.osmfoundation.org/policies/nominatim/): it is for * occasional searches of users, not for heavy use (an absolute maximum of one request * per second for all users of an app), and forbids auto-complete. The * [Nominatim geocoder](#searchcontrol-nominatim) follows the technical requirements, * but you are responsible for your use of the service, which you confirm with the * `acceptUsagePolicy` option: for more traffic, use your own Nominatim server or a * commercial provider. * * @example * ```js * new SearchControl({ * geocoder: SearchControl.nominatim({acceptUsagePolicy: true}) * }).addTo(map); * * // Photon of Komoot, which allows auto-complete * new SearchControl({ * autoComplete: true, * async geocoder(query, {signal}) { * const response = await fetch(`https://photon.komoot.io/api/?q=${encodeURIComponent(query)}`, {signal}); * const {features} = await response.json(); * return features.map(({geometry, properties}) => ({ * label: [properties.name, properties.city, properties.country].filter(Boolean).join(', '), * latlng: [geometry.coordinates[1], geometry.coordinates[0]], * raw: properties * })); * } * }).addTo(map); * ``` * * @fires MaplairMap#searchresult {SearchResultEvent} Fired when a result of the * [search control](#searchcontrol) is selected. */ var SearchControl = class SearchControl extends Control { static defaultOptions = { position: "topleft", geocoder: void 0, collapsed: true, autoComplete: false, autoCompleteDelay: 250, minLength: 3, zoom: 16, marker: true, clearOnMapClick: false, placeholder: void 0, noResultsText: void 0 }; /** * Returns a [geocoder](#searchcontrol-geocoder) searching with * [Nominatim](https://nominatim.org/release-docs/latest/api/Search/), by default the * public service of OpenStreetMap. Using it requires that you read and accept its * [usage policy](https://operations.osmfoundation.org/policies/nominatim/) with the * `acceptUsagePolicy` option, otherwise this throws an error. The geocoder sends at most one request per second, caches the results of the last 100 * queries, adds the OpenStreetMap attribution to the map and does not search while * typing with the public service. For more traffic, use your own Nominatim server or a * commercial provider. * * @example * ```js * new SearchControl({ * geocoder: SearchControl.nominatim({acceptUsagePolicy: true, params: {countrycodes: 'at,de'}}) * }).addTo(map); * ``` * @param {object} [options] * @param {string} [options.url='https://nominatim.openstreetmap.org/search'] The URL * of the search endpoint. * @param {Record<string, string>} [options.params] Further query parameters, e.g. * `countrycodes`, `viewbox` or `limit` (5 by default). * @param {boolean} [options.acceptUsagePolicy=false] Confirms that your use of the * public service complies with its * [usage policy](https://operations.osmfoundation.org/policies/nominatim/), required * for the public service. * @returns {Geocoder} */ static nominatim({ url = "https://nominatim.openstreetmap.org/search", params = {}, acceptUsagePolicy = false } = {}) { const { host } = new URL(url), publicService = host === "nominatim.openstreetmap.org"; if (publicService && !acceptUsagePolicy) throw new Error("Using the public Nominatim service requires that you read and accept its usage policy (https://operations.osmfoundation.org/policies/nominatim/) with the acceptUsagePolicy option."); const cache = /* @__PURE__ */ new Map(); async function geocoder(query, { signal }) { const requestUrl = `${url}?${new URLSearchParams({ q: query, format: "jsonv2", limit: "5", ...params })}`; if (cache.has(requestUrl)) return cache.get(requestUrl); const now = Date.now(), next = nextRequests.get(host) ?? 0, wait = next - now; nextRequests.set(host, Math.max(now, next) + 1e3); if (wait > 0) await delay(wait, signal); const response = await fetch(requestUrl, { signal }); if (!response.ok) throw new Error(`Nominatim: ${response.status} ${response.statusText}`); const results = (await response.json()).map((place) => { const [s, n, w, e] = place.boundingbox.map(Number); return { label: place.display_name, latlng: [Number(place.lat), Number(place.lon)], bounds: [[s, w], [n, e]], raw: place }; }); cache.set(requestUrl, results); if (cache.size > 100) cache.delete(cache.keys().next().value); return results; } return Object.defineProperties(geocoder, { attribution: { get: () => `&copy; <a href="https://www.openstreetmap.org/copyright">${I18n.translate("OpenStreetMap contributors")}</a>` }, autoComplete: { value: !publicService } }); } /** * Returns a [geocoder](#searchcontrol-geocoder) searching the layers of a layer group, * e.g. the markers of a `FeatureGroup` or the features of a `GeoJSON` layer, by their * label: a property of their GeoJSON feature (`layer.feature.properties`) or the * result of a function. The group is searched at the time of the search, so layers * added later are found as well, and nested groups without a label are searched * recursively. The search ignores the case and finds the query anywhere in the * label; labels starting with it come first, then in alphabetical order. The results * contain the found `layer` and its GeoJSON feature as `raw`; layers without a * single position (e.g. polygons) have the `bounds` and their center as `latlng`. * Combine it with [`autoComplete`](#searchcontrol-autocomplete) to search while * typing, and with [`marker`](#searchcontrol-marker) `false` or a function to not * cover the found marker with another one. * * @example * ```js * const stations = new GeoJSON(data, { * onEachFeature: (feature, layer) => layer.bindTooltip(feature.properties.name) * }).addTo(map); * new SearchControl({ * geocoder: SearchControl.layers(stations, {property: 'name'}), * autoComplete: true, * minLength: 1, * marker: false * }).addTo(map); * map.on('searchresult', ({result}) => result.layer.openTooltip()); * ``` * @param {LayerGroup} group The layer group to search. * @param {object} [options] * @param {string} [options.property='name'] The property of the GeoJSON features to * search. * @param {(layer: Layer) => string|number|null|undefined} [options.label] A function * returning the label of a layer instead of the `property`, nothing to skip the * layer (or to search its layers, if it is a group). * @param {number} [options.limit=10] The maximum number of results. * @returns {Geocoder} */ static layers(group, { property = "name", label = (layer) => layer.feature?.properties?.[property], limit = 10 } = {}) { return (query) => { query = query.toLocaleLowerCase(); const found = []; group.eachLayer(function search(layer) { const text = label(layer); if (text === void 0 || text === null || text === "") { layer.eachLayer?.(search); return; } const result = { label: String(text), layer, raw: layer.feature }, index = result.label.toLocaleLowerCase().indexOf(query); if (index < 0) return; if (layer.getLatLng) result.latlng = layer.getLatLng(); else if (layer.getBounds?.().isValid()) { result.bounds = layer.getBounds(); result.latlng = result.bounds.getCenter(); } else return; found.push({ result, prefix: index === 0 }); }); return Promise.resolve(found.sort((a, b) => b.prefix - a.prefix || a.result.label.localeCompare(b.result.label)).slice(0, limit).map(({ result }) => result)); }; } /** * Creates a search control. * @param {...SearchControlOptions} args The options. */ constructor(...args) { super(...args); if (!this.options.geocoder) throw new Error("SearchControl: the geocoder option is required, e.g. SearchControl.nominatim()."); this.callInitHooks(SearchControl); } /** * @internal * @param {MaplairMap} map * @returns {HTMLElement} */ onAdd(map) { const className = "maplair-control-search", container = this._container = create("search", `${className} maplair-bar`), form = create("form", `${className}-form`, container), toggle = this._toggle = create("button", `${className}-toggle`, form), input = this._input = create("input", `${className}-input`, form), reset = create("button", `${className}-reset`, form), list = this._list = create("ul", `${className}-results`, container), listId = `${className}-results-${stamp(this)}`, title = I18n.translate("Search"); toggle.type = "button"; toggle.innerHTML = searchIcon; toggle.title = title; toggle.setAttribute("aria-label", title); input.type = "search"; input.placeholder = this.options.placeholder ?? title; input.autocomplete = "off"; input.enterKeyHint = "search"; input.spellcheck = false; input.setAttribute("autocapitalize", "none"); input.setAttribute("autocorrect", "off"); input.role = "combobox"; input.setAttribute("aria-label", title); input.setAttribute("aria-autocomplete", "list"); input.setAttribute("aria-controls", listId); reset.type = "reset"; reset.innerHTML = "<span aria-hidden=\"true\">&times;</span>"; reset.title = I18n.translate("Clear the search"); reset.setAttribute("aria-label", reset.title); list.id = listId; list.role = "listbox"; list.setAttribute("aria-label", I18n.translate("Search results")); this._message = create("div", `${className}-message`, container); this._message.role = "status"; disableClickPropagation(container); disableScrollPropagation(container); on(toggle, "click", this._onToggle, this); on(form, "submit", this._onSubmit, this); on(form, "reset", this._onReset, this); on(input, "input", this._onInput, this); on(input, "keydown", this._onKeyDown, this); on(list, "click", this._onListClick, this); map.on("click", this._onMapClick, this); this._attribution = this.options.geocoder.attribution; map.attributionControl?.addAttribution(this._attribution); this._showResults([]); this._setExpanded(!this.options.collapsed); return container; } /** * @internal * @param {MaplairMap} map */ onRemove(map) { map.off("click", this._onMapClick, this); map.attributionControl?.removeAttribution(this._attribution); this._abort(); this._marker?.remove(); } /** * Expands the search field of a [collapsed](#searchcontrol-collapsed) control and * focuses it. * @returns {this} */ expand() { this._setExpanded(true); this._input.focus(); return this; } /** * Collapses the control into its button, if [collapsed](#searchcontrol-collapsed), * and hides the results. * @returns {this} */ collapse() { this._showResults([]); this._setExpanded(!this.options.collapsed); return this; } /** * Searches the given text and shows the results in the list. Resolves to the results. * @param {string} query * @returns {Promise<SearchResult[]>} */ async search(query) { this._abort(); this._input.value = query; query = query.trim(); if (!query) { this._showResults([]); return []; } const latlng = LatLng.parse(query); if (latlng) { const results = [{ label: query, latlng }]; this._showResults(results); return results; } const controller = this._controller = new AbortController(); this._setLoading(true); try { const results = await this.options.geocoder(query, { signal: controller.signal }); if (!controller.signal.aborted) this._showResults(results, this.options.noResultsText ?? I18n.translate("No results")); return results; } catch (error) { if (controller.signal.aborted) return []; this._showResults([], I18n.translate("The search failed")); throw error; } finally { if (this._controller === controller) { this._controller = null; this._setLoading(false); } } } /** * Shows the given result on the map: zooms to it, shows a * [marker](#searchcontrol-marker) and fires `searchresult` on the map. * @param {SearchResult} result * @returns {this} */ select(result) { const map = this._map, latlng = LatLng.from(result.latlng), bounds = result.bounds ? LatLngBounds.from(result.bounds) : void 0; this._input.value = result.label; this._showResults([]); if (bounds?.isValid() && !bounds.getNorthWest().equals(bounds.getSouthEast())) map.fitBounds(bounds, { maxZoom: this.options.zoom }); else map.setView(latlng, this.options.zoom); this._marker?.remove(); const { marker } = this.options; this._marker = typeof marker === "function" ? marker(result)?.addTo(map) ?? null : marker ? new Marker(latlng, { title: result.label }).addTo(map) : null; map.fire("searchresult", { result, latlng, bounds }); return this; } /** * Clears the search field, the results and the marker. * @returns {this} */ clear() { this._abort(); this._input.value = ""; this._showResults([]); this._marker?.remove(); this._marker = null; return this; } _setExpanded(expanded) { this._container.classList.toggle("maplair-control-search-expanded", expanded); this._toggle.setAttribute("aria-expanded", expanded); } _abort() { clearTimeout(this._autoCompleteTimeout); this._controller?.abort(); this._controller = null; if (this._container) this._setLoading(false); } _setLoading(loading) { this._container.classList.toggle("maplair-control-search-loading", loading); this._list.toggleAttribute("aria-busy", loading); } _showResults(results, message = "") { this._results = results; this._list.replaceChildren(...results.map((result, i) => { const item = create("li", "maplair-control-search-result"); item.id = `${this._list.id}-${i}`; item.role = "option"; item.textContent = result.label; return item; })); this._list.hidden = !results.length; this._message.textContent = results.length ? "" : message; this._input.setAttribute("aria-expanded", !!results.length); this._setActive(-1); } _setActive(index) { this._active = index; for (const [i, item] of [...this._list.children].entries()) item.setAttribute("aria-selected", i === index); if (index < 0) this._input.removeAttribute("aria-activedescendant"); else { const item = this._list.children[index]; this._input.setAttribute("aria-activedescendant", item.id); item.scrollIntoView({ block: "nearest" }); } } _onToggle() { if (this.options.collapsed && !this._container.classList.contains("maplair-control-search-expanded")) this.expand(); else this._onSubmit(); } _onSubmit(e) { if (e) preventDefault(e); const query = this._input.value, result = this._results[this._active], latlng = LatLng.parse(query); if (result) this.select(result); else if (latlng) this.select({ label: query.trim(), latlng }); else this.search(query).catch(falseFn); } _onReset() { this.clear(); this._input.focus(); } _onInput() { clearTimeout(this._autoCompleteTimeout); const query = this._input.value.trim(); if (!this.options.autoComplete || this.options.geocoder.autoComplete === false) this._showResults([]); else if (query.length >= this.options.minLength || LatLng.parse(query)) this._autoCompleteTimeout = setTimeout(() => { this.search(this._input.value).catch(falseFn); }, this.options.autoCompleteDelay); else { this._abort(); this._showResults([]); } } _onKeyDown(e) { if (e.isComposing || e.keyCode === 229) return; const n = this._results.length; if ((e.key === "ArrowDown" || e.key === "ArrowUp") && n) { preventDefault(e); const step = e.key === "ArrowDown" ? 1 : -1; this._setActive(((this._active < 0 && step < 0 ? n : this._active) + step + n) % n); } else if (e.key === "Escape") { preventDefault(e); if (n || this._message.textContent) this._showResults([]); else if (this._input.value) this.clear(); else if (this.options.collapsed) { this.collapse(); this._map.getContainer().focus(); } } } _onListClick(e) { const item = e.target.closest(".maplair-control-search-result"), index = [...this._list.children].indexOf(item); if (index >= 0) this.select(this._results[index]); } _onMapClick() { if (this.options.clearOnMapClick) { this.clear(); this.collapse(); } else if (this._input.value) this._showResults([]); else this.collapse(); } }; export { SearchControl }; //# sourceMappingURL=SearchControl.js.map