621 lines
28 KiB
JavaScript
621 lines
28 KiB
JavaScript
import { WALKING_ICON } from "/js/icons.js";
|
|
import { firstSymbolLayerId } from "/js/radar.js";
|
|
import { escapeHtml } from "/js/gpx.js";
|
|
import { lineLength, formatDistance } from "/js/measure.js";
|
|
import { buildLineGraph, orderLanesAsync, LaneLayer } from "/vendor/maplibre-gl-lanes/maplibre-gl-lanes.mjs";
|
|
|
|
// Overpass has permissive CORS (verified: Access-Control-Allow-Origin: *),
|
|
// so this queries it directly from the browser — no server-side proxy
|
|
// needed, same "public API, no key" story as the Nominatim search already
|
|
// hits from here. One query per click (not per pan/move like the
|
|
// Wikipedia layer's live refetch), so this stays well within Overpass's
|
|
// shared rate limits.
|
|
//
|
|
// Three independent public mirrors (also CORS-open, verified), raced with
|
|
// Promise.any rather than called one at a time — the shared free instances
|
|
// vary a lot in load from one moment to the next, and a multi-second wait
|
|
// on a single one was the main complaint. Whichever answers first wins;
|
|
// the others are simply left to finish and get GC'd, not worth the extra
|
|
// AbortController plumbing for a single one-off per-click request.
|
|
const OVERPASS_APIS = [
|
|
"https://overpass-api.de/api/interpreter",
|
|
"https://overpass.kumi.systems/api/interpreter",
|
|
"https://overpass.private.coffee/api/interpreter",
|
|
];
|
|
const CLICK_RADIUS_M = 40;
|
|
// OSM colour tag values are free text (untrusted) — only used as a CSS
|
|
// background if they look like an actual color (hex or a plain word),
|
|
// never interpolated unchecked into a style attribute.
|
|
const SAFE_COLOR = /^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)$/;
|
|
|
|
// Pre-rendered raster tiles, not vector — waymarkedtrails.org already
|
|
// colors each route by its OSM `colour` tag (the KST/KČT-style paint-blaze
|
|
// colors used in Slovakia/Czechia), falling back to plain red where a route
|
|
// has none, so there's no styling to do here ourselves. Used whenever no
|
|
// offline extract is available at all — same "quietly renders nothing
|
|
// without a network" story as the Wikipedia/Radar/Contour lines overlays.
|
|
const ONLINE_SOURCE_ID = "hiking-trails-online";
|
|
const ONLINE_LAYER_ID = "hiking-trails-online-line";
|
|
const TILE_URL = "https://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png";
|
|
const ATTRIBUTION =
|
|
'Trails © <a href="https://waymarkedtrails.org" target="_blank">Waymarked Trails</a> (CC-BY-SA), map data © OpenStreetMap contributors';
|
|
const OPACITY = 0.85;
|
|
|
|
// Offline: real vector trails for each country the viewer actually picks,
|
|
// GeoJSON generated at build time by Maptool::HikingTrails straight
|
|
// from the same Geofabrik .osm.pbf offline.pmtiles itself is built from
|
|
// (see lib/maptool/hiking_trails.rb, PmtilesBuilder.extract_hiking_trails)
|
|
// — no network needed, and no waiting on Overpass for click details either
|
|
// (hit-tested locally via LaneLayer.queryLane instead, see _handleClick
|
|
// below). One file per country rather than one combined file: a viewer
|
|
// covering a dozen countries' worth of offline map data rarely wants all
|
|
// of their hiking trails loaded at once, so this is opt-in per country
|
|
// instead.
|
|
//
|
|
// Drawn with maplibre-gl-lanes rather than a plain line layer: a stretch
|
|
// of path several marked routes share (very common with KST blazes) is
|
|
// otherwise one line drawn over and over, only the topmost color visible.
|
|
// Lanes puts each route in its own parallel lane instead. It needs routes
|
|
// sharing a path to share exact vertices, which OSM relations over shared
|
|
// ways already do. One LaneLayer over every picked country, not one per
|
|
// country, so lanes at a border stay ordered together. Doesn't drape over
|
|
// 3D terrain (sinks under raised ground, warns on the console) — a known
|
|
// limitation of the library, not worth working around for an overlay.
|
|
const LANES_LAYER_ID = "hiking-trails-lanes";
|
|
// Zoomed out further, a whole country's lanes took seconds per frame/zoom
|
|
// build and froze the map — and a trail line at that scale tells nothing.
|
|
const LANES_MIN_ZOOM = 11;
|
|
const LANE_SIZES = () => ({ spacing: 3.5, width: 3, casingWidth: 0.5 });
|
|
function offlineUrl(code) {
|
|
return `/tiles/hiking_trails/${code}.geojson`;
|
|
}
|
|
|
|
// waymarkedtrails.org's own fallback for an untagged route.
|
|
const DEFAULT_TRAIL_COLOR = "#c1272d";
|
|
// Real-world `colour` values seen in production data (see the 2026-09-13
|
|
// extraction against SK.osm.pbf) — anything outside this set (typos like
|
|
// "yelllow", multi-value combos like "blue, yellow", stray hex codes) falls
|
|
// back to DEFAULT_TRAIL_COLOR rather than being trusted as a CSS value
|
|
// straight from OSM tag text.
|
|
const KNOWN_TRAIL_COLORS = new Set(["red", "yellow", "blue", "green", "orange", "purple", "brown", "black", "white", "grey", "gray", "darkblue"]);
|
|
|
|
function normalizedTrailColor(raw) {
|
|
if (!raw) return DEFAULT_TRAIL_COLOR;
|
|
const trimmed = raw.trim();
|
|
if (KNOWN_TRAIL_COLORS.has(trimmed.toLowerCase())) return trimmed.toLowerCase();
|
|
return /^#[0-9a-fA-F]{3,8}$/.test(trimmed) ? trimmed : DEFAULT_TRAIL_COLOR;
|
|
}
|
|
|
|
// The offline trails currently drawn (every ticked country), 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
|
|
// 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;
|
|
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) {
|
|
const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
|
|
for (const line of lines) {
|
|
for (let i = 1; i < line.length; i++) {
|
|
const [a, b] = [line[i - 1], line[i]];
|
|
if (Math.max(a[0], b[0]) < w || Math.min(a[0], b[0]) > e || Math.max(a[1], b[1]) < s || Math.min(a[1], b[1]) > n) continue;
|
|
for (let x = Math.floor(Math.min(a[0], b[0]) / GRID_DEG); x <= Math.floor(Math.max(a[0], b[0]) / GRID_DEG); x++) {
|
|
for (let y = Math.floor(Math.min(a[1], b[1]) / GRID_DEG); y <= Math.floor(Math.max(a[1], b[1]) / GRID_DEG); y++) {
|
|
const key = `${x},${y}`;
|
|
if (!grid.has(key)) grid.set(key, []);
|
|
grid.get(key).push({ a, b, color: properties.color });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let any = false;
|
|
const colors = points.map(({ lon, lat }) => {
|
|
const found = new Set();
|
|
const [cx, cy] = [Math.floor(lon / GRID_DEG), Math.floor(lat / GRID_DEG)];
|
|
for (let dx = -1; dx <= 1; dx++) {
|
|
for (let dy = -1; dy <= 1; dy++) {
|
|
for (const { a, b, color } of grid.get(`${cx + dx},${cy + dy}`) || []) {
|
|
if (!found.has(color) && segmentDistanceM([lon, lat], a, b) <= TRAIL_MATCH_M) found.add(color);
|
|
}
|
|
}
|
|
}
|
|
if (found.size) any = true;
|
|
return [...found];
|
|
});
|
|
return any ? colors : null;
|
|
}
|
|
|
|
// Point to segment, on a local flat projection (fine at these distances).
|
|
function segmentDistanceM([lon, lat], a, b) {
|
|
const kx = 111320 * Math.cos((lat * Math.PI) / 180);
|
|
const ky = 110540;
|
|
const [ax, ay, bx, by] = [(a[0] - lon) * kx, (a[1] - lat) * ky, (b[0] - lon) * kx, (b[1] - lat) * ky];
|
|
const [dx, dy] = [bx - ax, by - ay];
|
|
const t = Math.max(0, Math.min(1, -(ax * dx + ay * dy) / (dx * dx + dy * dy || 1)));
|
|
return Math.hypot(ax + t * dx, ay + t * dy);
|
|
}
|
|
|
|
// Online mode's highlight outline for whichever route(s) the last click
|
|
// matched — drawn as its own separate source/layer (real geometry, from the
|
|
// Overpass response), since the raster tiles have no paintable features to
|
|
// highlight at all. Offline lanes use LaneLayer.setHighlight instead. Same "yellow outline on a picked
|
|
// route" treatment the earlier SVG prototype visualization used.
|
|
const HIGHLIGHT_SOURCE_ID = "hiking-trails-highlight";
|
|
const HIGHLIGHT_LAYER_ID = "hiking-trails-highlight-line";
|
|
|
|
// An Overlays panel item — a plain on/off checkbox (raster overlay) until
|
|
// offline extracts exist for at least one country, at which point it
|
|
// becomes an expandable per-country checklist instead (same expand shape
|
|
// as RadarControl), since a viewer with a dozen countries' worth of
|
|
// offline map data rarely wants all of their hiking trails loaded, let
|
|
// alone parsed by the browser, at once.
|
|
export class HikingTrailsControl {
|
|
constructor(map) {
|
|
this._map = map;
|
|
this._active = false; // the online-mode checkbox's own state
|
|
this._offlineCountries = []; // codes with an extract available on the server
|
|
this._selectedCountries = new Set(); // codes currently shown, offline mode
|
|
this._trailData = new Map(); // code -> fetched GeoJSON, kept across toggles/style swaps
|
|
this._routeInfo = new Map(); // String(relation id) -> feature properties, for the panel
|
|
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
|
|
|
|
// Each country entered while the main checkbox is on joins in.
|
|
// ponytail: a country left behind stays loaded until unticked.
|
|
map.on("moveend", () => {
|
|
if (this._inView) this._addCountriesInView();
|
|
if (this._selectedCountries.size > 0 && this._needsRebuild()) this._rebuildLanes();
|
|
});
|
|
|
|
map.on("click", (event) => this._handleClick(event));
|
|
|
|
this._panel = document.getElementById("trail-panel");
|
|
this._panelBody = this._panel.querySelector(".trail-panel__body");
|
|
this._panel.querySelector(".trail-panel__close").addEventListener("click", () => this._hidePanel());
|
|
|
|
// setStyle() (switching Online/Offline) tears down all custom sources/
|
|
// layers — put whatever was showing back, same as every other
|
|
// Overlays control. The highlight is transient (tied to whichever
|
|
// trail is showing in the panel, if any) — simpler to just drop it
|
|
// here than try to carry it across a style swap.
|
|
map.on("style.load", () => {
|
|
if (this._active) this._addOnlineLayer();
|
|
this._clearHighlight();
|
|
if (this._selectedCountries.size > 0) this._rebuildLanes();
|
|
});
|
|
}
|
|
|
|
mount(li) {
|
|
li.innerHTML = `
|
|
<div class="overlays-panel__row">
|
|
<input type="checkbox" class="overlays-panel__toggle">
|
|
<span class="overlays-panel__icon">${WALKING_ICON}</span>
|
|
<button type="button" class="overlays-panel__name">Hiking trails</button>
|
|
</div>
|
|
<div class="overlays-panel__details" hidden>
|
|
<ul class="hiking-trail-countries"></ul>
|
|
</div>
|
|
`;
|
|
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._checkbox.addEventListener("change", (event) => {
|
|
if (this._offlineCountries.length) this._toggleInView(event.target.checked);
|
|
else this._toggleOnline(event.target.checked);
|
|
});
|
|
this._nameButton.addEventListener("click", () => {
|
|
if (this._offlineCountries.length === 0) return; // nothing to expand into yet
|
|
const expanding = this._details.hidden;
|
|
this._details.hidden = !expanding;
|
|
this._nameButton.setAttribute("aria-expanded", String(expanding));
|
|
});
|
|
}
|
|
|
|
// Called once map.js's GET /api/hiking-trails check resolves. Switches
|
|
// this item from "online raster, plain on/off" to "offline vector,
|
|
// pick your countries" — the two are mutually exclusive rather than
|
|
// both offered at once, since once a real local extract exists there's
|
|
// no reason to still fall back to a third-party tile server for any of
|
|
// it.
|
|
setOfflineCountries(countries, bboxes = {}) {
|
|
this._offlineCountries = countries;
|
|
this._bboxes = bboxes;
|
|
if (countries.length === 0) return;
|
|
|
|
if (this._active) this._toggleOnline(false);
|
|
// The main checkbox stays: offline it shows the countries in view,
|
|
// never all at once (together they're ~1 GB of GeoJSON, more than a
|
|
// browser parses); the name opens the list to pick some by hand.
|
|
this._checkbox.checked = false;
|
|
this._checkbox.title = `Countries in view, from zoom ${LANES_MIN_ZOOM} — click the name to pick some`;
|
|
|
|
this._countryList.innerHTML = countries
|
|
.map(
|
|
(code) => `
|
|
<li class="hiking-trail-countries__item">
|
|
<label>
|
|
<input type="checkbox" class="hiking-trail-countries__toggle" value="${code}">
|
|
${code}
|
|
</label>
|
|
</li>
|
|
`,
|
|
)
|
|
.join("");
|
|
this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => {
|
|
input.addEventListener("change", (event) => {
|
|
this._toggleCountry(event.target.value, event.target.checked);
|
|
this._syncMainCheckbox();
|
|
});
|
|
});
|
|
}
|
|
|
|
// 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);
|
|
this._syncMainCheckbox();
|
|
}
|
|
|
|
_toggleInView(active) {
|
|
this._inView = active;
|
|
if (active) {
|
|
this._addCountriesInView();
|
|
} else {
|
|
this._countryList.querySelectorAll(".hiking-trail-countries__toggle:checked").forEach((input) => {
|
|
input.checked = false;
|
|
this._toggleCountry(input.value, false);
|
|
});
|
|
}
|
|
this._syncMainCheckbox();
|
|
}
|
|
|
|
// Trails are drawn from LANES_MIN_ZOOM only, so nothing loads before.
|
|
_addCountriesInView() {
|
|
if (this._map.getZoom() < LANES_MIN_ZOOM) return;
|
|
const view = this._map.getBounds();
|
|
this._countryList.querySelectorAll(".hiking-trail-countries__toggle:not(:checked)").forEach((input) => {
|
|
const [w, s, e, n] = this._bboxes[input.value] || [];
|
|
if (n === undefined || w > view.getEast() || e < view.getWest() || s > view.getNorth() || n < view.getSouth()) return;
|
|
input.checked = true;
|
|
this._toggleCountry(input.value, true);
|
|
});
|
|
}
|
|
|
|
_syncMainCheckbox() {
|
|
const on = this._countryList.querySelectorAll(".hiking-trail-countries__toggle:checked").length;
|
|
this._checkbox.checked = this._inView;
|
|
this._checkbox.indeterminate = !this._inView && on > 0;
|
|
}
|
|
|
|
_toggleOnline(active) {
|
|
this._active = active;
|
|
if (active) this._addOnlineLayer();
|
|
else this._removeOnlineLayer();
|
|
}
|
|
|
|
async _toggleCountry(code, active) {
|
|
if (!active) {
|
|
this._selectedCountries.delete(code);
|
|
this._rebuildLanes();
|
|
return;
|
|
}
|
|
this._selectedCountries.add(code);
|
|
if (!this._trailData.has(code)) {
|
|
let geojson;
|
|
try {
|
|
geojson = await (await fetch(offlineUrl(code))).json();
|
|
} catch {
|
|
return; // degrade quietly, same story as every other optional layer here
|
|
}
|
|
// Normalized once here so an untrustworthy `colour` tag value never
|
|
// reaches the layer's color directly — same reasoning gpx.js's own
|
|
// feature.properties.color ||= TRACK_COLOR normalization gives.
|
|
for (const feature of geojson.features) {
|
|
feature.properties.color = normalizedTrailColor(feature.properties.colour);
|
|
}
|
|
this._trailData.set(code, geojson);
|
|
if (!this._selectedCountries.has(code)) return; // toggled back off while fetching
|
|
}
|
|
this._rebuildLanes();
|
|
}
|
|
|
|
// Rebuilt from scratch on every country toggle, style swap (setStyle
|
|
// drops custom layers too) and when the view leaves the area built for —
|
|
// lane order depends on every route drawn, so there's no cheaper
|
|
// incremental path. Only the route pieces around the view (half a view
|
|
// around it): a whole country's graph took seconds on the main thread
|
|
// per rebuild and froze the browser; at zoom 11 this is ~0.5 s. Ordering runs in a worker; a newer rebuild started
|
|
// meanwhile wins, same token guard as _handleOnlineClick.
|
|
async _rebuildLanes() {
|
|
const build = (this._lanesBuild = {});
|
|
const all = [...this._selectedCountries].flatMap((code) => this._trailData.get(code)?.features || []);
|
|
shownTrails = all;
|
|
let features = [];
|
|
this._builtArea = null;
|
|
if (all.length > 0 && this._map.getZoom() >= LANES_MIN_ZOOM) {
|
|
const view = this._map.getBounds();
|
|
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));
|
|
}
|
|
let graph = null;
|
|
if (features.length > 0) {
|
|
graph = buildLineGraph(features.flatMap(splitOneway), { routeProperty: "id", onewayProperty: "oneway" });
|
|
await orderLanesAsync(graph);
|
|
}
|
|
if (this._lanesBuild !== build) return;
|
|
|
|
this._hidePanel();
|
|
if (this._map.getLayer(LANES_LAYER_ID)) this._map.removeLayer(LANES_LAYER_ID);
|
|
this._lanes = null;
|
|
this._routeInfo = new Map(features.map((feature) => [String(feature.properties.id), feature.properties]));
|
|
if (!graph) return;
|
|
|
|
this._lanes = new LaneLayer({ id: LANES_LAYER_ID, graph, sizes: LANE_SIZES, casingColor: "rgba(255, 255, 255, 0.8)" });
|
|
// Below labels (same firstSymbolLayerId spot contour.js/radar.js use),
|
|
// so place names/POI icons stay readable on top of the trail lines.
|
|
this._map.addLayer(this._lanes, firstSymbolLayerId(this._map));
|
|
this._map.setLayerZoomRange(LANES_LAYER_ID, LANES_MIN_ZOOM, 24);
|
|
}
|
|
|
|
// Zoomed in from below LANES_MIN_ZOOM, or out of the built area.
|
|
_needsRebuild() {
|
|
if (this._map.getZoom() < LANES_MIN_ZOOM) return false;
|
|
if (!this._builtArea) return true;
|
|
const view = this._map.getBounds();
|
|
const [w, s, e, n] = this._builtArea;
|
|
return view.getWest() < w || view.getSouth() < s || view.getEast() > e || view.getNorth() > n;
|
|
}
|
|
|
|
_handleClick(event) {
|
|
if (this._selectedCountries.size > 0) this._handleOfflineClick(event);
|
|
else if (this._active) this._handleOnlineClick(event);
|
|
}
|
|
|
|
// The lanes have real geometry to hit-test directly — no network
|
|
// round-trip, so this resolves instantly. Each route has its own lane, so
|
|
// a click picks exactly one, highlighted by the layer itself. A genuine
|
|
// miss just closes an already-open panel rather than showing a "not
|
|
// found" message, same as clicking empty space anywhere else on the map.
|
|
_handleOfflineClick(event) {
|
|
const hit = this._map.getZoom() >= LANES_MIN_ZOOM && this._lanes?.queryLane(event.point, 8);
|
|
const info = hit && this._routeInfo.get(String(hit.route));
|
|
if (!info) {
|
|
this._hidePanel();
|
|
return;
|
|
}
|
|
this._lanes.setHighlight(hit.route);
|
|
this._showPanel(routeHtml(info));
|
|
}
|
|
|
|
_showPanel(html) {
|
|
this._panelBody.innerHTML = html;
|
|
this._panel.hidden = false;
|
|
}
|
|
|
|
_hidePanel() {
|
|
if (this._panel.hidden) return;
|
|
this._panel.hidden = true;
|
|
this._clearHighlight();
|
|
}
|
|
|
|
// The raster tiles have no queryable features (they're pixels), so
|
|
// "what trail is this" is answered with a one-off Overpass query instead
|
|
// of a MapLibre feature hit-test — an `around` search rather than an
|
|
// exact point match, since a click rarely lands exactly on the (already
|
|
// pixel-thick) rendered line.
|
|
async _handleOnlineClick(event) {
|
|
const { lng, lat } = event.lngLat;
|
|
this._showPanel(`<p class="gpx-popup__category">Looking for trails…</p>`);
|
|
// A newer click's request replaces this one while Overpass is still
|
|
// answering — same "in-flight response arrives after it's already
|
|
// stale" guard the old Popup-identity check gave, just keyed off a
|
|
// fresh token each click instead of a fresh Popup instance.
|
|
const request = (this._onlineRequest = {});
|
|
|
|
let relations;
|
|
try {
|
|
relations = await fetchNearbyRoutes(lng, lat);
|
|
} catch {
|
|
if (this._onlineRequest === request) this._panelBody.innerHTML = `<p class="gpx-popup__category">Could not reach Overpass.</p>`;
|
|
return;
|
|
}
|
|
if (this._onlineRequest !== request) return;
|
|
|
|
if (relations.length === 0) {
|
|
this._panelBody.innerHTML = `<p class="gpx-popup__category">No hiking trail found here.</p>`;
|
|
return;
|
|
}
|
|
this._panelBody.innerHTML = relations.map((relation) => routeHtml(overpassRouteInfo(relation))).join("<hr>");
|
|
this._setHighlight(relations.map((relation) => ({ geometry: routeGeometry(relation), color: normalizedTrailColor(relation.tags?.colour) })));
|
|
}
|
|
|
|
_addOnlineLayer() {
|
|
if (this._map.getSource(ONLINE_SOURCE_ID)) return;
|
|
|
|
this._map.addSource(ONLINE_SOURCE_ID, {
|
|
type: "raster",
|
|
tiles: [TILE_URL],
|
|
tileSize: 256,
|
|
maxzoom: 17,
|
|
attribution: ATTRIBUTION,
|
|
});
|
|
// Below labels (same firstSymbolLayerId spot contour.js/radar.js use),
|
|
// so place names/POI icons stay readable on top of the trail lines.
|
|
this._map.addLayer(
|
|
{ id: ONLINE_LAYER_ID, type: "raster", source: ONLINE_SOURCE_ID, paint: { "raster-opacity": OPACITY } },
|
|
firstSymbolLayerId(this._map),
|
|
);
|
|
}
|
|
|
|
_removeOnlineLayer() {
|
|
if (this._map.getLayer(ONLINE_LAYER_ID)) this._map.removeLayer(ONLINE_LAYER_ID);
|
|
if (this._map.getSource(ONLINE_SOURCE_ID)) this._map.removeSource(ONLINE_SOURCE_ID);
|
|
}
|
|
|
|
// features: an array of { geometry, color } — geometry a GeoJSON
|
|
// LineString or MultiLineString (mixed is fine), color the trail's own
|
|
// (already-normalized) colour — everything the last click matched, drawn
|
|
// as one highlight layer (a wider outline in the trail's own color,
|
|
// rather than a fixed color that would repaint it) on top of the base
|
|
// trail rendering.
|
|
_setHighlight(features) {
|
|
const data = {
|
|
type: "FeatureCollection",
|
|
features: features.map(({ geometry, color }) => ({ type: "Feature", properties: { color }, geometry })),
|
|
};
|
|
const source = this._map.getSource(HIGHLIGHT_SOURCE_ID);
|
|
if (source) {
|
|
source.setData(data);
|
|
return;
|
|
}
|
|
this._map.addSource(HIGHLIGHT_SOURCE_ID, { type: "geojson", data });
|
|
this._map.addLayer({
|
|
id: HIGHLIGHT_LAYER_ID,
|
|
type: "line",
|
|
source: HIGHLIGHT_SOURCE_ID,
|
|
layout: { "line-cap": "round", "line-join": "round" },
|
|
paint: { "line-color": ["get", "color"], "line-width": 5, "line-opacity": 0.9 },
|
|
});
|
|
}
|
|
|
|
_clearHighlight() {
|
|
this._lanes?.setHighlight(null);
|
|
if (this._map.getLayer(HIGHLIGHT_LAYER_ID)) this._map.removeLayer(HIGHLIGHT_LAYER_ID);
|
|
if (this._map.getSource(HIGHLIGHT_SOURCE_ID)) this._map.removeSource(HIGHLIGHT_SOURCE_ID);
|
|
}
|
|
}
|
|
|
|
// way(around:...) finds candidate ways near the click, then rel(bw...)
|
|
// walks backward from those to their parent relations — the same
|
|
// find-the-way-then-its-relation shape as clicking a route on
|
|
// waymarkedtrails.org's own site. `out geom` inlines each member way's
|
|
// full coordinate list right on the relation, so no separate stitching
|
|
// step is needed to get real geometry back.
|
|
async function queryOverpass(url, query) {
|
|
const response = await fetch(url, { method: "POST", body: `data=${encodeURIComponent(query)}` });
|
|
if (!response.ok) throw new Error(`overpass ${response.status}`);
|
|
return response.json();
|
|
}
|
|
|
|
async function fetchNearbyRoutes(lng, lat) {
|
|
const query = `[out:json][timeout:15];way(around:${CLICK_RADIUS_M},${lat},${lng})->.w;rel(bw.w)["route"="hiking"];out geom;`;
|
|
const data = await Promise.any(OVERPASS_APIS.map((url) => queryOverpass(url, query)));
|
|
return (data.elements || []).filter((element) => element.type === "relation");
|
|
}
|
|
|
|
// OSM doesn't tag a route's length directly — summed from each member
|
|
// way's own geometry instead, same haversine-sum measure.js's own Measure
|
|
// tool uses for a hand-drawn line. Shared endpoints between adjacent ways
|
|
// get walked twice, same as how a real hike over those ways would. Mirrors
|
|
// Maptool::HikingTrails.relation_feature's own distance calc server-side
|
|
// (lib/maptool/hiking_trails.rb) — this is the online, no-server-file path.
|
|
function routeDistance(relation) {
|
|
return (relation.members || [])
|
|
.filter((member) => member.type === "way" && member.geometry)
|
|
.reduce((total, member) => total + lineLength(member.geometry.map((point) => [point.lon, point.lat])), 0);
|
|
}
|
|
|
|
// Same member-way walk as routeDistance above, collecting coordinates
|
|
// instead of summing them — the online click highlight's geometry source,
|
|
// since there's no vector feature to read it back from the way the offline
|
|
// layer's own queryRenderedFeatures result already carries one.
|
|
function routeGeometry(relation) {
|
|
const lines = (relation.members || [])
|
|
.filter((member) => member.type === "way" && member.geometry)
|
|
.map((member) => member.geometry.map((point) => [point.lon, point.lat]));
|
|
return { type: "MultiLineString", coordinates: lines };
|
|
}
|
|
|
|
// Adapts a raw Overpass relation into the same shape offline GeoJSON
|
|
// features' properties already carry (lib/maptool/hiking_trails.rb's own
|
|
// ROUTE_TAGS + distance_meters + id) — one HTML builder (routeHtml) below
|
|
// serves both instead of two near-identical ones.
|
|
function overpassRouteInfo(relation) {
|
|
const tags = relation.tags || {};
|
|
return {
|
|
id: relation.id,
|
|
name: tags.name,
|
|
description: tags.description,
|
|
colour: tags.colour,
|
|
network: tags.network,
|
|
operator: tags.operator,
|
|
ref: tags.ref,
|
|
distance_meters: routeDistance(relation),
|
|
};
|
|
}
|
|
|
|
function routeHtml(info) {
|
|
const name = info.name || info.description || "Hiking trail";
|
|
const swatch = SAFE_COLOR.test(info.colour || "")
|
|
? `<span class="hiking-trail-popup__swatch" style="background:${info.colour}"></span>`
|
|
: "";
|
|
const meta = [formatDistance(info.distance_meters || 0)];
|
|
if (info.ref) meta.push(`#${info.ref}`);
|
|
if (info.network) meta.push(info.network);
|
|
if (info.operator) meta.push(escapeHtml(info.operator));
|
|
|
|
const parts = [
|
|
`<div class="gpx-popup__header"><strong>${escapeHtml(name)}</strong>${swatch}</div>`,
|
|
`<p class="gpx-popup__category">${meta.filter(Boolean).join(" · ")}</p>`,
|
|
];
|
|
// description already used as the title above when there's no name — only
|
|
// shown again here as its own line if there both is a name *and* a
|
|
// description to add, so it's never rendered twice for the common
|
|
// no-name case.
|
|
if (info.name && info.description) parts.push(`<p class="gpx-popup__description">${escapeHtml(info.description)}</p>`);
|
|
parts.push(
|
|
`<p class="gpx-popup__link"><a href="https://www.openstreetmap.org/relation/${info.id}" target="_blank" rel="noopener noreferrer">View on OpenStreetMap →</a></p>`,
|
|
);
|
|
return parts.join("");
|
|
}
|
|
|
|
// A route's one-way lines (oneway_lines, already pointing the way they're
|
|
// walked: lib/maptool/hiking_trails.rb) as a feature of their own marked
|
|
// oneway, so maplibre-gl-lanes keeps the route on them in that direction.
|
|
// The route's lines (its member ways) with a vertex in `area` [w, s, e,
|
|
// n], [] when none; oneway_lines renumbered to match.
|
|
function clipToArea(feature, area) {
|
|
const [w, s, e, n] = area;
|
|
const lines = feature.geometry.type === "LineString" ? [feature.geometry.coordinates] : feature.geometry.coordinates;
|
|
const oneway = new Set(feature.properties.oneway_lines);
|
|
const kept = [];
|
|
const keptOneway = [];
|
|
lines.forEach((line, i) => {
|
|
if (!line.some(([x, y]) => x >= w && x <= e && y >= s && y <= n)) return;
|
|
if (oneway.has(i)) keptOneway.push(kept.length);
|
|
kept.push(line);
|
|
});
|
|
if (kept.length === 0) return [];
|
|
return [{ ...feature, properties: { ...feature.properties, oneway_lines: keptOneway }, geometry: { type: "MultiLineString", coordinates: kept } }];
|
|
}
|
|
|
|
function splitOneway(feature) {
|
|
const oneway = new Set(feature.properties.oneway_lines);
|
|
if (oneway.size === 0) return [feature];
|
|
const lines = feature.geometry.coordinates;
|
|
const part = (coordinates, properties) => ({ ...feature, properties, geometry: { type: "MultiLineString", coordinates } });
|
|
return [
|
|
part(lines.filter((_, i) => !oneway.has(i)), feature.properties),
|
|
part(lines.filter((_, i) => oneway.has(i)), { ...feature.properties, oneway: "yes" }),
|
|
].filter((f) => f.geometry.coordinates.length > 0);
|
|
}
|