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:
1 parent
2611713489
commit
0051a0337c
10 files changed
+316
-21
No files matched your search
@@ -59,6 +59,16 @@ independence from connectivity.
|
|||||||
** [x] Fixed: the Unigrid Matrix category filter only re-sliced the *points* source (`_applyCategoryFilter`) — toggling the "Note" category off hid point notes but not polygon/line ones sharing that category. `_linesByPath` now tracks those alongside `_pointsByPath`, re-sliced/scanned the same way
|
** [x] Fixed: the Unigrid Matrix category filter only re-sliced the *points* source (`_applyCategoryFilter`) — toggling the "Note" category off hid point notes but not polygon/line ones sharing that category. `_linesByPath` now tracks those alongside `_pointsByPath`, re-sliced/scanned the same way
|
||||||
* [ ] Offline satellite tile caching (e.g. ESRI) for a selected route area — key for judging surface quality and obstacles when wild camping
|
* [ ] Offline satellite tile caching (e.g. ESRI) for a selected route area — key for judging surface quality and obstacles when wild camping
|
||||||
|
|
||||||
|
== Search
|
||||||
|
|
||||||
|
* [ ] Unified search box — one query across every data source, not just what's currently on the map. `GET /api/search` (`lib/maptool/search.rb`) for local sources, online ones queried from the browser (`public/js/search.js`)
|
||||||
|
** [x] Every layer under Tracks & Points (GPX, FIT, GeoJSON, notes, plugin output) and offline hiking trails — shown *and* hidden ones. Matches name + description, case/diacritics-insensitive ("kosice" finds "Košice"); parsed features cached in memory per file by mtime
|
||||||
|
** [ ] Offline vector data — `offline.pmtiles` is tiles, not searchable by name; extract named places/POIs from the same Geofabrik `.osm.pbf` with `osmium tags-filter` during the offline build (same pattern as `HikingTrails`) into a per-country index, then one more key in `Search::SOURCES`. Probably needs SQLite FTS5 (`sqlite3` gem) at that size instead of the in-memory scan
|
||||||
|
** [x] Every result shows where it was found (layer file / "Hiking trails SK" / "Online · Nominatim"); clicking one zooms to it (fitBounds for a track) and switches its layer on if it was off
|
||||||
|
** [x] Source checklist in the search panel (all on by default), re-runs the search on change
|
||||||
|
** [x] Online sources pluggable — one more entry in search.js's `SOURCES`; Nominatim already in, its failure only adds a "no connection" line under the local results
|
||||||
|
** [ ] Kiwix as a source (its geo/full-text search already backs `GET /api/kiwix/nearby`)
|
||||||
|
|
||||||
== Nice to have (later)
|
== Nice to have (later)
|
||||||
|
|
||||||
Deprioritized for now — revisit after the sections above land.
|
Deprioritized for now — revisit after the sections above land.
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ require_relative "lib/maptool/livetrack_client"
|
|||||||
require_relative "lib/maptool/kiwix"
|
require_relative "lib/maptool/kiwix"
|
||||||
require_relative "lib/maptool/plugins"
|
require_relative "lib/maptool/plugins"
|
||||||
require_relative "lib/maptool/pmtiles_builder"
|
require_relative "lib/maptool/pmtiles_builder"
|
||||||
|
require_relative "lib/maptool/search"
|
||||||
|
|
||||||
module Maptool
|
module Maptool
|
||||||
# Only /login, /auth/callback and /logout ever write to session
|
# Only /login, /auth/callback and /logout ever write to session
|
||||||
@@ -419,6 +420,15 @@ module Maptool
|
|||||||
send_file path, type: "application/geo+json"
|
send_file path, type: "application/geo+json"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# The search box's local half (public/js/search.js) — every saved
|
||||||
|
# layer, shown or not, plus offline hiking trails. Read-only and
|
||||||
|
# login-free like the tree listing: viewing needs no account.
|
||||||
|
get "/api/search" do
|
||||||
|
sources = params[:sources].to_s.split(",")
|
||||||
|
sources = Search::SOURCES.keys if sources.empty?
|
||||||
|
json results: Search.query(params[:q], gpx_store: GPX_STORE, data_dir: DATA_DIR, sources: sources)
|
||||||
|
end
|
||||||
|
|
||||||
# Pinged once per page load (public/js/map.js) — url is a same-origin
|
# Pinged once per page load (public/js/map.js) — url is a same-origin
|
||||||
# path (not kiwix-serve's own address, which the browser can't reach
|
# path (not kiwix-serve's own address, which the browser can't reach
|
||||||
# directly behind the reverse proxy in front of this app), proxied by
|
# directly behind the reverse proxy in front of this app), proxied by
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
require "json"
|
||||||
|
require_relative "gpx"
|
||||||
|
require_relative "fit"
|
||||||
|
require_relative "pmtiles_builder"
|
||||||
|
|
||||||
|
module Maptool
|
||||||
|
# Server-side half of the search box (public/js/search.js): looks through
|
||||||
|
# every saved layer, whether it's currently shown on the map or not, and
|
||||||
|
# every offline hiking-trails country. Online providers (Nominatim) are
|
||||||
|
# queried by the browser itself, so this route keeps working with no
|
||||||
|
# uplink at all.
|
||||||
|
#
|
||||||
|
# Each source is a name -> a list of [label, ref, file on disk, reader]
|
||||||
|
# entries (ref is what the browser needs to switch that layer on).
|
||||||
|
# Adding one (e.g. an offline place-name index pulled from the Geofabrik
|
||||||
|
# PBF) means adding a key to SOURCES and nothing else.
|
||||||
|
module Search
|
||||||
|
LIMIT = 50
|
||||||
|
|
||||||
|
SOURCES = {
|
||||||
|
"layers" => lambda do |gpx_store, _data_dir|
|
||||||
|
files(gpx_store.tree).map do |path|
|
||||||
|
[path, path, gpx_store.resolve_file(path), -> { gpx_store.geojson(path) }]
|
||||||
|
end
|
||||||
|
end,
|
||||||
|
"hiking_trails" => lambda do |_gpx_store, data_dir|
|
||||||
|
PmtilesBuilder.hiking_trails_countries(data_dir).map do |code|
|
||||||
|
path = PmtilesBuilder.hiking_trails_country_path(data_dir, code)
|
||||||
|
["Hiking trails #{code}", code, path, -> { File.read(path) }]
|
||||||
|
end
|
||||||
|
end,
|
||||||
|
}.freeze
|
||||||
|
|
||||||
|
# path => [mtime, entries] — a country's hiking-trails file runs to tens
|
||||||
|
# of MB, so it's parsed once per change, not once per keystroke.
|
||||||
|
# ponytail: unbounded in-memory cache, fine for a handful of files; an
|
||||||
|
# on-disk/SQLite FTS index once the offline place-name source lands.
|
||||||
|
@cache = {}
|
||||||
|
|
||||||
|
def self.query(text, gpx_store:, data_dir:, sources: SOURCES.keys)
|
||||||
|
words = normalize(text).split
|
||||||
|
return [] if words.empty?
|
||||||
|
|
||||||
|
results = []
|
||||||
|
(sources & SOURCES.keys).each do |source|
|
||||||
|
SOURCES[source].call(gpx_store, data_dir).each do |label, ref, disk_path, read|
|
||||||
|
entries(disk_path, read).each do |entry|
|
||||||
|
next unless words.all? { |word| entry[:text].include?(word) }
|
||||||
|
|
||||||
|
results << entry.except(:text).merge(source: source, source_label: label, ref: ref)
|
||||||
|
return results if results.size >= LIMIT
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
results
|
||||||
|
end
|
||||||
|
|
||||||
|
# Lowercased, diacritics stripped — "kosice" finds "Košice".
|
||||||
|
def self.normalize(text)
|
||||||
|
text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").downcase
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.entries(path, read)
|
||||||
|
mtime = File.mtime(path)
|
||||||
|
cached = @cache[path]
|
||||||
|
return cached[1] if cached && cached[0] == mtime
|
||||||
|
|
||||||
|
entries = begin
|
||||||
|
JSON.parse(read.call).fetch("features", []).filter_map { |feature| entry(feature, File.basename(path)) }
|
||||||
|
rescue JSON::ParserError, Gpx::ParseError, Fit::ParseError, Errno::ENOENT
|
||||||
|
[]
|
||||||
|
end
|
||||||
|
@cache[path] = [mtime, entries]
|
||||||
|
entries
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.entry(feature, fallback_name)
|
||||||
|
coords = feature.dig("geometry", "coordinates")
|
||||||
|
return nil unless coords.is_a?(Array) && !coords.empty?
|
||||||
|
|
||||||
|
props = feature["properties"] || {}
|
||||||
|
name = props["name"].to_s.strip
|
||||||
|
name = fallback_name if name.empty?
|
||||||
|
lngs, lats = positions(coords).map { |p| p.first(2) }.transpose
|
||||||
|
{
|
||||||
|
name: name,
|
||||||
|
kind: props["kind"] || feature.dig("geometry", "type"),
|
||||||
|
bbox: [lngs.min, lats.min, lngs.max, lats.max],
|
||||||
|
text: normalize("#{name} #{props["description"]}"),
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.positions(coords)
|
||||||
|
coords.first.is_a?(Numeric) ? [coords] : coords.flat_map { |c| positions(c) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.files(node)
|
||||||
|
(node["children"] || []).flat_map do |child|
|
||||||
|
child["type"] == "folder" ? files(child) : [child["path"]]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1164,6 +1164,22 @@ html, body {
|
|||||||
color: #888;
|
color: #888;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.search-panel__sources {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 2px 10px;
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-panel__where {
|
||||||
|
display: block;
|
||||||
|
font-size: 11px;
|
||||||
|
color: #888;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
.notes-ctrl {
|
.notes-ctrl {
|
||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -301,6 +301,7 @@ export class GpxPanelControl {
|
|||||||
const checkbox = document.createElement("input");
|
const checkbox = document.createElement("input");
|
||||||
checkbox.type = "checkbox";
|
checkbox.type = "checkbox";
|
||||||
checkbox.checked = this._visible.has(file.path);
|
checkbox.checked = this._visible.has(file.path);
|
||||||
|
checkbox.dataset.path = file.path;
|
||||||
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
|
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
|
||||||
// Just the real, as-uploaded name — it used to grow a ".geojson" suffix
|
// Just the real, as-uploaded name — it used to grow a ".geojson" suffix
|
||||||
// once cached (matching the real "<path>.geojson" cache file on disk),
|
// once cached (matching the real "<path>.geojson" cache file on disk),
|
||||||
@@ -482,6 +483,15 @@ export class GpxPanelControl {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Called by the search box (search.js) when a result comes from a file
|
||||||
|
// that isn't shown yet — same as ticking its box in the tree by hand.
|
||||||
|
show(path) {
|
||||||
|
if (this._visible.has(path)) return;
|
||||||
|
const checkbox = [...this._treeContainer.querySelectorAll("input[data-path]")].find((input) => input.dataset.path === path);
|
||||||
|
if (checkbox) checkbox.checked = true;
|
||||||
|
this._toggleFile(path, true, checkbox);
|
||||||
|
}
|
||||||
|
|
||||||
async _toggleFile(path, visible, checkbox) {
|
async _toggleFile(path, visible, checkbox) {
|
||||||
if (visible) {
|
if (visible) {
|
||||||
this._visible.add(path);
|
this._visible.add(path);
|
||||||
|
|||||||
@@ -180,6 +180,14 @@ export class HikingTrailsControl {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Search box (search.js) picked a trail from a country that isn't ticked.
|
||||||
|
showCountry(code) {
|
||||||
|
const input = [...this._countryList.querySelectorAll("input")].find((el) => el.value === code);
|
||||||
|
if (!input || input.checked) return;
|
||||||
|
input.checked = true;
|
||||||
|
this._toggleCountry(code, true);
|
||||||
|
}
|
||||||
|
|
||||||
_toggleOnline(active) {
|
_toggleOnline(active) {
|
||||||
this._active = active;
|
this._active = active;
|
||||||
if (active) this._addOnlineLayer();
|
if (active) this._addOnlineLayer();
|
||||||
|
|||||||
+8
-2
@@ -444,7 +444,8 @@ const SLOVAKIA_BOUNDS = [
|
|||||||
[16.83, 47.73],
|
[16.83, 47.73],
|
||||||
[22.57, 49.61],
|
[22.57, 49.61],
|
||||||
];
|
];
|
||||||
map.addControl(new SearchControl(), "top-left");
|
const searchControl = new SearchControl();
|
||||||
|
map.addControl(searchControl, "top-left");
|
||||||
map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-left");
|
map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-left");
|
||||||
// showCompass: false — this map never rotates, so a bearing-reset button
|
// showCompass: false — this map never rotates, so a bearing-reset button
|
||||||
// (NavigationControl's default third button) would just be dead weight.
|
// (NavigationControl's default third button) would just be dead weight.
|
||||||
@@ -545,9 +546,14 @@ const profilePanel = new TrackProfilePanel(map);
|
|||||||
profilePanel.mount();
|
profilePanel.mount();
|
||||||
|
|
||||||
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Explorer"></div>`);
|
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Explorer"></div>`);
|
||||||
new GpxPanelControl(map, profilePanel).mount(sidebar);
|
const gpxPanel = new GpxPanelControl(map, profilePanel);
|
||||||
|
gpxPanel.mount(sidebar);
|
||||||
const overlaysControl = new OverlaysControl(map);
|
const overlaysControl = new OverlaysControl(map);
|
||||||
overlaysControl.mount(sidebar);
|
overlaysControl.mount(sidebar);
|
||||||
|
searchControl.setLayerOpeners({
|
||||||
|
layers: (path) => gpxPanel.show(path),
|
||||||
|
hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code),
|
||||||
|
});
|
||||||
pitchToggle.setOverlaysControl(overlaysControl);
|
pitchToggle.setOverlaysControl(overlaysControl);
|
||||||
// Running a plugin needs a login (POST /api/plugins/:name/run) — same
|
// Running a plugin needs a login (POST /api/plugins/:name/run) — same
|
||||||
// "hide the write-only affordance" story as NotesControl above.
|
// "hide the write-only affordance" story as NotesControl above.
|
||||||
|
|||||||
@@ -249,6 +249,10 @@ export class OverlaysControl {
|
|||||||
this._hikingTrails.setOfflineCountries(countries);
|
this._hikingTrails.setOfflineCountries(countries);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
showHikingTrailsCountry(code) {
|
||||||
|
this._hikingTrails.showCountry(code);
|
||||||
|
}
|
||||||
|
|
||||||
// Called by map.js's PitchToggleControl whenever the 3D pitch toggle
|
// Called by map.js's PitchToggleControl whenever the 3D pitch toggle
|
||||||
// changes, so raised terrain follows the camera tilt rather than needing
|
// changes, so raised terrain follows the camera tilt rather than needing
|
||||||
// the "Terrain shading" checkbox re-clicked to notice.
|
// the "Terrain shading" checkbox re-clicked to notice.
|
||||||
|
|||||||
+94
-19
@@ -8,14 +8,32 @@ const NOMINATIM_API = "https://nominatim.openstreetmap.org/search";
|
|||||||
// there with no network round-trip.
|
// there with no network round-trip.
|
||||||
const COORD_PATTERN = /^\s*(-?\d+(?:\.\d+)?)\s*[, ]\s*(-?\d+(?:\.\d+)?)\s*$/;
|
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.
|
// 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,
|
// Every result says where it was found; picking one from a layer that's
|
||||||
// the Wikipedia layer) — no offline geocoding index to fall back to.
|
// currently switched off switches it on (see setLayerOpeners).
|
||||||
// Nominatim: OpenStreetMap's own geocoder, free, no API key, matching the
|
|
||||||
// online basemap's own OSM-derived style already used here.
|
|
||||||
export class SearchControl {
|
export class SearchControl {
|
||||||
constructor() {
|
constructor() {
|
||||||
this._results = [];
|
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) {
|
onAdd(map) {
|
||||||
@@ -28,6 +46,13 @@ export class SearchControl {
|
|||||||
<form class="search-panel__form">
|
<form class="search-panel__form">
|
||||||
<input type="text" class="search-panel__input" placeholder="Search, or lat, lng">
|
<input type="text" class="search-panel__input" placeholder="Search, or lat, lng">
|
||||||
</form>
|
</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>
|
<ul class="search-panel__results"></ul>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
@@ -41,6 +66,13 @@ export class SearchControl {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
this._search();
|
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;
|
return this._container;
|
||||||
}
|
}
|
||||||
@@ -67,44 +99,87 @@ export class SearchControl {
|
|||||||
const coords = query.match(COORD_PATTERN);
|
const coords = query.match(COORD_PATTERN);
|
||||||
if (coords) {
|
if (coords) {
|
||||||
this._resultsEl.innerHTML = "";
|
this._resultsEl.innerHTML = "";
|
||||||
this._jumpTo(Number(coords[1]), Number(coords[2]));
|
this._jumpTo({ lat: Number(coords[1]), lng: Number(coords[2]) });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this._resultsEl.innerHTML = `<li class="search-panel__status">Searching…</li>`;
|
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 {
|
try {
|
||||||
const url = new URL(NOMINATIM_API);
|
const url = new URL(NOMINATIM_API);
|
||||||
url.searchParams.set("q", query);
|
url.searchParams.set("q", query);
|
||||||
url.searchParams.set("format", "jsonv2");
|
url.searchParams.set("format", "jsonv2");
|
||||||
url.searchParams.set("limit", "5");
|
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 {
|
} catch {
|
||||||
this._resultsEl.innerHTML = `<li class="search-panel__status">Search unavailable — check your connection.</li>`;
|
return [{ status: "Online search unavailable — no connection." }];
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
this._renderResults(places);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_renderResults(places) {
|
_renderResults(results) {
|
||||||
this._results = places;
|
this._results = results;
|
||||||
if (places.length === 0) {
|
if (results.length === 0) {
|
||||||
this._resultsEl.innerHTML = `<li class="search-panel__status">No results</li>`;
|
this._resultsEl.innerHTML = `<li class="search-panel__status">No results</li>`;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this._resultsEl.innerHTML = places
|
this._resultsEl.innerHTML = results
|
||||||
.map((place, i) => `<li class="search-panel__result" data-index="${i}">${escapeHtml(place.display_name)}</li>`)
|
.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("");
|
.join("");
|
||||||
this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => {
|
this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => {
|
||||||
el.addEventListener("click", () => {
|
el.addEventListener("click", () => {
|
||||||
const place = this._results[Number(el.dataset.index)];
|
const result = this._results[Number(el.dataset.index)];
|
||||||
this._jumpTo(Number(place.lat), Number(place.lon));
|
result.open?.();
|
||||||
|
this._jumpTo(result);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
_jumpTo(lat, lng) {
|
_jumpTo({ lat, lng, bbox }) {
|
||||||
this._map.flyTo({ center: [lng, lat], zoom: Math.max(this._map.getZoom(), 14) });
|
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._panel.hidden = true;
|
||||||
this._button.classList.remove("active");
|
this._button.classList.remove("active");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
require_relative "test_helper"
|
||||||
|
require "maptool/gpx_store"
|
||||||
|
require "maptool/search"
|
||||||
|
require "stringio"
|
||||||
|
|
||||||
|
class SearchTest < Minitest::Test
|
||||||
|
def setup
|
||||||
|
@data_dir = Dir.mktmpdir
|
||||||
|
@store = Maptool::GpxStore.new(File.join(@data_dir, "gpx"))
|
||||||
|
camp = { "type" => "FeatureCollection", "features" => [
|
||||||
|
point("Kemp Košice", 21.26, 48.72, "pitná voda"),
|
||||||
|
{ "type" => "Feature", "properties" => { "kind" => "track" },
|
||||||
|
"geometry" => { "type" => "LineString", "coordinates" => [[17.0, 48.0, 150], [18.0, 49.0, 300]] } },
|
||||||
|
] }
|
||||||
|
@store.save(folder: "trips", filename: "camps.geojson", io: StringIO.new(JSON.generate(camp)))
|
||||||
|
|
||||||
|
trails = File.join(@data_dir, "hiking_trails")
|
||||||
|
FileUtils.mkdir_p(trails)
|
||||||
|
File.write(File.join(trails, "SK.geojson"),
|
||||||
|
JSON.generate("type" => "FeatureCollection", "features" => [point("Cesta hrdinov SNP", 19.0, 48.8)]))
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_finds_across_sources_ignoring_case_and_diacritics_and_says_where
|
||||||
|
layer = search("kosice")
|
||||||
|
assert_equal [["Kemp Košice", "layers", "trips/camps.geojson"]], layer.map { |r| r.values_at(:name, :source, :ref) }
|
||||||
|
|
||||||
|
trail = search("snp hrdinov").first
|
||||||
|
assert_equal ["hiking_trails", "SK", "Hiking trails SK"], trail.values_at(:source, :ref, :source_label)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_matches_description_and_falls_back_to_file_name_with_bbox
|
||||||
|
assert_equal ["Kemp Košice"], search("voda").map { |r| r[:name] }
|
||||||
|
|
||||||
|
track = search("camps").first
|
||||||
|
assert_equal [17.0, 48.0, 18.0, 49.0], track[:bbox]
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_source_filter_and_blank_query
|
||||||
|
assert_empty search("snp", sources: ["layers"])
|
||||||
|
assert_empty search(" ")
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def search(text, **opts)
|
||||||
|
Maptool::Search.query(text, gpx_store: @store, data_dir: @data_dir, **opts)
|
||||||
|
end
|
||||||
|
|
||||||
|
def point(name, lng, lat, description = nil)
|
||||||
|
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => [lng, lat] },
|
||||||
|
"properties" => { "name" => name, "description" => description }.compact }
|
||||||
|
end
|
||||||
|
end
|
||||||
Reference in new issue
Block a user