Search the offline map and Wikipedia, nearest results first
CI / check (push) Successful in 26s
CI / deploy (push) Successful in 33s

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:
randy committed 2026-11-12 12:13:13 +01:00
1 parent ba9c40ac3d
commit 3f973a26d7
14 files changed
+549 -90

No files matched your search

+28 -6
View File
@@ -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
+138
View File
@@ -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/<CODE>.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
+48
View File
@@ -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
+71 -33
View File
@@ -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"]]