GET /api/search (lib/maptool/search.rb) matches feature name and description, case- and diacritics-insensitive, across every file in Tracks & Points (shown or not) and every offline hiking-trails country. Parsed features are cached in memory per file by mtime. The search box now queries local sources and Nominatim side by side, labels each result with where it was found, lets you untick sources, and switches a result's layer on if it was off before zooming to it.
187 lines
6.7 KiB
JavaScript
187 lines
6.7 KiB
JavaScript
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 = `
|
|
<button type="button" class="search-ctrl__button" title="Search" aria-label="Search">${SEARCH_ICON}</button>
|
|
<div class="search-panel" hidden>
|
|
<form class="search-panel__form">
|
|
<input type="text" class="search-panel__input" placeholder="Search, or lat, lng">
|
|
</form>
|
|
<div class="search-panel__sources">
|
|
${SOURCES.map(
|
|
(source) => `
|
|
<label><input type="checkbox" value="${source.id}" checked> ${escapeHtml(source.label)}</label>
|
|
`,
|
|
).join("")}
|
|
</div>
|
|
<ul class="search-panel__results"></ul>
|
|
</div>
|
|
`;
|
|
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 = `<li class="search-panel__status">Searching…</li>`;
|
|
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),
|
|
}));
|
|
} 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 = `<li class="search-panel__status">No results</li>`;
|
|
return;
|
|
}
|
|
this._resultsEl.innerHTML = results
|
|
.map((result, i) =>
|
|
result.status
|
|
? `<li class="search-panel__status">${escapeHtml(result.status)}</li>`
|
|
: `<li class="search-panel__result" data-index="${i}">
|
|
${escapeHtml(result.name)}
|
|
<span class="search-panel__where">${escapeHtml(result.where)}</span>
|
|
</li>`,
|
|
)
|
|
.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);
|
|
});
|
|
});
|
|
}
|
|
|
|
_jumpTo({ lat, lng, bbox }) {
|
|
if (bbox && (bbox[0] !== bbox[2] || bbox[1] !== bbox[3])) {
|
|
this._map.fitBounds(bbox, { padding: 40, maxZoom: 15 });
|
|
} else {
|
|
const [x, y] = bbox || [lng, lat];
|
|
this._map.flyTo({ center: [x, y], zoom: Math.max(this._map.getZoom(), 14) });
|
|
}
|
|
this._panel.hidden = true;
|
|
this._button.classList.remove("active");
|
|
}
|
|
}
|