Files
maptool/public/js/search.js
T

261 lines
10 KiB
JavaScript

import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { SEARCH_ICON } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
import { addRoutePoint } from "/js/panels.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 (saved layers shown or not, offline
// hiking trails, the offline place index, offline Wikipedia — works with
// no uplink), one request per source so a slow one (Kiwix fetches every
// hit's page) doesn't hold up the rest; "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: "places", label: "Offline map", local: true },
{ id: "layers", label: "My layers", local: true },
{ id: "hiking_trails", label: "Hiking trails", local: true },
{ id: "kiwix", label: "Wikipedia", local: true },
{ id: "nominatim", label: "Online (Nominatim)", local: false },
];
function haversineKm(lat1, lng1, lat2, lng2) {
const rad = Math.PI / 180;
const a = Math.sin(((lat2 - lat1) * rad) / 2) ** 2 + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(((lng2 - lng1) * rad) / 2) ** 2;
return 2 * 6371 * Math.asin(Math.sqrt(a));
}
function formatKm(km) {
return km < 10 ? `${km.toFixed(1)} km` : `${Math.round(km)} km`;
}
// 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;
}
// Every source answers on its own; the list re-renders (nearest first
// across all of them) as each one comes in.
const searchId = (this._searchId = (this._searchId || 0) + 1);
const { lat, lng } = this._map.getCenter();
const enabled = SOURCES.filter((source) => this._enabled.has(source.id));
const bySource = new Map();
const render = () => {
if (searchId !== this._searchId) return; // a newer search started meanwhile
const results = [...bySource.values()].flat();
const found = results.filter((result) => !result.status).sort((a, b) => (a.score ?? Infinity) - (b.score ?? Infinity));
const notes = results.filter((result) => result.status);
const pending = bySource.size < enabled.length;
this._renderResults([...found, ...notes], pending);
};
render();
await Promise.all(
enabled.map(async (source) => {
const results = source.local ? await this._searchLocal(query, source, lat, lng) : await this._searchNominatim(query, lat, lng);
bySource.set(source.id, results);
render();
}),
);
}
async _searchLocal(query, source, lat, lng) {
try {
const url = new URL("/api/search", window.location.origin);
url.searchParams.set("q", query);
url.searchParams.set("sources", source.id);
url.searchParams.set("lat", lat);
url.searchParams.set("lng", lng);
const { results } = await (await fetch(url)).json();
return results.map((result) => ({
name: result.name,
where: result.source_label,
bbox: result.bbox,
score: result.score,
distanceKm: result.distance_km,
// A Wikipedia hit opens its article (through this app's /kiwix
// proxy); everything else switches its layer on, if it has one.
open:
result.source === "kiwix"
? () => window.open(result.ref, "_blank", "noopener")
: () => this._openers[result.source]?.(result.ref, result),
}));
} catch {
return [{ status: `${source.label}: search failed.` }];
}
}
async _searchNominatim(query, lat, lng) {
try {
const url = new URL(NOMINATIM_API);
url.searchParams.set("q", query);
url.searchParams.set("format", "jsonv2");
url.searchParams.set("limit", "5");
// Prefer (not restrict to) what's on screen, so "Lidl" finds the
// nearby one rather than whichever Nominatim ranks first.
const bounds = this._map.getBounds();
url.searchParams.set("viewbox", [bounds.getWest(), bounds.getNorth(), bounds.getEast(), bounds.getSouth()].join(","));
const places = await (await fetch(url)).json();
return places.map((place) => {
const distanceKm = haversineKm(lat, lng, Number(place.lat), Number(place.lon));
return {
name: place.display_name,
where: "Online · Nominatim",
lat: Number(place.lat),
lng: Number(place.lon),
score: distanceKm,
distanceKm,
};
});
} catch {
return [{ status: "Online search unavailable — no connection." }];
}
}
_renderResults(results, pending = false) {
this._results = results;
const tail = pending
? `<li class="search-panel__status">Searching…</li>`
: results.length === 0
? `<li class="search-panel__status">No results</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}">
${result.lat != null || result.bbox ? `<button type="button" class="search-panel__route" title="Add to route" aria-label="Add to route">+</button>` : ""}
${escapeHtml(result.name)}
<span class="search-panel__where">${escapeHtml(
[result.where, result.distanceKm != null && formatKm(result.distanceKm)].filter(Boolean).join(" · "),
)}</span>
</li>`,
)
.join("") + tail;
this._resultsEl.querySelectorAll(".search-panel__route").forEach((button) => {
button.addEventListener("click", (event) => {
event.stopPropagation();
const { lat, lng, bbox, name } = this._results[Number(button.closest("li").dataset.index)];
addRoutePoint(lat != null ? [lng, lat] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], name);
});
});
this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => {
el.addEventListener("click", () => {
const result = this._results[Number(el.dataset.index)];
result.open?.();
if (result.bbox || result.lat != null) 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");
}
}