diff --git a/lib/maptool/hiking_trails.rb b/lib/maptool/hiking_trails.rb index 13b5d22..a03335f 100644 --- a/lib/maptool/hiking_trails.rb +++ b/lib/maptool/hiking_trails.rb @@ -37,6 +37,22 @@ module Maptool class ExtractError < StandardError; end ROUTE_TAGS = %w[name description ref colour network operator].freeze + # The OSM route types kept, each as a `kind` the map and the elevation + # profile filter by (an educational trail is a hiking route too, told + # apart below). + KINDS = { "hiking" => "hiking", "foot" => "hiking", "bicycle" => "bicycle", "mtb" => "bicycle", "ski" => "ski" }.freeze + # Bumped when the extract's shape changes, so PmtilesBuilder redoes a + # country's file even though its .osm.pbf hasn't changed. + VERSION = 2 + # ponytail: OSM has no single educational-trail tag in practice; the + # name in the languages here, `educational=yes`, or the SK/CZ marking + # (a green diagonal stripe, osmc:symbol "…green_diagonal"). + EDUCATIONAL = /náučn|naučn|lehrpfad|themenweg|dydaktycz|edukacyj|przyrodnicz|tanösvény|nature trail|sentiero natura|sendero (de )?interpretaci/i + + # Current extract format? (see VERSION; the version is the first key). + def self.current?(path) + File.open(path) { |f| f.read(32) }.to_s.start_with?(%({"version":#{VERSION},)) + end def self.osmium_bin ENV.fetch("OSMIUM_BIN", "osmium") @@ -51,7 +67,7 @@ module Maptool def self.extract(pbf_path) Dir.mktmpdir("maptool-hiking-trails") do |dir| filtered = File.join(dir, "hiking.osm.pbf") - run!(osmium_bin, "tags-filter", pbf_path, "r/route=hiking", "-o", filtered) + run!(osmium_bin, "tags-filter", pbf_path, "r/route=#{KINDS.keys.join(',')}", "-o", filtered) located = File.join(dir, "hiking-located.osm.pbf") run!(osmium_bin, "add-locations-to-ways", filtered, "-o", located) @@ -81,12 +97,12 @@ module Maptool ways[head[1..].to_i] = way_coordinates(fields) when "r" tags = tags_field(fields) - relations << { id: head[1..].to_i, tags: tags, members: members_field(fields) } if tags["route"] == "hiking" + relations << { id: head[1..].to_i, tags: tags, members: members_field(fields) } if KINDS.key?(tags["route"]) end end features = relations.filter_map { |relation| relation_feature(relation, ways) } - { "type" => "FeatureCollection", "features" => features } + { "version" => VERSION, "type" => "FeatureCollection", "features" => features } end def self.relation_feature(relation, ways) @@ -109,6 +125,7 @@ module Maptool "name" => tags["name"] || tags["description"], "distance_meters" => distance.round(1), "oneway_lines" => oneway.empty? ? nil : oneway, + "kind" => kind(tags), } ROUTE_TAGS.each { |key| properties[key] ||= tags[key] } @@ -124,6 +141,14 @@ module Maptool end private_class_method :relation_feature + def self.kind(tags) + kind = KINDS.fetch(tags["route"], "hiking") + educational = tags["educational"] == "yes" || tags["osmc:symbol"].to_s.include?("green_diagonal") || + [tags["name"], tags["description"]].any? { |t| t.to_s.match?(EDUCATIONAL) } + kind == "hiking" && educational ? "educational" : kind + end + private_class_method :kind + def self.round_coordinates(lines) lines.map { |coords| coords.map { |lon, lat| [lon.round(5), lat.round(5)] } } end diff --git a/lib/maptool/pmtiles_builder.rb b/lib/maptool/pmtiles_builder.rb index f632ec3..de6dd23 100644 --- a/lib/maptool/pmtiles_builder.rb +++ b/lib/maptool/pmtiles_builder.rb @@ -394,7 +394,7 @@ module Maptool FileUtils.mkdir_p(hiking_trails_dir(data_dir)) sources.each do |source| out_path = hiking_trails_country_path(data_dir, source["code"]) - next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) + next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) && HikingTrails.current?(out_path) tmp_path = "#{out_path}.tmp" begin diff --git a/public/css/style.css b/public/css/style.css index 59a600f..5a00a2c 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -2202,6 +2202,12 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr padding: 0; } +.hiking-trail-kinds { + margin-bottom: 8px; + padding-bottom: 8px; + border-bottom: 1px solid #eee; +} + .hiking-trail-countries__item label { display: flex; align-items: center; diff --git a/public/js/hiking_trails.js b/public/js/hiking_trails.js index a87a9d9..2acd133 100644 --- a/public/js/hiking_trails.js +++ b/public/js/hiking_trails.js @@ -86,25 +86,32 @@ function normalizedTrailColor(raw) { return /^#[0-9a-fA-F]{3,8}$/.test(trimmed) ? trimmed : DEFAULT_TRAIL_COLOR; } -// The offline trails currently drawn (every ticked country), for +// Route kinds (Maptool::HikingTrails#kind; a file extracted before kinds +// existed has none: hiking), the ones the map shows picked by the viewer. +const KIND_LABELS = { hiking: "Hiking", educational: "Educational", bicycle: "Cycling", ski: "Ski" }; +const DEFAULT_KINDS = ["hiking", "educational"]; +const kindOf = (properties) => properties.kind || "hiking"; + +// The offline trails of every ticked country (all kinds), for // trailColorsAlong. let shownTrails = []; const TRAIL_MATCH_M = 20; // GPS/OSM offset a point may be off its trail const GRID_DEG = 0.001; // ~100 m cells -// For each {lon, lat} point, the colors of the drawn trails within +// For each {lon, lat} point, the colors of the trails of `kinds` within // TRAIL_MATCH_M of it ([] off-trail), for the elevation profile's trail -// band; null when no point is on a drawn trail. Only what the hiking -// trails overlay shows, so ticking a country there is what turns it on. -export function trailColorsAlong(points) { - if (!shownTrails.length || !points.length) return null; +// band; null when no point is on one. Only the countries the hiking +// trails overlay has loaded, so ticking a country there turns it on. +export function trailColorsAlong(points, kinds) { + const trails = shownTrails.filter(({ properties }) => kinds.includes(kindOf(properties))); + if (!trails.length || !points.length) return null; const lons = points.map((p) => p.lon); const lats = points.map((p) => p.lat); const [w, e] = [Math.min(...lons) - GRID_DEG, Math.max(...lons) + GRID_DEG]; const [s, n] = [Math.min(...lats) - GRID_DEG, Math.max(...lats) + GRID_DEG]; // Only segments near the points, bucketed by cell. const grid = new Map(); - for (const { geometry, properties } of shownTrails) { + for (const { geometry, properties } of trails) { const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates; for (const line of lines) { for (let i = 1; i < line.length; i++) { @@ -172,6 +179,10 @@ export class HikingTrailsControl { this._lanes = null; // the current LaneLayer, null when no country is shown this._bboxes = {}; // code -> [w, s, e, n] this._inView = false; // main checkbox, offline: the countries in view + this._kinds = DEFAULT_KINDS; + try { + this._kinds = JSON.parse(localStorage.getItem("hikingTrailKinds")) || DEFAULT_KINDS; + } catch {} // Each country entered while the main checkbox is on joins in. // ponytail: a country left behind stays loaded until unticked. @@ -206,13 +217,15 @@ export class HikingTrailsControl {
`; this._checkbox = li.querySelector(".overlays-panel__toggle"); this._nameButton = li.querySelector(".overlays-panel__name"); this._details = li.querySelector(".overlays-panel__details"); - this._countryList = li.querySelector(".hiking-trail-countries"); + this._kindList = li.querySelector(".hiking-trail-kinds"); + this._countryList = li.querySelector(".hiking-trail-countries:not(.hiking-trail-kinds)"); this._checkbox.addEventListener("change", (event) => { if (this._offlineCountries.length) this._toggleInView(event.target.checked); @@ -244,6 +257,18 @@ export class HikingTrailsControl { this._checkbox.checked = false; this._checkbox.title = `Countries in view, from zoom ${LANES_MIN_ZOOM} — click the name to pick some`; + this._kindList.innerHTML = Object.entries(KIND_LABELS) + .map(([kind, label]) => ``) + .join(""); + this._kindList.addEventListener("change", () => { + this._kinds = [...this._kindList.querySelectorAll("input:checked")].map((input) => input.value); + try { + localStorage.setItem("hikingTrailKinds", JSON.stringify(this._kinds)); + } catch {} + this._builtArea = null; + if (this._selectedCountries.size > 0) this._rebuildLanes(); + }); + this._countryList.innerHTML = countries .map( (code) => ` @@ -354,7 +379,7 @@ export class HikingTrailsControl { const [dx, dy] = [view.getEast() - view.getWest(), view.getNorth() - view.getSouth()]; const area = [view.getWest() - dx / 2, view.getSouth() - dy / 2, view.getEast() + dx / 2, view.getNorth() + dy / 2]; this._builtArea = area; - features = all.flatMap((feature) => clipToArea(feature, area)); + features = all.filter(({ properties }) => this._kinds.includes(kindOf(properties))).flatMap((feature) => clipToArea(feature, area)); } let graph = null; if (features.length > 0) { diff --git a/public/js/track_profile.js b/public/js/track_profile.js index 6b4a188..4566c5f 100644 --- a/public/js/track_profile.js +++ b/public/js/track_profile.js @@ -260,7 +260,11 @@ export class TrackProfilePanel { // track follows (several stacked where trails share the path), blank off // trail. Point i's colors span from it to the next point. _renderTrailBand() { - const colors = trailColorsAlong(this._profile); + // The trails the activity uses: a ride the cycling routes, skiing the + // ski routes, on foot (or unknown) the hiking and educational trails. + if (/driv|motor|car/i.test(this._activityType)) return null; + const kinds = this._ride ? ["bicycle"] : /ski/i.test(this._activityType) ? ["ski"] : ["hiking", "educational"]; + const colors = trailColorsAlong(this._profile, kinds); if (!colors) return null; const HEIGHT = 10; const toX = (p) => this._fx(p) * VIEWBOX_WIDTH; diff --git a/test/test_hiking_trails.rb b/test/test_hiking_trails.rb index b44f523..58fe46c 100644 --- a/test/test_hiking_trails.rb +++ b/test/test_hiking_trails.rb @@ -38,6 +38,22 @@ class HikingTrailsTest < Minitest::Test assert_nil Maptool::HikingTrails.parse_opl(opl.sub("forward,w3@backward", ",w3@"))["features"].first["properties"]["oneway_lines"] end + def test_parse_opl_tells_hiking_educational_bicycle_and_ski_routes_apart + opl = <<~OPL + w1 Thighway=path Nn10x20.087y49.179,n11x20.088y49.18 + r1 Troute=hiking,name=Červená Mw1@ + r2 Troute=hiking,name=Náučný%20%chodník%20%Sitno Mw1@ + r3 Troute=foot,osmc:symbol=green:white:green_diagonal Mw1@ + r4 Troute=mtb,name=Okruh Mw1@ + r5 Troute=ski,name=Bežkárska Mw1@ + r6 Troute=bus Mw1@ + OPL + + collection = Maptool::HikingTrails.parse_opl(opl) + assert_equal %w[hiking educational educational bicycle ski], collection["features"].map { |f| f["properties"]["kind"] } + assert_equal({ "version" => Maptool::HikingTrails::VERSION }, collection.slice("version")) + end + def test_parse_opl_skips_relations_that_are_not_route_hiking opl = <<~OPL w1 Thighway=path Nn10x20.087y49.179,n11x20.088y49.18 diff --git a/test/test_pmtiles_builder.rb b/test/test_pmtiles_builder.rb index d7652ff..3794bc0 100644 --- a/test/test_pmtiles_builder.rb +++ b/test/test_pmtiles_builder.rb @@ -278,7 +278,8 @@ class PmtilesBuilderTest < Minitest::Test # against real OPL fixtures. assert_equal ["SK"], Maptool::PmtilesBuilder.hiking_trails_countries(@data_dir) path = Maptool::PmtilesBuilder.hiking_trails_country_path(@data_dir, "SK") - assert_equal({ "type" => "FeatureCollection", "features" => [] }, JSON.parse(File.read(path))) + assert_equal({ "version" => Maptool::HikingTrails::VERSION, "type" => "FeatureCollection", "features" => [] }, JSON.parse(File.read(path))) + assert Maptool::HikingTrails.current?(path) end def test_build_offline_only_re_extracts_hiking_trails_for_a_newly_added_country