Search the offline map and Wikipedia, nearest results first
Every named OSM object in each country's Geofabrik extract goes into a SQLite FTS5 index (data/places/<CODE>.sqlite, lib/maptool/places.rb), built as the last offline-build step or on its own with rake places:index. Kiwix full-text search is another source; clicking a hit opens the article. Results from every source are sorted by distance from the map center (settlements weighted closer) and show it; each source is queried separately so a slow one doesn't hold up the list.
This commit is contained in:
1 parent
ba9c40ac3d
commit
3f973a26d7
14 files changed
+549
-90
No files matched your search
+90
-40
@@ -10,17 +10,31 @@ const NOMINATIM_API = "https://nominatim.openstreetmap.org/search";
|
||||
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).
|
||||
// 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).
|
||||
@@ -104,72 +118,108 @@ export class SearchControl {
|
||||
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]);
|
||||
// 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, sources) {
|
||||
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", sources.join(","));
|
||||
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,
|
||||
open: () => this._openers[result.source]?.(result.ref, result),
|
||||
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: "Local search failed." }];
|
||||
return [{ status: `${source.label}: search failed.` }];
|
||||
}
|
||||
}
|
||||
|
||||
async _searchNominatim(query) {
|
||||
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) => ({
|
||||
name: place.display_name,
|
||||
where: "Online · Nominatim",
|
||||
lat: Number(place.lat),
|
||||
lng: Number(place.lon),
|
||||
}));
|
||||
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) {
|
||||
_renderResults(results, pending = false) {
|
||||
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("");
|
||||
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}">
|
||||
${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__result").forEach((el) => {
|
||||
el.addEventListener("click", () => {
|
||||
const result = this._results[Number(el.dataset.index)];
|
||||
result.open?.();
|
||||
this._jumpTo(result);
|
||||
if (result.bbox || result.lat != null) this._jumpTo(result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user