Search: look through all saved layers and offline hiking trails

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.
This commit is contained in:
randy committed 2026-11-12 11:37:42 +01:00
1 parent 2611713489
commit 0051a0337c
10 files changed
+316 -21

No files matched your search

+94 -19
View File
@@ -8,14 +8,32 @@ const NOMINATIM_API = "https://nominatim.openstreetmap.org/search";
// 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.
// Online only, like this app's other non-basemap online features (Radar,
// the Wikipedia layer) — no offline geocoding index to fall back to.
// Nominatim: OpenStreetMap's own geocoder, free, no API key, matching the
// online basemap's own OSM-derived style already used here.
// 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) {
@@ -28,6 +46,13 @@ export class SearchControl {
<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>
`;
@@ -41,6 +66,13 @@ export class SearchControl {
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;
}
@@ -67,44 +99,87 @@ export class SearchControl {
const coords = query.match(COORD_PATTERN);
if (coords) {
this._resultsEl.innerHTML = "";
this._jumpTo(Number(coords[1]), Number(coords[2]));
this._jumpTo({ lat: Number(coords[1]), lng: Number(coords[2]) });
return;
}
this._resultsEl.innerHTML = `<li class="search-panel__status">Searching…</li>`;
let places;
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");
places = await (await fetch(url)).json();
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 {
this._resultsEl.innerHTML = `<li class="search-panel__status">Search unavailable — check your connection.</li>`;
return;
return [{ status: "Online search unavailable — no connection." }];
}
this._renderResults(places);
}
_renderResults(places) {
this._results = places;
if (places.length === 0) {
_renderResults(results) {
this._results = results;
if (results.length === 0) {
this._resultsEl.innerHTML = `<li class="search-panel__status">No results</li>`;
return;
}
this._resultsEl.innerHTML = places
.map((place, i) => `<li class="search-panel__result" data-index="${i}">${escapeHtml(place.display_name)}</li>`)
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 place = this._results[Number(el.dataset.index)];
this._jumpTo(Number(place.lat), Number(place.lon));
const result = this._results[Number(el.dataset.index)];
result.open?.();
this._jumpTo(result);
});
});
}
_jumpTo(lat, lng) {
this._map.flyTo({ center: [lng, lat], zoom: Math.max(this._map.getZoom(), 14) });
_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");
}