Bicycle and foot route profiles (Valhalla bicycle/pedestrian costing); hiking trail colours in the elevation profile; power, splits and best efforts in the profile; TCX import; FIT course export
CI / check (push) Successful in 19s
CI / deploy (push) Successful in 18s

This commit is contained in:
randy committed 2026-11-16 12:18:06 +01:00
1 parent 4c704045c5
commit f8755ea65a
21 files changed
+634 -40

No files matched your search

+26
View File
@@ -2141,6 +2141,27 @@ html, body {
color: #fff;
}
.profile-stats {
margin-top: 8px;
font-size: 0.85em;
}
.profile-stats table {
border-collapse: collapse;
}
.profile-stats td {
padding: 1px 10px 1px 0;
white-space: nowrap;
}
.profile-chart__trails {
display: block;
width: 100%;
height: 10px;
background: #eee;
}
.profile-panel__xaxis {
position: relative;
height: 14px;
@@ -2390,6 +2411,11 @@ html, body {
width: 4.5em;
}
.route-panel__vehicle [hidden],
.route-panel__avoid[hidden] {
display: none;
}
.route-panel__avoid {
display: flex;
gap: 8px;
+6 -1
View File
@@ -366,6 +366,11 @@ export class GpxPanelControl {
// A folder's loose points have no single file they came from.
file.original && { label: "Original file", run: () => this._download(`${gpxFileUrl(file.path)}?download=original`, file.name) },
{ label: "GeoJSON", run: () => this._download(geojsonUrl, `${file.name}.geojson`) },
// A course for a Garmin/Wahoo device to follow.
file.kinds?.some((kind) => kind === "track" || kind === "route") && {
label: "FIT course (Garmin, Wahoo)",
run: () => this._download(`${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "fit", name: file.name })}`, `${file.name}.fit`),
},
]);
}
@@ -984,7 +989,7 @@ export class GpxPanelControl {
// its .gpx/.fit/.geojson entries, so it's accepted here even though the
// tree never shows a .zip itself. .geojson: e.g. a node's GeoJSON
// download, re-imported.
const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name));
const files = [...fileList].filter((file) => /\.(gpx|fit|tcx|geojson|zip)$/i.test(file.name));
if (files.length === 0) return [];
let tree = null;
+62
View File
@@ -83,6 +83,67 @@ 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
// 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
@@ -227,6 +288,7 @@ export class HikingTrailsControl {
async _rebuildLanes() {
const build = (this._lanesBuild = {});
const features = [...this._selectedCountries].flatMap((code) => this._trailData.get(code)?.features || []);
shownTrails = features;
let graph = null;
if (features.length > 0) {
graph = buildLineGraph(features.flatMap(splitOneway), { routeProperty: "id", onewayProperty: "oneway" });
+8 -1
View File
@@ -488,7 +488,8 @@ export class RoutePanelControl {
const select = this._panel.querySelector(".route-panel__vehicle-select");
const editButton = this._panel.querySelector('[data-action="vehicle-edit"]');
const fieldset = this._panel.querySelector(".route-panel__vehicle");
const inputs = [...fieldset.querySelectorAll("input")];
const inputs = [...fieldset.querySelectorAll("input, select")];
const avoidRow = this._panel.querySelector(".route-panel__avoid");
try {
this._vehicles = await (await fetch(VEHICLES_URL)).json();
} catch {
@@ -500,6 +501,11 @@ export class RoutePanelControl {
this._vehicle = current();
this._vehicleId = select.value = this._vehicle.id;
inputs.forEach((input) => (input.value = this._vehicle[input.name] ?? ""));
// No type: a car (profiles saved before bicycle/foot existed).
const type = (fieldset.querySelector('[name="type"]').value = this._vehicle.type || "car");
if (type === "bicycle" && !this._vehicle.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid";
fieldset.querySelectorAll("[data-for]").forEach((el) => (el.hidden = !el.dataset.for.split(" ").includes(type)));
avoidRow.hidden = type !== "car"; // tolls/motorways: a car's choice
};
this._selectVehicle = (id) => {
this._vehicleId = id;
@@ -537,6 +543,7 @@ export class RoutePanelControl {
const value = input.value.trim();
if (input.name === "name") current().name = value;
else if (value === "") delete current()[input.name];
else if (input.name === "type" || input.name === "bicycle_type") current()[input.name] = value;
else current()[input.name] = value;
save();
}),
+2 -1
View File
@@ -7,7 +7,7 @@ import { escapeHtml } from "/js/gpx.js";
// Tracks & Points. Checked on every page load, not just right after a
// share, so a share made while logged out is still waiting after login.
const SHARED_CACHE = "shared-files";
const KNOWN_EXTENSION = /\.(gpx|fit|geojson|zip)$/i;
const KNOWN_EXTENSION = /\.(gpx|fit|tcx|geojson|zip)$/i;
// Some apps share a bare name ("Track 12") — the upload only accepts
// these extensions, so one is added from the file's type.
const EXTENSION_BY_TYPE = {
@@ -18,6 +18,7 @@ const EXTENSION_BY_TYPE = {
"application/json": ".geojson",
"application/zip": ".zip",
"application/vnd.ant.fit": ".fit",
"application/vnd.garmin.tcx+xml": ".tcx",
};
const DEFAULT_FOLDER = "Shared";
+161 -1
View File
@@ -1,7 +1,8 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { trailColorsAlong } from "/js/hiking_trails.js";
// Small-multiples profile chart: one row per metric the track actually has
// (elevation always, speed/cadence/heart rate only when present — plenty of
// (elevation always, speed/cadence/heart rate/power only when present — plenty of
// GPX files have none of those), sharing one x-axis (distance) and one
// crosshair. Elevation/speed/cadence/heart rate live on wildly different
// scales, so this is deliberately several single-series charts stacked
@@ -22,7 +23,11 @@ const SERIES = [
{ key: "speed_kmh", label: "Speed", unit: "km/h", color: "#1baf7a", height: 70, area: false },
{ key: "cadence_rpm", label: "Cadence", unit: "rpm", color: "#eda100", height: 70, area: false },
{ key: "heart_rate_bpm", label: "Heart rate", unit: "bpm", color: "#e34948", height: 70, area: false },
{ key: "power_w", label: "Power", unit: "W", color: "#7b4fd6", height: 70, area: false },
];
const BEST_DISTANCES_KM = [1, 5, 10, 21.0975, 42.195, 100];
const BEST_POWER_SECS = [5, 60, 300, 1200, 3600];
const CLIMB_TOLERANCE_M = 10; // a dip smaller than this doesn't end a climb
export class TrackProfilePanel {
constructor(map) {
@@ -63,6 +68,8 @@ export class TrackProfilePanel {
this._activeSeries = SERIES.filter((s) => this._profile.some((p) => typeof p[s.key] === "number"));
this._activeSeries.forEach((series) => this._chartsContainer.appendChild(this._renderChart(series)));
const trails = this._renderTrailBand();
if (trails) this._chartsContainer.appendChild(trails);
// One shared strip below the whole stack, not per-chart — every chart
// above uses the same x-scale (distance-position), so a separate axis
@@ -71,6 +78,7 @@ export class TrackProfilePanel {
this._xAxisStripEl.className = "profile-panel__xaxis";
this._chartsContainer.appendChild(this._xAxisStripEl);
this._renderXAxisTicks();
this._chartsContainer.insertAdjacentHTML("beforeend", statsTables(this._profile, properties.activity_type));
this._chartsContainer.addEventListener("pointermove", this._onPointerMove);
this._chartsContainer.addEventListener("pointerleave", this._onPointerLeave);
@@ -122,6 +130,35 @@ export class TrackProfilePanel {
return wrapper;
}
// A strip under the charts in the color of each marked hiking trail the
// 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);
if (!colors) return null;
const HEIGHT = 10;
const toX = (d) => (d / this._maxDistance) * VIEWBOX_WIDTH;
let rects = "";
let start = 0;
for (let i = 1; i < this._profile.length; i++) {
const run = colors[start];
if (i < this._profile.length - 1 && colors[i].join() === run.join()) continue;
const [x1, x2] = [toX(this._profile[start].distance_meters), toX(this._profile[i].distance_meters)];
run.forEach((color, j) => {
rects += `<rect x="${x1.toFixed(1)}" width="${(x2 - x1).toFixed(1)}" y="${((j * HEIGHT) / run.length).toFixed(2)}" height="${(HEIGHT / run.length).toFixed(2)}" fill="${color}"></rect>`;
});
start = i;
}
const band = document.createElement("div");
band.className = "profile-trails"; // not .profile-chart: those are the series rows _updateCrosshair walks
// Colors are normalizedTrailColor's (hiking_trails.js): known words or hex only.
band.innerHTML = `
<div class="profile-chart__label">Marked trails</div>
<svg viewBox="0 0 ${VIEWBOX_WIDTH} ${HEIGHT}" preserveAspectRatio="none" class="profile-chart__trails">${rects}</svg>
`;
return band;
}
_renderXAxisToggle() {
const row = document.createElement("div");
row.className = "profile-panel__xaxis-toggle";
@@ -213,6 +250,129 @@ export class TrackProfilePanel {
}
}
// Splits and best efforts under the charts, as two collapsed <details>.
// Splits need times (a planned route has none); the biggest climb doesn't.
function statsTables(profile, activityType) {
const timed = profile.filter((p) => typeof p.elapsed_secs === "number");
const total = profile.at(-1).distance_meters;
const ride = /cycl|bik|ride/i.test(activityType || "");
const hasHr = profile.some((p) => typeof p.heart_rate_bpm === "number");
const hasPower = profile.some((p) => typeof p.power_w === "number");
const pace = (secs, meters) => (ride ? `${((meters / secs) * 3.6).toFixed(1)} km/h` : `${formatPace(secs / (meters / 1000))} /km`);
let html = "";
if (timed.length > 1) {
const step = ride || total > 50000 ? 5000 : 1000;
const rows = splits(timed, step).map(
(s) => `<tr><td>${(s.to / 1000).toFixed(s.to % 1000 ? 1 : 0)} km</td><td>${formatDuration(s.secs)}</td><td>${pace(s.secs, s.meters)}</td><td>↑ ${Math.round(s.gain)} m</td>${hasHr ? `<td>${s.hr ? `${Math.round(s.hr)} bpm` : ""}</td>` : ""}${hasPower ? `<td>${s.power ? `${Math.round(s.power)} W` : ""}</td>` : ""}</tr>`,
);
html += `<details class="profile-stats"><summary>Splits (${step / 1000} km)</summary><table>${rows.join("")}</table></details>`;
}
const best = [];
if (timed.length > 1) {
BEST_DISTANCES_KM.filter((km) => km * 1000 <= total).forEach((km) => {
const secs = fastest(timed, km * 1000);
if (secs) best.push([`${km === 21.0975 ? "Half marathon" : km === 42.195 ? "Marathon" : `${km} km`}`, `${formatDuration(secs)} · ${pace(secs, km * 1000)}`]);
});
}
if (hasPower) {
BEST_POWER_SECS.forEach((secs) => {
const watts = bestPower(timed, secs);
if (watts) best.push([`Power ${secs < 60 ? `${secs} s` : `${secs / 60} min`}`, `${Math.round(watts)} W`]);
});
}
const climb = biggestClimb(profile);
if (climb) best.push(["Biggest climb", `↑ ${Math.round(climb.gain)} m over ${(climb.meters / 1000).toFixed(1)} km (${((climb.gain / climb.meters) * 100).toFixed(1)} %)`]);
if (best.length) html += `<details class="profile-stats"><summary>Best efforts</summary><table>${best.map(([k, v]) => `<tr><td>${k}</td><td>${v}</td></tr>`).join("")}</table></details>`;
return html;
}
// Every `step` meters: time, gain and average heart rate/power, the last
// split shorter. Points are the first at/after each boundary.
function splits(profile, step) {
const out = [];
let start = 0;
for (let i = 1; i < profile.length; i++) {
const last = i === profile.length - 1;
if (!last && profile[i].distance_meters < (out.length + 1) * step) continue;
const part = profile.slice(start, i + 1);
let gain = 0;
part.forEach((p, j) => {
const climb = j > 0 && p.elevation_meters != null && part[j - 1].elevation_meters != null ? p.elevation_meters - part[j - 1].elevation_meters : 0;
if (climb > 0) gain += climb;
});
const meters = profile[i].distance_meters - profile[start].distance_meters;
const secs = profile[i].elapsed_secs - profile[start].elapsed_secs;
if (meters > 0 && secs > 0) out.push({ to: profile[i].distance_meters, meters, secs, gain, hr: average(part, "heart_rate_bpm"), power: average(part, "power_w") });
start = i;
}
return out;
}
function average(points, key) {
const values = points.map((p) => p[key]).filter((v) => typeof v === "number");
return values.length ? values.reduce((a, b) => a + b, 0) / values.length : null;
}
// Shortest time over any stretch of at least `meters` (two pointers).
function fastest(profile, meters) {
let best = null;
let j = 0;
for (let i = 0; i < profile.length; i++) {
while (j < profile.length && profile[j].distance_meters - profile[i].distance_meters < meters) j++;
if (j === profile.length) break;
const secs = profile[j].elapsed_secs - profile[i].elapsed_secs;
if (secs > 0 && (best === null || secs < best)) best = secs;
}
return best;
}
// Highest average power over any `secs` window, time-weighted (samples
// aren't evenly spaced); a missing reading counts as 0 W.
function bestPower(profile, secs) {
const energy = [0];
for (let i = 1; i < profile.length; i++) energy.push(energy[i - 1] + (profile[i].power_w || 0) * (profile[i].elapsed_secs - profile[i - 1].elapsed_secs));
let best = null;
let j = 0;
for (let i = 0; i < profile.length; i++) {
while (j < profile.length && profile[j].elapsed_secs - profile[i].elapsed_secs < secs) j++;
if (j === profile.length) break;
const watts = (energy[j] - energy[i]) / (profile[j].elapsed_secs - profile[i].elapsed_secs);
if (best === null || watts > best) best = watts;
}
return best;
}
// The largest rise from a low to a later high without a dip of more than
// CLIMB_TOLERANCE_M in between.
function biggestClimb(profile) {
const points = profile.filter((p) => typeof p.elevation_meters === "number");
if (points.length < 2) return null;
let best = null;
let low = points[0];
let high = points[0];
const finish = () => {
const gain = high.elevation_meters - low.elevation_meters;
if (gain >= CLIMB_TOLERANCE_M && gain > (best?.gain ?? 0)) best = { gain, meters: high.distance_meters - low.distance_meters };
};
for (const p of points) {
if (p.elevation_meters > high.elevation_meters) high = p;
else if (high.elevation_meters - p.elevation_meters > CLIMB_TOLERANCE_M) {
finish();
low = high = p;
}
if (p.elevation_meters < low.elevation_meters) low = high = p;
}
finish();
return best;
}
function formatPace(secsPerKm) {
const minutes = Math.floor(secsPerKm / 60);
return `${minutes}:${String(Math.round(secsPerKm % 60)).padStart(2, "0")}`;
}
function nearestIndex(profile, targetDistance) {
// Distances are monotonically non-decreasing (see TrackStats.build_profile),
// so a binary search would work too — linear is simpler and profiles here
+1
View File
@@ -25,6 +25,7 @@
"application/geo+json", "application/json", ".geojson",
"application/zip", ".zip",
".fit", "application/vnd.ant.fit",
".tcx", "application/vnd.garmin.tcx+xml",
"application/xml", "text/xml",
"application/octet-stream"
]