Route elevation profile (climb, descent, max grade) from the terrain tiles, and reach (isochrones) in the route panel

This commit is contained in:
randy committed 2026-11-13 22:55:55 +01:00
1 parent b80575828a
commit cca985d2b9
10 files changed
+274 -26

No files matched your search

+142 -3
View File
@@ -3,8 +3,13 @@ import { ROUTE_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js";
import { wirePreview } from "/js/preview.js";
import { elevationAt } from "/js/dem.js";
const ROUTE_URL = "/api/route";
const ISOCHRONE_URL = "/api/isochrone";
const REACH_SOURCE = "route-reach";
const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart
const GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel
const VEHICLE_URL = "/api/vehicle";
const NOTES_URL = "/api/library/notes";
const SOURCE = "route";
@@ -16,9 +21,16 @@ const SAVE_FOLDER = "Routes";
// them comes from POST /api/route (Valhalla, for the stored vehicle). The
// route stays drawn after the panel closes, until Clear.
export class RoutePanelControl {
constructor(map, gnssControl) {
constructor(map, gnssControl, profilePanel) {
this._map = map;
this._gnss = gnssControl;
this._profilePanel = profilePanel;
this._reach = null; // the last /api/isochrone FeatureCollection
// Elevations from the offline terrain when it's there, as the hillshade does.
this._offlineTerrain = fetch("/api/terrain-tiles")
.then((r) => r.json())
.then((d) => d.available)
.catch(() => false);
this._points = []; // [{ lngLat: [lon, lat], name, marker }]
this._route = null; // the last /api/route Feature
this._request = 0; // so a slow older response can't overwrite a newer one
@@ -59,6 +71,17 @@ export class RoutePanelControl {
this._panel.querySelector('[data-action="position"]').addEventListener("click", () => this._addPosition());
this._editingNote = this._panel.querySelector(".route-panel__editing");
this._saveButton.addEventListener("click", () => this._save());
this._profileButton = this._panel.querySelector(".route-panel__profile");
this._profileButton.addEventListener("click", () => this._profilePanel.show(this._profileProperties()));
this._reachStatus = this._panel.querySelector(".route-panel__reach-status");
this._reachClear = this._panel.querySelector('[data-action="reach-clear"]');
this._panel.querySelector('[data-action="reach"]').addEventListener("click", () => this._showReach());
this._reachClear.addEventListener("click", () => {
this._reach = null;
this._reachClear.hidden = true;
this._reachStatus.hidden = true;
this._draw();
});
this._setupVehicle();
onlyOneSidePanelOpen(this._panel, () => this._setOpen(false));
@@ -213,6 +236,7 @@ export class RoutePanelControl {
this._draw();
this._saveButton.hidden = !route || !isLoggedIn();
this._directions.hidden = !route;
this._profileButton.hidden = true;
if (!route) {
this._summary.textContent = message;
return;
@@ -227,16 +251,84 @@ export class RoutePanelControl {
li.textContent = length > 0 ? `${text} (${length.toFixed(1)} km)` : text;
list.appendChild(li);
});
this._addElevation(route);
}
// Sampled from the terrain tiles once the route is there; adds climb,
// descent and the steepest sustained grade to the summary.
async _addElevation(route) {
const profile = await elevationProfile(route.geometry.coordinates, await this._offlineTerrain);
if (this._route !== route || !profile) return;
route.elevation = profile;
this._summary.textContent += ` · ↑ ${Math.round(profile.gain)} m ↓ ${Math.round(profile.loss)} m · max ${profile.maxGrade.toFixed(0)} %`;
this._profileButton.hidden = false;
}
// What TrackProfilePanel (and a library track) reads.
_profileProperties() {
const { distance_km: km, time_s: seconds } = this._route.properties;
const elevation = this._route.elevation;
return {
name: this._editing?.name || "Route",
distance_meters: km * 1000,
duration_secs: seconds,
...(elevation && { elevation_gain_meters: elevation.gain, profile: elevation.profile }),
};
}
// From the start point (or the map center with no points yet).
async _showReach() {
const center = this._points[0]?.lngLat || this._map.getCenter().toArray();
const minutes = this._panel.querySelector(".route-panel__reach select").value.split(",").map(Number);
this._reachStatus.hidden = false;
this._reachStatus.textContent = "Computing reach…";
try {
const response = await fetch(ISOCHRONE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ center, minutes }),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `failed (${response.status})`);
this._reach = data;
} catch (err) {
this._reachStatus.textContent = `No reach: ${err.message}`;
return;
}
this._reachStatus.textContent = `Reach from ${this._points[0] ? "the start" : "the map center"}: ${minutes.map((m) => formatDuration(m * 60)).join(", ")}`;
this._reachClear.hidden = false;
this._draw();
}
_draw() {
if (!this._map.isStyleLoaded() && !this._map.getSource(SOURCE)) return; // style.load draws it
const reach = this._reach || { type: "FeatureCollection", features: [] };
if (this._map.getSource(REACH_SOURCE)) {
this._map.getSource(REACH_SOURCE).setData(reach);
} else {
// Valhalla colors each contour (properties.color); drawn under the route.
this._map.addSource(REACH_SOURCE, { type: "geojson", data: reach });
this._map.addLayer({
id: `${REACH_SOURCE}-fill`,
type: "fill",
source: REACH_SOURCE,
paint: { "fill-color": ["get", "color"], "fill-opacity": 0.15 },
});
this._map.addLayer({
id: `${REACH_SOURCE}-outline`,
type: "line",
source: REACH_SOURCE,
paint: { "line-color": ["get", "color"], "line-width": 2 },
});
}
const data = { type: "FeatureCollection", features: this._route ? [this._route] : [] };
const source = this._map.getSource(SOURCE);
if (source) {
source.setData(data);
return;
}
if (!this._map.isStyleLoaded()) return; // style.load draws it
this._map.addSource(SOURCE, { type: "geojson", data });
this._map.addLayer({
id: `${SOURCE}-casing`,
@@ -265,7 +357,8 @@ export class RoutePanelControl {
const feature = {
type: "Feature",
geometry: this._route.geometry,
properties: { ...properties, name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
// The elevation profile too, so the library shows it like a track's.
properties: { ...properties, ...this._profileProperties(), name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
};
const editing = this._editing;
const response = await fetch(NOTES_URL, {
@@ -328,6 +421,52 @@ export class RoutePanelControl {
}
}
// The route's coordinates resampled every ≥50 m (at most PROFILE_SAMPLES
// points), each with its terrain elevation, as TrackProfilePanel's
// `profile`; plus total climb/descent and the steepest grade sustained
// over GRADE_WINDOW_M. null when no elevation could be read.
async function elevationProfile(coordinates, offline) {
const along = [0];
for (let i = 1; i < coordinates.length; i++) along.push(along[i - 1] + distanceM(coordinates[i - 1], coordinates[i]));
const total = along.at(-1);
const step = Math.max(50, total / PROFILE_SAMPLES);
const samples = [];
let segment = 1;
for (let d = 0; d < total; d += step) {
while (along[segment] < d) segment++;
const [a, b] = [coordinates[segment - 1], coordinates[segment]];
const t = (d - along[segment - 1]) / (along[segment] - along[segment - 1] || 1);
samples.push({ distance_meters: d, lon: a[0] + (b[0] - a[0]) * t, lat: a[1] + (b[1] - a[1]) * t });
}
samples.push({ distance_meters: total, lon: coordinates.at(-1)[0], lat: coordinates.at(-1)[1] });
const elevations = await Promise.all(samples.map((s) => elevationAt(s.lon, s.lat, offline)));
const profile = samples.map((s, i) => ({ ...s, elevation_meters: elevations[i] })).filter((p) => p.elevation_meters != null);
if (profile.length < 2) return null;
let gain = 0;
let loss = 0;
let maxGrade = 0;
let j = 0;
profile.forEach((p, i) => {
if (i > 0) {
const climb = p.elevation_meters - profile[i - 1].elevation_meters;
if (climb > 0) gain += climb;
else loss -= climb;
}
while (j < profile.length - 1 && profile[j].distance_meters - p.distance_meters < GRADE_WINDOW_M) j++;
const run = profile[j].distance_meters - p.distance_meters;
if (run >= GRADE_WINDOW_M) maxGrade = Math.max(maxGrade, (Math.abs(profile[j].elevation_meters - p.elevation_meters) / run) * 100);
});
return { profile, gain, loss, maxGrade };
}
function distanceM([lon1, lat1], [lon2, lat2]) {
const rad = Math.PI / 180;
const a = Math.sin(((lat2 - lat1) * rad) / 2) ** 2 + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(((lon2 - lon1) * rad) / 2) ** 2;
return 12742000 * Math.asin(Math.sqrt(a));
}
function formatDuration(seconds) {
const minutes = Math.round(seconds / 60);
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;