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

+1 -1
View File
@@ -88,7 +88,7 @@ Deprioritized for now — revisit after the sections above land.
** [x] Phase 1: `valhalla` compose service (`bin/routing-service.sh`), builds from the offline map's extracts, "Offline routing" row in the Offline data panel
** [x] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
** [x] Route points from search / GPS / a library point, reordering, re-editing a saved route
** [ ] Phase 3: elevation profile from terrain.pmtiles, isochrones
** [x] Phase 3: elevation profile from terrain.pmtiles, isochrones
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
=== HW integration
+13
View File
@@ -463,6 +463,19 @@ module Maptool
halt 503, json(error: e.message)
end
# Where the stored vehicle gets in each of `minutes` from `center`
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
post "/api/isochrone" do
body = JSON.parse(request.body.read)
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR))
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
halt 422, json(error: e.message)
rescue Routing::Unavailable => e
halt 503, json(error: e.message)
end
get "/api/vehicle" do
json Routing.vehicle(DATA_DIR)
end
+13 -4
View File
@@ -2,7 +2,7 @@
:toc:
:toclevels: 1
Status: *phases 1–2 implemented* (the container and builds; the route panel, vehicle profile and saving a route); phase 3 proposed.
Status: *implemented* (the container and builds; the route panel, vehicle profile and saving a route; elevation profile and reach).
== Goal
@@ -157,9 +157,18 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
. Container + build script + "Build routing" + status. Done when
`curl valhalla:8002/route` answers on the server.
. `/api/route`, the vehicle profile, the route panel, save to library.
. Elevation profile of the route (sampled from `terrain.pmtiles`, which
is already there, instead of Valhalla's own SRTM download), then
isochrones.
. Elevation profile of the route, then isochrones. Done:
* The browser samples the route every ≥50 m (at most 400 points) from
the same terrain tiles the hillshade uses (`dem.js`; from
`terrain.pmtiles` when it's there, else online), instead of
Valhalla's own SRTM download. The summary adds climb, descent and the
steepest grade sustained over 500 m. "Elevation profile" opens the
usual profile panel, and a saved route keeps the profile, so the
library shows it like a track's.
* `POST /api/isochrone` (`{"center": [lon, lat], "minutes": [...]}`,
1–4 times up to 240 min) returns Valhalla's polygons for the stored
vehicle. "Reach in" in the route panel draws them from the start
point, or from the map center when there are no points yet.
== Open questions
+45 -17
View File
@@ -143,24 +143,11 @@ module Maptool
# (km), time (s) and the turn-by-turn instructions.
def self.route(valhalla_url, locations, vehicle)
raise RouteError, "at least two points are needed" if locations.size < 2
raise Unavailable, "routing is not set up" if valhalla_url.to_s.empty?
car = vehicle[:weight] <= CAR_MAX_WEIGHT
costing = car ? "auto" : "truck"
options = car ? vehicle.slice(:height, :width) : vehicle
body = { locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers" }
uri = URI("#{valhalla_url}/route")
response = begin
Net::HTTP.start(uri.host, uri.port, open_timeout: 2, read_timeout: 60) do |http|
http.post(uri.path, JSON.generate(body), "Content-Type" => "application/json")
end
rescue SystemCallError, Net::OpenTimeout, SocketError
raise Unavailable, "the routing service is not running"
end
data = JSON.parse(response.body)
raise RouteError, data["error"] || "no route found" unless response.is_a?(Net::HTTPSuccess)
costing, options = costing(vehicle)
data = valhalla(valhalla_url, "/route",
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers")
legs = data["trip"]["legs"]
{ type: "Feature",
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
@@ -171,6 +158,47 @@ module Maptool
raise RouteError, "invalid coordinates"
end
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
# GeoJSON FeatureCollection of polygons, largest first.
def self.isochrone(valhalla_url, center, minutes, vehicle)
lon, lat = center
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
costing, options = costing(vehicle)
valhalla(valhalla_url, "/isochrone",
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
contours: minutes.map { |m| { time: m } }, polygons: true)
rescue ArgumentError, TypeError
raise RouteError, "invalid center or times"
end
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
def self.costing(vehicle)
vehicle[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", vehicle.slice(:height, :width)] : ["truck", vehicle]
end
private_class_method :costing
def self.valhalla(valhalla_url, path, body)
raise Unavailable, "routing is not set up" if valhalla_url.to_s.empty?
uri = URI("#{valhalla_url}#{path}")
response = begin
Net::HTTP.start(uri.host, uri.port, open_timeout: 2, read_timeout: 60) do |http|
http.post(uri.path, JSON.generate(body), "Content-Type" => "application/json")
end
rescue SystemCallError, Net::OpenTimeout, SocketError
raise Unavailable, "the routing service is not running"
end
data = JSON.parse(response.body)
raise RouteError, data["error"] || "no result" unless response.is_a?(Net::HTTPSuccess)
data
end
private_class_method :valhalla
# Valhalla's encoded polyline (precision 6) → [[lon, lat], ...].
def self.decode_polyline(encoded)
values = []
+34
View File
@@ -2407,3 +2407,37 @@ html, body {
.preview-highlight {
pointer-events: none;
}
.route-panel__profile,
.route-panel__reach button,
.route-panel__reach select {
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
padding: 3px 6px;
font: inherit;
font-size: 12px;
cursor: pointer;
}
.route-panel__profile {
margin-bottom: 8px;
}
.route-panel__profile[hidden],
.route-panel__reach button[hidden],
.route-panel__reach-status[hidden] {
display: none;
}
.route-panel__reach {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
}
.route-panel__reach-status {
margin: 0 0 8px;
color: #666;
}
+1 -1
View File
@@ -585,7 +585,7 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Offline hub"></div>`);
layerToggle.mount(sidebar);
layerToggle.setActive("online");
new RoutePanelControl(map, gnssControl).mount(sidebar);
new RoutePanelControl(map, gnssControl, profilePanel).mount(sidebar);
new OfflineDataControl().mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`);
+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`;
+2
View File
@@ -233,6 +233,8 @@ class AppTest < Minitest::Test
def test_routing_without_a_valhalla_service_says_so
assert_equal 503, request.post("/api/route", input: JSON.generate(locations: [[17.1, 48.1], [17.2, 48.2]]), "CONTENT_TYPE" => "application/json").status
assert_equal 400, request.post("/api/route", input: JSON.generate(locations: "x"), "CONTENT_TYPE" => "application/json").status
assert_equal 503, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [60]), "CONTENT_TYPE" => "application/json").status
assert_equal 422, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [999]), "CONTENT_TYPE" => "application/json").status
end
def test_the_vehicle_is_readable_by_anyone_but_saved_only_when_logged_in
+10
View File
@@ -90,6 +90,16 @@ class RoutingTest < Minitest::Test
assert_raises(Maptool::Routing::Unavailable) { Maptool::Routing.route("", [[1, 2], [3, 4]], {}) }
end
def test_isochrone_asks_valhalla_for_each_time_and_checks_them
reply = JSON.generate(type: "FeatureCollection", features: [])
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
assert_equal "FeatureCollection", Maptool::Routing.isochrone(url, [17.1, 48.1], [60, 30, 60], Maptool::Routing::DEFAULT_VEHICLE)["type"]
end
assert_includes request, %("contours":[{"time":30},{"time":60}])
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", [17.1, 48.1], [600], {}) }
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", nil, [30], {}) }
end
private
# Answers one HTTP request with `response`; returns what was received.
+13
View File
@@ -121,10 +121,23 @@
<button type="button" data-action="save" hidden>Save to library</button>
</div>
<p class="route-panel__summary"></p>
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
<details class="route-panel__directions" hidden>
<summary>Directions</summary>
<ol></ol>
</details>
<div class="route-panel__reach">
<span>Reach in</span>
<select>
<option value="30">30 min</option>
<option value="60" selected>1 h</option>
<option value="120">2 h</option>
<option value="30,60,120">30 min · 1 h · 2 h</option>
</select>
<button type="button" data-action="reach">Show</button>
<button type="button" data-action="reach-clear" hidden>Hide</button>
</div>
<p class="route-panel__reach-status" hidden></p>
<fieldset class="route-panel__vehicle">
<legend>Vehicle</legend>
<label>Height <input type="number" name="height" step="0.1" min="1" max="6"> m</label>