Files
maptool/public/js/route.js
T

474 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
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";
const COLOR = "#1d6fdc";
const SAVE_FOLDER = "Routes";
// Offline routing (docs/routing-design.adoc): while the panel is open, a
// map click adds a point, markers drag to move, and the route through
// 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, 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
this._editing = null; // { key, id, name } of a saved route being edited
onRoutePoint(({ lngLat, name }) => {
this._setOpen(true);
this._addPoint(lngLat, name);
});
onRouteEdit(({ key, feature }) => this._edit(key, feature));
map.on("click", (event) => {
if (this._panel.hidden || event.originalEvent.altKey) return;
this._addPoint([event.lngLat.lng, event.lngLat.lat]);
});
// setStyle() (base map switch) drops custom sources.
map.on("style.load", () => this._draw());
}
mount(sidebar) {
this._container = document.createElement("div");
this._container.className = "sidebar-item";
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Route" aria-label="Route">${ROUTE_ICON}</button>`;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("route-panel");
this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
this._list = this._panel.querySelector(".route-panel__points");
this._summary = this._panel.querySelector(".route-panel__summary");
this._directions = this._panel.querySelector(".route-panel__directions");
this._saveButton = this._panel.querySelector('[data-action="save"]');
this._panel.querySelector('[data-action="reverse"]').addEventListener("click", () => {
this._points.reverse();
this._changed();
});
this._panel.querySelector('[data-action="clear"]').addEventListener("click", () => this._clear());
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));
sidebar.appendChild(this._container);
}
_togglePanel(force) {
this._setOpen(force === undefined ? this._panel.hidden : force);
}
_setOpen(open) {
this._panel.hidden = !open;
this._icon.classList.toggle("active", open);
this._map.getCanvas().style.cursor = open ? "crosshair" : "";
if (open) notifySidePanelOpen(this._panel);
}
// --- points ---------------------------------------------------------------
_addPoint(lngLat, name, { quiet = false } = {}) {
const element = document.createElement("div");
element.className = "route-marker";
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
const point = { lngLat, name, marker };
marker.on("dragend", () => {
const { lng, lat } = marker.getLngLat();
point.lngLat = [lng, lat];
point.name = null; // no longer that place
this._changed();
});
this._points.push(point);
if (!quiet) this._changed();
}
// The GNSS fix when there is one, else the browser's own position.
_addPosition() {
const fix = this._gnss?.getPosition();
if (fix) {
this._addPoint([fix.lng, fix.lat], "My position");
return;
}
navigator.geolocation.getCurrentPosition(
(position) => this._addPoint([position.coords.longitude, position.coords.latitude], "My position"),
() => window.alert("Could not determine your location."),
{ enableHighAccuracy: true },
);
}
_move(point, step) {
const index = this._points.indexOf(point);
const other = index + step;
if (other < 0 || other >= this._points.length) return;
[this._points[index], this._points[other]] = [this._points[other], this._points[index]];
this._changed();
}
// A saved route's points back in the panel; Save then updates that item.
_edit(key, feature) {
this._clear();
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
this._setOpen(true);
this._changed();
}
_removePoint(point) {
point.marker.remove();
this._points = this._points.filter((p) => p !== point);
this._changed();
}
_clear() {
this._points.forEach((p) => p.marker.remove());
this._points = [];
this._editing = null;
this._changed();
}
_changed() {
this._renderPoints();
this._fetchRoute();
}
_renderPoints() {
this._list.innerHTML = "";
this._points.forEach((point, index) => {
const label = index === 0 ? "Start" : index === this._points.length - 1 ? "End" : `Via ${index}`;
point.marker.getElement().textContent = index === 0 ? "S" : index === this._points.length - 1 ? "E" : String(index);
const li = document.createElement("li");
const text = document.createElement("span");
text.className = "route-panel__point";
text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`;
li.append(
text,
this._pointButton("↑", "Move up", index > 0, () => this._move(point, -1)),
this._pointButton("↓", "Move down", index < this._points.length - 1, () => this._move(point, 1)),
this._pointButton("×", "Remove", true, () => this._removePoint(point)),
);
// Hover/hold previews the point; a click on its name commits.
wirePreview(this._map, text, () => ({ lngLat: point.lngLat }));
text.addEventListener("click", () => this._map.easeTo({ center: point.lngLat, zoom: Math.max(this._map.getZoom(), 14) }));
this._list.appendChild(li);
});
this._editingNote.hidden = !this._editing;
if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`;
this._saveButton.textContent = this._editing ? "Save changes" : "Save to library";
}
_pointButton(text, title, enabled, onClick) {
const button = document.createElement("button");
button.type = "button";
button.className = "route-panel__remove";
button.title = title;
button.setAttribute("aria-label", title);
button.textContent = text;
button.disabled = !enabled;
button.addEventListener("click", onClick);
return button;
}
// --- route ----------------------------------------------------------------
async _fetchRoute() {
const request = ++this._request;
this._route = null;
if (this._points.length < 2) {
this._showResult(null, "");
return;
}
this._showResult(null, "Routing…");
let data;
let error;
try {
const response = await fetch(ROUTE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat) }),
});
data = await response.json().catch(() => ({}));
if (!response.ok) error = data.error || `routing failed (${response.status})`;
} catch (err) {
error = err.message;
}
if (request !== this._request) return;
this._route = error ? null : data;
this._showResult(this._route, error ? `No route: ${error}` : "");
}
_showResult(route, message) {
this._draw();
this._saveButton.hidden = !route || !isLoggedIn();
this._directions.hidden = !route;
this._profileButton.hidden = true;
if (!route) {
this._summary.textContent = message;
return;
}
const { distance_km: km, time_s: seconds, maneuvers } = route.properties;
this._summary.textContent = `${km.toFixed(1)} km · ${formatDuration(seconds)}`;
const list = this._directions.querySelector("ol");
list.innerHTML = "";
maneuvers.forEach(({ text, km: length }) => {
const li = document.createElement("li");
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;
}
this._map.addSource(SOURCE, { type: "geojson", data });
this._map.addLayer({
id: `${SOURCE}-casing`,
type: "line",
source: SOURCE,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": "#fff", "line-width": 8 },
});
this._map.addLayer({
id: `${SOURCE}-line`,
type: "line",
source: SOURCE,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": COLOR, "line-width": 5 },
});
}
// A route item in the library ("Routes" folder), keeping its points and
// vehicle so it can be routed again later; an edited one is updated in
// place.
async _save() {
const name = window.prompt("Route name:", this._editing?.name || `Route ${new Date().toLocaleDateString()}`);
if (!name || !name.trim()) return;
const { maneuvers, ...properties } = this._route.properties;
const feature = {
type: "Feature",
geometry: this._route.geometry,
// 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, {
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(
editing
? { feature: JSON.stringify(feature), path: editing.key, id: editing.id }
: { feature: JSON.stringify(feature), folder: SAVE_FOLDER },
),
});
if (response.status === 401) {
window.location.href = "/login";
return;
}
if (!response.ok) {
window.alert("Could not save the route.");
return;
}
const path = editing ? editing.key : (await response.json()).path;
notifyGpxStoreChanged(path);
this._editing = { key: path, id: editing?.id ?? (await this._savedId(path)), name: name.trim() };
this._renderPoints();
this._summary.textContent += " · saved";
}
// The id of the route just saved, so a second Save updates it instead of
// adding another copy.
async _savedId(key) {
const { features } = await (await fetch(`/api/library/node/${encodeURIComponent(key)}`)).json();
return features.find((f) => f.geometry.type === "LineString")?.properties.id;
}
// --- vehicle --------------------------------------------------------------
// Readable by anyone, saved only when logged in; a change re-routes.
async _setupVehicle() {
const inputs = [...this._panel.querySelectorAll(".route-panel__vehicle input")];
try {
this._vehicle = await (await fetch(VEHICLE_URL)).json();
} catch {
return;
}
inputs.forEach((input) => {
input.value = this._vehicle[input.name];
input.disabled = !isLoggedIn();
input.addEventListener("change", async () => {
const body = new URLSearchParams(inputs.map((i) => [i.name, i.value]));
const response = await fetch(VEHICLE_URL, { method: "PUT", body });
const data = await response.json().catch(() => ({}));
if (!response.ok) {
window.alert(data.error || "Could not save the vehicle.");
input.value = this._vehicle[input.name];
return;
}
this._vehicle = data;
this._fetchRoute();
});
});
}
}
// 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`;
}