From 3f973a26d7a5dccba6e78844c7ffca2d7b50bd89 Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Thu, 12 Nov 2026 12:13:13 +0100 Subject: [PATCH] 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/.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. --- Gemfile | 1 + Gemfile.lock | 21 +++++ Rakefile | 14 ++++ TODO.adoc | 7 +- app.rb | 11 ++- lib/maptool/kiwix.rb | 34 ++++++-- lib/maptool/places.rb | 138 +++++++++++++++++++++++++++++++++ lib/maptool/pmtiles_builder.rb | 48 ++++++++++++ lib/maptool/search.rb | 104 +++++++++++++++++-------- public/js/search.js | 130 +++++++++++++++++++++---------- test/test_kiwix.rb | 40 ++++++++++ test/test_places.rb | 68 ++++++++++++++++ test/test_pmtiles_builder.rb | 12 ++- test/test_search.rb | 11 +++ 14 files changed, 549 insertions(+), 90 deletions(-) create mode 100644 lib/maptool/places.rb create mode 100644 test/test_places.rb diff --git a/Gemfile b/Gemfile index 8e9d3a4..ed57413 100644 --- a/Gemfile +++ b/Gemfile @@ -6,6 +6,7 @@ gem "puma", "~> 8.0" gem "rexml", "~> 3.4" gem "oauth2", "~> 2.0" gem "rubyzip", "~> 3.0" +gem "sqlite3", "~> 2.10" group :development do gem "rerun" diff --git a/Gemfile.lock b/Gemfile.lock index 1e3b7a6..2318d33 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -98,6 +98,16 @@ GEM snaky_hash (2.0.9) hashie (>= 0.1.0, < 6) version_gem (~> 1.1, >= 1.1.16) + sqlite3 (2.10.2-aarch64-linux-gnu) + sqlite3 (2.10.2-aarch64-linux-musl) + sqlite3 (2.10.2-arm-linux-gnu) + sqlite3 (2.10.2-arm-linux-musl) + sqlite3 (2.10.2-arm64-darwin) + sqlite3 (2.10.2-x86-linux-gnu) + sqlite3 (2.10.2-x86-linux-musl) + sqlite3 (2.10.2-x86_64-darwin) + sqlite3 (2.10.2-x86_64-linux-gnu) + sqlite3 (2.10.2-x86_64-linux-musl) tilt (2.9.0) timeout (0.6.1) uri (1.1.2) @@ -126,6 +136,7 @@ DEPENDENCIES rubyzip (~> 3.0) sinatra (~> 4.2) sinatra-contrib (~> 4.2) + sqlite3 (~> 2.10) CHECKSUMS anonymous_loader (0.1.5) sha256=c96a4a1b5f49f320037fae63e931ac15b3823686e4f0ee6f24f75a0ade4227cb @@ -176,6 +187,16 @@ CHECKSUMS sinatra (4.2.1) sha256=b7aeb9b11d046b552972ade834f1f9be98b185fa8444480688e3627625377080 sinatra-contrib (4.2.1) sha256=10d091c944d268aa910c618ea40a3c3ebe0533e6e32990d84af92235a3d26b4a snaky_hash (2.0.9) sha256=e93e6ec80632f8c8c4a3fe6e25d51eaef253e0e58dc7100f0f8370320feb3128 + sqlite3 (2.10.2-aarch64-linux-gnu) sha256=e9aea2c2b3476fc875dd8a89313a9a2862818519c0186bfb5b56d6f57bb08d98 + sqlite3 (2.10.2-aarch64-linux-musl) sha256=4986fc40cdf21342362b72a941df28e95cfe0e644f3ad2532d948b157c39dbee + sqlite3 (2.10.2-arm-linux-gnu) sha256=762f609ef891463226b472d3df66aea84d5466ff4376d3ccf4a059718c4ce9c9 + sqlite3 (2.10.2-arm-linux-musl) sha256=833623eaf1157b1b85d1c0830e3e8f9beb3bb95a9bec3d252f20557a50e9803a + sqlite3 (2.10.2-arm64-darwin) sha256=5b0d235ea037e6dcd1b8387a19d73be571917db9f93044d35741cf933a21a37d + sqlite3 (2.10.2-x86-linux-gnu) sha256=46a02a29e9ae452824082388be5c24fd26f133b14bdd268610c6aa9a8d924c44 + sqlite3 (2.10.2-x86-linux-musl) sha256=38980cf01eb2e4ac1c0755964d60b3d743ccf00686798a626bab852ff4cd3d1e + sqlite3 (2.10.2-x86_64-darwin) sha256=fd2c67b49d313031af112e172c83ab321681a2b4996bf882eefac50be7bea08f + sqlite3 (2.10.2-x86_64-linux-gnu) sha256=ca92731ab464df9cae503fa1a439a549e2724f6953c8c05a7769b59366e38f15 + sqlite3 (2.10.2-x86_64-linux-musl) sha256=b9f8fc62f3e0eb8966b41de251b492b4c8e9d1b23559beb6e150ad7f8d590941 tilt (2.9.0) sha256=da5735d0280bba96e9a91041bb14aee435ccad5c17b0fa519249ae543d9aa3a5 timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb uri (1.1.2) sha256=89292e98eabbef6248b0a0ed5e7e398e152f83f17560023a6d94a7f492b169fb diff --git a/Rakefile b/Rakefile index 2d30764..bdb521f 100644 --- a/Rakefile +++ b/Rakefile @@ -40,6 +40,20 @@ namespace :hiking do end end +namespace :places do + desc "Build the offline place-search index (data/places/.sqlite) from every already-downloaded " \ + "Geofabrik extract in data/geofabrik_cache, without a full offline build. Countries whose index is " \ + "already newer than their extract are skipped. Usage: rake places:index [MAPTOOL_DATA_DIR=data]" + task :index do + require_relative "lib/maptool/pmtiles_builder" + + data_dir = ENV.fetch("MAPTOOL_DATA_DIR", File.join(__dir__, "data")) + puts "Indexing places from #{data_dir}/geofabrik_cache..." + countries = Maptool::PmtilesBuilder.index_cached_places(data_dir) + puts "Place index available for: #{countries.empty? ? "(none)" : countries.join(", ")}" + end +end + namespace :gpx do desc "Backfill properties.id on Note-category features saved before edit/delete (and its id targeting) existed" task :backfill_note_ids do diff --git a/TODO.adoc b/TODO.adoc index 2336a11..1c01812 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -61,13 +61,14 @@ independence from connectivity. == 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] 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] Offline vector data — every named OSM object in each country's Geofabrik `.osm.pbf` (`osmium tags-filter nwr/name` + `osmium export -f geojsonseq`) into a SQLite FTS5 index, `data/places/.sqlite` (`lib/maptool/places.rb`), built as the last offline-build step ("indexing places") and cached by mtime like hiking trails. Prefix + diacritics-insensitive matching, street segments merged per ~2 km cell ** [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`) +** [x] Kiwix as a source — full-text search of the ZIM (`Kiwix.search`), each hit's coordinates read from its page like the Wikipedia layer does; clicking opens the article (and jumps to it when it has coordinates) +** [x] Nearest first — every result carries its distance from the map center and the list is sorted by it across all sources; settlements count as closer (city x0.01 … suburb x0.3, `Places::DISTANCE_WEIGHT`) so a town's name still finds the town. Nominatim gets the visible area as a (non-restricting) `viewbox` == Nice to have (later) diff --git a/app.rb b/app.rb index a1e3c7c..08bf27f 100644 --- a/app.rb +++ b/app.rb @@ -433,13 +433,16 @@ module Maptool send_file path, type: "application/geo+json" 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. + # The search box's local half (public/js/search.js) — saved layers + # (shown or not), offline hiking trails, the offline place index and + # Kiwix; lat/lng (the map center) puts nearer places first. 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) + center = params[:lat] && params[:lng] ? [params[:lat].to_f, params[:lng].to_f] : nil + json results: Search.query(params[:q], gpx_store: GPX_STORE, data_dir: DATA_DIR, sources: sources, + center: center, kiwix_url: KIWIX_URL) end # Pinged once per page load (public/js/map.js) — url is a same-origin diff --git a/lib/maptool/kiwix.rb b/lib/maptool/kiwix.rb index 335cc57..f23ccc4 100644 --- a/lib/maptool/kiwix.rb +++ b/lib/maptool/kiwix.rb @@ -81,6 +81,23 @@ module Maptool { "type" => "FeatureCollection", "features" => features } end + # Full-text search of the ZIM for the search box (Search's "kiwix" + # source): [{ title:, link:, position: [lng, lat] or nil }]. position + # comes from each article's own page, same as .nearby above — hence a + # small default limit; an article with no coordinates is still a + # result, it just opens without a place on the map to jump to. + def self.search(base_url, text, limit: 10, open_timeout: 2, read_timeout: 10) + return [] if base_url.to_s.strip.empty? || text.to_s.strip.empty? + + query = URI.encode_www_form(pattern: text, pageLength: limit, format: "xml") + response = proxy(base_url, "/kiwix/search", query, open_timeout: open_timeout, read_timeout: read_timeout) + return [] unless response&.code == "200" + + parse_search_results(response.body).map do |result| + result.merge(position: position(base_url, result[:link], open_timeout, read_timeout)) + end + end + def self.empty_collection { "type" => "FeatureCollection", "features" => [] } end @@ -104,20 +121,25 @@ module Maptool # already-*decoded* splat, see its own comment above) doesn't double- # encode the "%" and 404 the request. def self.point_feature(base_url, result, open_timeout, read_timeout) - response = proxy(base_url, URI::RFC2396_PARSER.unescape(result[:link]), nil, open_timeout: open_timeout, read_timeout: read_timeout) - return nil unless response&.code == "200" - - match = response.body.match(GEO_POSITION_PATTERN) - return nil unless match + coordinates = position(base_url, result[:link], open_timeout, read_timeout) + return nil unless coordinates { "type" => "Feature", "properties" => { "name" => result[:title], "link" => result[:link] }, - "geometry" => { "type" => "Point", "coordinates" => [match[2].to_f, match[1].to_f] }, + "geometry" => { "type" => "Point", "coordinates" => coordinates }, } end private_class_method :point_feature + # [lng, lat] from the article page's geo.position meta tag, or nil. + def self.position(base_url, link, open_timeout, read_timeout) + response = proxy(base_url, URI::RFC2396_PARSER.unescape(link), nil, open_timeout: open_timeout, read_timeout: read_timeout) + match = response&.code == "200" && response.body.match(GEO_POSITION_PATTERN) + match ? [match[2].to_f, match[1].to_f] : nil + end + private_class_method :position + def self.haversine_km(lat1, lng1, lat2, lng2) earth_radius_km = 6371.0 dlat = (lat2 - lat1) * Math::PI / 180 diff --git a/lib/maptool/places.rb b/lib/maptool/places.rb new file mode 100644 index 0000000..22060a5 --- /dev/null +++ b/lib/maptool/places.rb @@ -0,0 +1,138 @@ +require "json" +require "open3" +require "set" +require "sqlite3" +require "tmpdir" + +module Maptool + # Offline place-name search: every named OSM object in a country's + # Geofabrik .osm.pbf (towns, streets, peaks, POIs, ...) in a SQLite FTS5 + # index, one data/places/.sqlite per country — built during the + # offline build next to hiking trails, from the same already-downloaded + # PBF. offline.pmtiles itself is tiles, not searchable by name. + module Places + class ExtractError < StandardError; end + + # Most to least important; the first key a feature carries decides + # its kind and rank. Within "place", the value refines it further. + KIND_KEYS = %w[place natural tourism amenity historic leisure shop aeroway railway highway waterway + boundary landuse man_made office building].freeze + PLACE_RANK = { "city" => 0, "town" => 1, "village" => 2, "suburb" => 3, "hamlet" => 3 }.freeze + # How much closer a settlement counts as when results are ordered by + # distance from the map center (Search) — so typing a city's name finds + # the city, not a same-named street around the corner, while a shop or + # a street is purely nearest-first. Keyed by importance (PLACE_RANK). + # ponytail: fixed multipliers, tune if real searches rank oddly. + DISTANCE_WEIGHT = Hash.new(1.0).merge(0 => 0.01, 1 => 0.03, 2 => 0.1, 3 => 0.3).freeze + KEY_RANK = Hash.new(7).merge("place" => 4, "natural" => 5, "tourism" => 5, "amenity" => 5, "historic" => 5, + "leisure" => 5, "shop" => 5, "aeroway" => 5, "railway" => 6, "highway" => 6, "waterway" => 6) + + def self.osmium_bin + ENV.fetch("OSMIUM_BIN", "osmium") + end + + def self.extract(pbf_path, db_path) + Dir.mktmpdir("maptool-places") do |dir| + named = File.join(dir, "named.osm.pbf") + run!(osmium_bin, "tags-filter", pbf_path, "nwr/name", "-o", named) + seq = File.join(dir, "named.geojsonseq") + run!(osmium_bin, "export", named, "-f", "geojsonseq", "-x", "print_record_separator=false", "-o", seq) + File.open(seq) { |io| import(io, db_path) } + end + end + + # Pure apart from SQLite — one GeoJSON feature per line in, index out — + # so it's testable without osmium installed (same split as + # HikingTrails.extract/parse_opl). + def self.import(io, db_path) + File.delete(db_path) if File.exist?(db_path) + db = SQLite3::Database.new(db_path) + db.execute(<<~SQL) + CREATE VIRTUAL TABLE places USING fts5( + name, kind UNINDEXED, importance UNINDEXED, lon UNINDEXED, lat UNINDEXED, bbox UNINDEXED, + tokenize = 'unicode61 remove_diacritics 2', prefix = '2 3' + ) + SQL + # A street is many way segments, all named the same — one row per + # name/kind per ~2 km cell keeps a town's "Hlavná" from filling the + # whole result list. ponytail: grid dedupe, a long road still shows + # once per cell it crosses. + seen = Set.new + insert = db.prepare("INSERT INTO places VALUES (?, ?, ?, ?, ?, ?)") + db.transaction do + io.each_line do |line| + row = row(JSON.parse(line)) + next unless row && seen.add?([row[0], row[1], (row[4] * 50).round, (row[3] * 50).round]) + + insert.execute(row) + rescue JSON::ParserError + next + end + end + insert.close + db.execute("INSERT INTO places(places) VALUES ('optimize')") + db.close + end + + # [name, kind, importance, lon, lat, bbox json] or nil + def self.row(feature) + tags = feature["properties"] || {} + name = tags["name"].to_s.strip + geometry = feature["geometry"] || {} + coords = geometry["coordinates"] + return nil if name.empty? || !coords.is_a?(Array) || coords.empty? + + points = positions(coords) + lngs, lats = points.map { |p| p.first(2) }.transpose + bbox = [lngs.min, lats.min, lngs.max, lats.max] + # A label point that's actually on the thing: the middle vertex of a + # line (a curved street's bbox center can be off the street), the + # bbox center of an area. + lon, lat = geometry["type"] == "LineString" ? points[points.size / 2] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] + + key = KIND_KEYS.find { |k| tags[k] } + value = tags[key].to_s + kind = if key.nil? then "" + elsif key == "highway" && geometry["type"] != "Point" then "street" + else value.tr("_", " ") + end + importance = key == "place" ? PLACE_RANK.fetch(value, KEY_RANK["place"]) : KEY_RANK[key] + [name, kind, importance, lon, lat, JSON.generate(bbox)] + end + + def self.positions(coords) + coords.first.is_a?(Numeric) ? [coords] : coords.flat_map { |c| positions(c) } + end + + # words: already lowercased/diacritics-stripped (Search.normalize); + # every one must match as a word prefix. Nearest to `center` ([lat, + # lng], the map's) first, settlements weighted closer (DISTANCE_WEIGHT); + # with no center, most important kinds first. + def self.search(db_path, words, center: nil, limit: 50) + match = words.map { |word| %("#{word.gsub('"', '""')}"*) }.join(" ") + order, params = + if center + weight = DISTANCE_WEIGHT.map { |importance, w| "WHEN #{importance} THEN #{w * w}" }.join(" ") + ["((lat - ?) * (lat - ?) + (lon - ?) * (lon - ?)) * CASE importance #{weight} ELSE 1 END", + [center[0], center[0], center[1], center[1]]] + else + ["importance, rank", []] + end + db = SQLite3::Database.new(db_path, readonly: true) + db.execute("SELECT name, kind, bbox, importance FROM places WHERE places MATCH ? ORDER BY #{order} LIMIT ?", [match, *params, limit]) + .map { |name, kind, bbox, importance| { name: name, kind: kind, bbox: JSON.parse(bbox), importance: importance } } + rescue SQLite3::Exception + [] + ensure + db&.close + end + + def self.run!(*args) + stdout, stderr, status = Open3.capture3(*args) + raise ExtractError, "#{args.first} exited with status #{status.exitstatus}: #{[stdout, stderr].map(&:strip).reject(&:empty?).join("\n")}" unless status.success? + rescue Errno::ENOENT, Errno::EACCES => e + raise ExtractError, "could not run '#{args.first}' (#{e.message}) — is osmium-tool installed and on PATH?" + end + private_class_method :run! + end +end diff --git a/lib/maptool/pmtiles_builder.rb b/lib/maptool/pmtiles_builder.rb index 4b0c286..bdc1bad 100644 --- a/lib/maptool/pmtiles_builder.rb +++ b/lib/maptool/pmtiles_builder.rb @@ -6,6 +6,7 @@ require "tmpdir" require "fileutils" require "etc" require_relative "hiking_trails" +require_relative "places" module Maptool # Regenerates data/offline.pmtiles and data/terrain.pmtiles for the @@ -367,6 +368,8 @@ module Maptool report_step.call("extracting hiking trails") extract_hiking_trails(sources, data_dir) + report_step.call("indexing places") + extract_places(sources, data_dir) { log: planetiler_log } ensure FileUtils.remove_entry(scratch_dir) if scratch_dir && Dir.exist?(scratch_dir) @@ -409,6 +412,50 @@ module Maptool end private_class_method :extract_hiking_trails + # The place-name search index (Places), one SQLite file per country — + # same per-country, cached-by-mtime, best-effort story as hiking trails + # above, from the same PBFs. + def self.extract_places(sources, data_dir) + FileUtils.mkdir_p(places_dir(data_dir)) + sources.each do |source| + out_path = places_country_path(data_dir, source["code"]) + next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) + + tmp_path = "#{out_path}.tmp" + begin + Places.extract(source["path"], tmp_path) + File.rename(tmp_path, out_path) + rescue Places::ExtractError, SQLite3::Exception => e + File.delete(tmp_path) if File.exist?(tmp_path) + warn "places index failed for #{source["code"]}, skipping: #{e.message}" + end + end + end + private_class_method :extract_places + + # Same, for every already-downloaded country, without a whole offline + # build — `rake places:index`, e.g. right after this index was added + # and offline.pmtiles itself was already up to date. + def self.index_cached_places(data_dir) + sources = cached_extracts(data_dir).map do |extract| + extract.merge("path" => File.join(geofabrik_cache_dir(data_dir), "#{extract["code"]}.osm.pbf")) + end + extract_places(sources, data_dir) + places_countries(data_dir) + end + + def self.places_dir(data_dir) + File.join(data_dir, "places") + end + + def self.places_country_path(data_dir, code) + File.join(places_dir(data_dir), "#{code}.sqlite") + end + + def self.places_countries(data_dir) + Dir.glob(File.join(places_dir(data_dir), "*.sqlite")).map { |path| File.basename(path, ".sqlite") }.sort + end + def self.hiking_trails_dir(data_dir) File.join(data_dir, "hiking_trails") end @@ -573,6 +620,7 @@ module Maptool File.delete(File.join(data_dir, "offline.pmtiles")) if File.exist?(File.join(data_dir, "offline.pmtiles")) File.delete(offline_meta_path(data_dir)) if File.exist?(offline_meta_path(data_dir)) FileUtils.remove_entry(hiking_trails_dir(data_dir)) if Dir.exist?(hiking_trails_dir(data_dir)) + FileUtils.remove_entry(places_dir(data_dir)) if Dir.exist?(places_dir(data_dir)) cache_dir = geofabrik_cache_dir(data_dir) FileUtils.remove_entry(cache_dir) if Dir.exist?(cache_dir) end diff --git a/lib/maptool/search.rb b/lib/maptool/search.rb index a9dfe3a..6984923 100644 --- a/lib/maptool/search.rb +++ b/lib/maptool/search.rb @@ -1,58 +1,100 @@ require "json" require_relative "gpx" require_relative "fit" +require_relative "kiwix" +require_relative "places" 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. + # Server-side half of the search box (public/js/search.js): every saved + # layer (shown on the map or not), offline hiking trails, the offline + # place-name index (Places) and the offline Wikipedia (Kiwix). 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. + # A source is a name -> lambda(words, ctx) returning results, each capped + # at LIMIT on its own so one busy source can't crowd out the rest — the + # LIMIT nearest to the map center when there is one: every result then + # carries distance_km (shown) and score (sorted by; distance, except a + # settlement counts as closer, see Places::DISTANCE_WEIGHT). ctx + # carries :text, :gpx_store, :data_dir, :center ([lat, lng] or nil) and + # :kiwix_url. `ref` in a result is what the browser needs to act on it + # (switch a layer on, open an article). module Search LIMIT = 50 + KIWIX_LIMIT = 10 # each result costs kiwix-serve one more page fetch, see Kiwix.search 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) }] + "layers" => lambda do |words, ctx| + store = ctx[:gpx_store] + scan(words, "layers", files(store.tree).map { |path| [path, path, store.resolve_file(path), -> { store.geojson(path) }] }) + end, + "hiking_trails" => lambda do |words, ctx| + countries = PmtilesBuilder.hiking_trails_countries(ctx[:data_dir]).map do |code| + path = PmtilesBuilder.hiking_trails_country_path(ctx[:data_dir], code) + ["Hiking trails #{code}", code, path, -> { File.read(path) }] + end + scan(words, "hiking_trails", countries) + end, + "places" => lambda do |words, ctx| + PmtilesBuilder.places_countries(ctx[:data_dir]).flat_map do |code| + Places.search(PmtilesBuilder.places_country_path(ctx[:data_dir], code), words, center: ctx[:center], limit: LIMIT).map do |place| + label = [place[:kind], "Offline map #{code}"].reject(&:empty?).join(" · ") + place.merge(source: "places", source_label: label, ref: code) + end 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) }] + "kiwix" => lambda do |_words, ctx| + Kiwix.search(ctx[:kiwix_url], ctx[:text], limit: KIWIX_LIMIT).map do |article| + { name: article[:title], bbox: article[:position] && (article[:position] * 2), + source: "kiwix", source_label: "Wikipedia", ref: article[:link] } 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. + # ponytail: unbounded in-memory cache, fine for a handful of layer files. @cache = {} - def self.query(text, gpx_store:, data_dir:, sources: SOURCES.keys) + def self.query(text, gpx_store:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "") 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) } + ctx = { text: text.to_s.strip, gpx_store: gpx_store, data_dir: data_dir, center: center, kiwix_url: kiwix_url.to_s } + (sources & SOURCES.keys).flat_map do |source| + results = SOURCES[source].call(words, ctx) + results = nearest_first(results, center) if center + results.first(LIMIT).map { |result| result.except(:importance) } + end + end - results << entry.except(:text).merge(source: source, source_label: label, ref: ref) - return results if results.size >= LIMIT - end + # Results without a position (a Wikipedia article with no coordinates) + # go last. + def self.nearest_first(results, center) + results.each do |result| + next unless (bbox = result[:bbox]) + + result[:distance_km] = haversine_km(center, [(bbox[1] + bbox[3]) / 2.0, (bbox[0] + bbox[2]) / 2.0]).round(1) + result[:score] = result[:distance_km] * Places::DISTANCE_WEIGHT[result[:importance]] + end + results.sort_by { |result| result[:score] || Float::INFINITY } + end + + def self.haversine_km((lat1, lng1), (lat2, lng2)) + rad = Math::PI / 180 + a = (Math.sin((lat2 - lat1) * rad / 2)**2) + (Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * (Math.sin((lng2 - lng1) * rad / 2)**2)) + 2 * 6371.0 * Math.asin(Math.sqrt(a)) + end + + # files: [label, ref, file on disk, reader] — every matching feature + # of each, found in memory (all of them, so query can pick the nearest). + def self.scan(words, source, files) + files.flat_map do |label, ref, disk_path, read| + entries(disk_path, read).filter_map do |entry| + entry.except(:text).merge(source: source, source_label: label, ref: ref) if words.all? { |word| entry[:text].include?(word) } end end - results end # Lowercased, diacritics stripped — "kosice" finds "Košice". @@ -81,7 +123,7 @@ module Maptool 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 + lngs, lats = Places.positions(coords).map { |p| p.first(2) }.transpose { name: name, kind: props["kind"] || feature.dig("geometry", "type"), @@ -90,10 +132,6 @@ module Maptool } 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"]] diff --git a/public/js/search.js b/public/js/search.js index 6942cdb..ca05a57 100644 --- a/public/js/search.js +++ b/public/js/search.js @@ -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 = `
  • Searching…
  • `; - 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 = `
  • No results
  • `; - return; - } - this._resultsEl.innerHTML = results - .map((result, i) => - result.status - ? `
  • ${escapeHtml(result.status)}
  • ` - : `
  • - ${escapeHtml(result.name)} - ${escapeHtml(result.where)} -
  • `, - ) - .join(""); + const tail = pending + ? `
  • Searching…
  • ` + : results.length === 0 + ? `
  • No results
  • ` + : ""; + this._resultsEl.innerHTML = + results + .map((result, i) => + result.status + ? `
  • ${escapeHtml(result.status)}
  • ` + : `
  • + ${escapeHtml(result.name)} + ${escapeHtml( + [result.where, result.distanceKm != null && formatKm(result.distanceKm)].filter(Boolean).join(" · "), + )} +
  • `, + ) + .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); }); }); } diff --git a/test/test_kiwix.rb b/test/test_kiwix.rb index 0b7bfb4..cfe6167 100644 --- a/test/test_kiwix.rb +++ b/test/test_kiwix.rb @@ -124,4 +124,44 @@ class KiwixTest < Minitest::Test geojson = Maptool::Kiwix.nearby("http://127.0.0.1:1", [48.0, 17.0, 48.2, 17.3], open_timeout: 1) assert_equal({ "type" => "FeatureCollection", "features" => [] }, geojson) end + + def test_search_returns_every_hit_with_its_position_when_it_has_one + server = TCPServer.new("127.0.0.1", 0) + port = server.addr[1] + search_line = nil + thread = Thread.new do + 3.times do + client = server.accept + request_line = client.gets + body = + if request_line.include?("/kiwix/search") + search_line = request_line + <<~XML + + Devín/kiwix/content/wikipedia/Dev%C3%ADn + Pivo/kiwix/content/wikipedia/Pivo + + XML + elsif request_line.include?("/Dev") + '' + else + "no coordinates here" + end + client.print("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}") + client.close + end + end + + results = Maptool::Kiwix.search("http://127.0.0.1:#{port}", "hrad devín", limit: 5) + thread.join + server.close + + assert_includes search_line, "pattern=hrad+dev%C3%ADn" + assert_equal [["Devín", [16.98, 48.17]], ["Pivo", nil]], results.map { |r| r.values_at(:title, :position) } + end + + def test_search_is_empty_without_a_kiwix_url_or_query + assert_empty Maptool::Kiwix.search("", "x") + assert_empty Maptool::Kiwix.search("http://127.0.0.1:1", " ") + end end diff --git a/test/test_places.rb b/test/test_places.rb new file mode 100644 index 0000000..27ae609 --- /dev/null +++ b/test/test_places.rb @@ -0,0 +1,68 @@ +require_relative "test_helper" +require "maptool/places" +require "stringio" + +# No real osmium — import is fed canned `osmium export -f geojsonseq` +# lines (same split HikingTrailsTest makes around parse_opl). +class PlacesTest < Minitest::Test + def setup + @dir = Dir.mktmpdir + @db = File.join(@dir, "SK.sqlite") + lines = [ + feature("Point", [17.107, 48.148], "name" => "Bratislava", "place" => "city"), + feature("Point", [17.20, 48.30], "name" => "Bratislavská reštaurácia", "amenity" => "restaurant"), + feature("Point", [21.26, 48.72], "name" => "Hlavná", "place" => "square"), + # two segments of one street a few hundred metres apart -> one row + feature("LineString", [[17.10, 48.14], [17.101, 48.141], [17.102, 48.142]], "name" => "Hlavná", "highway" => "residential"), + feature("LineString", [[17.103, 48.143], [17.104, 48.144]], "name" => "Hlavná", "highway" => "residential"), + feature("Polygon", [[[19.0, 48.0], [19.2, 48.0], [19.2, 48.2], [19.0, 48.0]]], "name" => "Košické jazero", "natural" => "water"), + feature("Point", [18.0, 48.0], "highway" => "crossing"), # no name -> skipped + "not json", + ] + Maptool::Places.import(StringIO.new(lines.join("\n")), @db) + end + + def teardown + FileUtils.remove_entry(@dir) + end + + def test_prefix_and_diacritics_insensitive_with_more_important_kinds_first + results = search("bratisl") + assert_equal ["Bratislava", "Bratislavská reštaurácia"], results.map { |r| r[:name] } + assert_equal ["city", "restaurant"], results.map { |r| r[:kind] } + + assert_equal ["Košické jazero"], search("kosicke").map { |r| r[:name] } + assert_equal [19.0, 48.0, 19.2, 48.2], search("jazero").first[:bbox] + end + + def test_street_segments_are_merged_and_nearer_matches_come_first + assert_equal ["square", "street"], search("hlavna", center: [48.7, 21.2]).map { |r| r[:kind] } + assert_equal ["street", "square"], search("hlavna", center: [48.14, 17.1]).map { |r| r[:kind] } + street = search("hlavna").find { |r| r[:kind] == "street" } + assert_equal [17.10, 48.14, 17.102, 48.142], street[:bbox] + assert_equal 2, search("hlavna").size + end + + def test_a_city_counts_as_closer_than_it_is_but_a_shop_next_door_still_wins + # restaurant ~18 km from Bratislava's center point; from right next to + # the restaurant it wins, from halfway the city does (weighted x0.01) + assert_equal "Bratislavská reštaurácia", search("bratisl", center: [48.30, 17.20]).first[:name] + assert_equal "Bratislava", search("bratisl", center: [48.22, 17.15]).first[:name] + end + + def test_all_words_must_match_and_unnamed_or_broken_lines_are_skipped + assert_equal ["Bratislavská reštaurácia"], search("bratislavska restau").map { |r| r[:name] } + assert_empty search("crossing") + end + + private + + def search(text, **opts) + words = text.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").downcase.split + Maptool::Places.search(@db, words, **opts).map { |r| r.except(:rank) } + end + + def feature(type, coordinates, tags) + JSON.generate("type" => "Feature", "geometry" => { "type" => type, "coordinates" => coordinates }, "properties" => tags) + end +end diff --git a/test/test_pmtiles_builder.rb b/test/test_pmtiles_builder.rb index 2de7510..bd4c822 100644 --- a/test/test_pmtiles_builder.rb +++ b/test/test_pmtiles_builder.rb @@ -209,7 +209,7 @@ class PmtilesBuilderTest < Minitest::Test assert_path_exists File.join(@data_dir, "offline.pmtiles") refute_path_exists File.join(@data_dir, "offline.tmp.pmtiles") assert_equal "done", Maptool::PmtilesBuilder.offline_status[:state] - assert_equal ["planetiler --osm-path", "osmium tags-filter", "osmium add-locations-to-ways", "osmium cat"], log_lines + assert_equal ["planetiler --osm-path", "osmium tags-filter", "osmium add-locations-to-ways", "osmium cat", "osmium tags-filter", "osmium export"], log_lines assert_equal( { "sources" => [{ "code" => "SK", "slug" => "europe/slovakia", "last_modified" => "Wed, 10 Sep 2026 08:00:01 GMT" }] }, Maptool::PmtilesBuilder.offline_meta(@data_dir), @@ -225,7 +225,7 @@ class PmtilesBuilderTest < Minitest::Test failed, done = Maptool::PmtilesBuilder.build_history(@data_dir) assert_equal ["error", "done"], [failed["state"], done["state"]] assert_equal ["offline", ["SK"]], done.values_at("kind", "regions") - assert_equal ["fetching SK (1/1)", "tiling with planetiler", "extracting hiking trails"], done["timings"].map { |t| t["step"] } + assert_equal ["fetching SK (1/1)", "tiling with planetiler", "extracting hiking trails", "indexing places"], done["timings"].map { |t| t["step"] } assert(done["timings"].all? { |t| t["seconds"] >= 0 }) assert done.key?("log") assert_match(/boom/, failed["message"]) @@ -261,12 +261,14 @@ class PmtilesBuilderTest < Minitest::Test # since the first build), so only AT's hiking trails get (re-)extracted # — SK.osm.pbf itself is also skipped by cached_extract's own # Last-Modified check, "osmium merge" runs regardless since two - # countries are now selected. + # countries are now selected. Same for the places index. assert_equal( - ["osmium merge", "planetiler --osm-path", "osmium tags-filter", "osmium add-locations-to-ways", "osmium cat"], + ["osmium merge", "planetiler --osm-path", "osmium tags-filter", "osmium add-locations-to-ways", "osmium cat", + "osmium tags-filter", "osmium export"], log_lines, ) assert_equal %w[AT SK], Maptool::PmtilesBuilder.hiking_trails_countries(@data_dir) + assert_equal %w[AT SK], Maptool::PmtilesBuilder.places_countries(@data_dir) end # The actual reasoning: hiking trails are a bonus overlay bolted onto the @@ -297,6 +299,8 @@ class PmtilesBuilderTest < Minitest::Test "osmium merge", "planetiler --osm-path", "osmium tags-filter", "osmium add-locations-to-ways", "osmium cat", # SK's own hiking-trails extraction "osmium tags-filter", "osmium add-locations-to-ways", "osmium cat", # AT's own + "osmium tags-filter", "osmium export", # SK's places index + "osmium tags-filter", "osmium export", # AT's ], log_lines, ) diff --git a/test/test_search.rb b/test/test_search.rb index aff07a9..913125b 100644 --- a/test/test_search.rb +++ b/test/test_search.rb @@ -35,6 +35,17 @@ class SearchTest < Minitest::Test assert_equal [17.0, 48.0, 18.0, 49.0], track[:bbox] end + def test_with_a_map_center_results_come_nearest_first_with_their_distance + camps = { "type" => "FeatureCollection", "features" => [ + point("Kemp far", 21.0, 48.7), point("Kemp near", 17.1, 48.15), + ] } + @store.save(folder: "", filename: "more.geojson", io: StringIO.new(JSON.generate(camps))) + + results = search("kemp", center: [48.14, 17.10]) + assert_equal ["Kemp near", "Kemp far", "Kemp Košice"], results.map { |r| r[:name] } + assert_in_delta 1.3, results.first[:distance_km], 0.2 + end + def test_source_filter_and_blank_query assert_empty search("snp", sources: ["layers"]) assert_empty search(" ")