import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { SEARCH_ICON } from "/js/icons.js"; import { escapeHtml } from "/js/gpx.js"; const NOMINATIM_API = "https://nominatim.openstreetmap.org/search"; // "lat, lng" / "lat lng" decimal degrees — the same plain-text shape the // topbar's own coordinate readout copies to the clipboard (map.js). Tried // before hitting the geocoder, so pasting a coordinate pair jumps straight // there with no network round-trip. const COORD_PATTERN = /^\s*(-?\d+(?:\.\d+)?)\s*[, ]\s*(-?\d+(?:\.\d+)?)\s*$/; // Sources the search box can look through, all ticked by default. "local" // ones are answered by GET /api/search (every saved layer, shown or not, // plus offline hiking trails — works with no uplink); "online" ones are // queried straight from the browser and just come back empty when there's // no connection. A new provider is one more entry here (plus, for a local // one, a key in lib/maptool/search.rb's SOURCES). const SOURCES = [ { id: "layers", label: "My layers", local: true }, { id: "hiking_trails", label: "Hiking trails", local: true }, { id: "nominatim", label: "Online (Nominatim)", local: false }, ]; // A place-name/coordinate search box, matching NPS's own Park Tiles viewer. // Every result says where it was found; picking one from a layer that's // currently switched off switches it on (see setLayerOpeners). export class SearchControl { constructor() { this._results = []; this._enabled = new Set(SOURCES.map((source) => source.id)); this._openers = {}; } // { layers: (path) => ..., hiking_trails: (code) => ... } — set from // map.js once the panels owning those layers exist. setLayerOpeners(openers) { this._openers = openers; } onAdd(map) { this._map = map; this._container = document.createElement("div"); this._container.className = "maplibregl-ctrl maplibregl-ctrl-group search-ctrl"; this._container.innerHTML = ` `; this._button = this._container.querySelector(".search-ctrl__button"); this._panel = this._container.querySelector(".search-panel"); this._input = this._container.querySelector(".search-panel__input"); this._resultsEl = this._container.querySelector(".search-panel__results"); this._button.addEventListener("click", () => this._toggle()); this._container.querySelector(".search-panel__form").addEventListener("submit", (event) => { event.preventDefault(); this._search(); }); this._container.querySelectorAll(".search-panel__sources input").forEach((input) => { input.addEventListener("change", () => { if (input.checked) this._enabled.add(input.value); else this._enabled.delete(input.value); if (this._input.value.trim()) this._search(); }); }); return this._container; } onRemove() { this._container.remove(); } getDefaultPosition() { return "top-left"; } _toggle() { const opening = this._panel.hidden; this._panel.hidden = !opening; this._button.classList.toggle("active", opening); if (opening) this._input.focus(); } async _search() { const query = this._input.value.trim(); if (!query) return; const coords = query.match(COORD_PATTERN); if (coords) { this._resultsEl.innerHTML = ""; this._jumpTo({ lat: Number(coords[1]), lng: Number(coords[2]) }); return; } this._resultsEl.innerHTML = `
  • Searching…
  • `; const local = SOURCES.filter((source) => source.local && this._enabled.has(source.id)).map((source) => source.id); const [localResults, onlineResults] = await Promise.all([ local.length ? this._searchLocal(query, local) : [], this._enabled.has("nominatim") ? this._searchNominatim(query) : [], ]); if (this._input.value.trim() !== query) return; // a newer search started meanwhile this._renderResults([...localResults, ...onlineResults]); } async _searchLocal(query, sources) { try { const url = new URL("/api/search", window.location.origin); url.searchParams.set("q", query); url.searchParams.set("sources", sources.join(",")); const { results } = await (await fetch(url)).json(); return results.map((result) => ({ name: result.name, where: result.source_label, bbox: result.bbox, open: () => this._openers[result.source]?.(result.ref, result), })); } catch { return [{ status: "Local search failed." }]; } } async _searchNominatim(query) { try { const url = new URL(NOMINATIM_API); url.searchParams.set("q", query); url.searchParams.set("format", "jsonv2"); url.searchParams.set("limit", "5"); const places = await (await fetch(url)).json(); return places.map((place) => ({ name: place.display_name, where: "Online · Nominatim", lat: Number(place.lat), lng: Number(place.lon), })); } catch { return [{ status: "Online search unavailable — no connection." }]; } } _renderResults(results) { this._results = results; if (results.length === 0) { this._resultsEl.innerHTML = `
  • No results
  • `; return; } this._resultsEl.innerHTML = results .map((result, i) => result.status ? `
  • ${escapeHtml(result.status)}
  • ` : `
  • ${escapeHtml(result.name)} ${escapeHtml(result.where)}
  • `, ) .join(""); this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => { el.addEventListener("click", () => { const result = this._results[Number(el.dataset.index)]; result.open?.(); this._jumpTo(result); }); }); } // A point target (typed coordinates, a geocoded place, a waypoint) also // gets a highlight marker so it's findable once the map stops moving — // one at a time, cleared by the next jump or by clicking it. _jumpTo({ lat, lng, bbox }) { this._marker?.remove(); this._marker = null; if (bbox && (bbox[0] !== bbox[2] || bbox[1] !== bbox[3])) { this._map.fitBounds(bbox, { padding: 40, maxZoom: 15 }); } else { const center = bbox ? bbox.slice(0, 2) : [lng, lat]; this._map.flyTo({ center, zoom: Math.max(this._map.getZoom(), 14) }); const el = document.createElement("div"); el.className = "search-highlight"; el.title = "Click to clear"; el.addEventListener("click", (event) => { event.stopPropagation(); this._marker?.remove(); this._marker = null; }); this._marker = new Marker({ element: el }).setLngLat(center).addTo(this._map); } this._panel.hidden = true; this._button.classList.remove("active"); } }