Files
maptool/public/js/route.js
T

927 lines
40 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, REVERSE_ICON, CLEAR_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute, onRouteProgress } 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";
// Logged in, the panel edits this server's shared trip (lib/maptool/trip.rb)
// instead of a route of its own: every change goes there (routed by the
// server), and other screens' changes come in by polling — the points,
// vehicle, avoids and route swapped in, the camera left where it is.
const TRIP_URL = "/api/trip";
const TRIP_POLL_MS = 2000;
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 VEHICLES_URL = "/api/vehicles";
const VEHICLE_KEY = "maptool.routeVehicle";
const AVOID_KEY = "maptool.routeAvoid";
// Motorways paid by a time-based vignette rather than per section. Not
// reliably tagged as toll in OSM, so every motorway km there counts.
const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]);
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, nav, marker }]; nav: saved as a point the device shows
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
this._version = -1; // the shared trip's, -1: not loaded yet
this._pushing = 0; // PUTs in flight: polls wait for them
// Rerouting (the dashboard, off the route): the start and the via points
// already passed give way to the current position.
onReroute(({ from, passed }) => {
// the shared trip is rerouted by the server, off its own GNSS (TripStore#follow)
if (this._shared || this._active().length < 2) return;
const reached = this._active().slice(0, 1 + passed);
if (reached[0]?.name === "My position") this._removePoint(reached.shift(), { quiet: true });
reached.forEach((p) => this._setPassed(p, true));
this._addPoint(from, "My position", { quiet: true });
const position = this._points.pop();
const next = this._points.findIndex((p) => !p.passed);
this._points.splice(next < 0 ? this._points.length : next, 0, position);
this._changed();
});
onRouteProgress((km) => {
this._showProgress(km);
this._progressKm = km;
this._stopListeners?.forEach((callback) => callback());
});
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._countries = this._panel.querySelector(".route-panel__countries");
this._setupAvoid();
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._panel.querySelector('[data-action="search"]').addEventListener("click", () => document.querySelector(".search-panel__input")?.focus());
this._totals = this._panel.querySelector(".route-panel__totals");
const icons = { reverse: REVERSE_ICON, clear: CLEAR_ICON };
for (const [action, icon] of Object.entries(icons)) this._panel.querySelector(`[data-action="${action}"]`).insertAdjacentHTML("afterbegin", icon);
this._setupSavedPoints();
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);
this._shared = isLoggedIn();
if (this._shared) {
this._pollTrip();
setInterval(() => this._pollTrip(), TRIP_POLL_MS);
}
}
// --- shared trip ------------------------------------------------------------
async _pollTrip() {
if (this._pushing) return;
try {
const response = await fetch(`${TRIP_URL}?version=${this._version}`, { cache: "no-store" });
if (response.status !== 200) return; // 204: unchanged
const trip = await response.json();
if (!this._pushing && trip.version > this._version) this._applyTrip(trip, true);
} catch {
// offline for a moment: the next poll
}
}
async _pushTrip() {
const request = ++this._request;
this._pushing++;
// the old route stays on the map (the driver's view) until the new one is in
if (this._points.length >= 2) this._summary.textContent = "Routing…";
try {
const response = await fetch(TRIP_URL, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
points: this._points.map(({ lngLat, name, nav, passed }) => ({ lngLat, name, nav, passed })),
vehicle: this._vehicleId,
avoid: this._avoid,
editing: this._editing,
}),
});
const trip = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(trip.error || `HTTP ${response.status}`);
if (request === this._request) this._applyTrip(trip, false);
} catch (err) {
if (request === this._request) this._showResult(null, `Not saved: ${err.message}`);
} finally {
this._pushing--;
}
}
// The server's trip into the panel: its route always, its points (and
// vehicle, avoids, the library route being edited) when they came from
// another screen.
_applyTrip(trip, fromElsewhere) {
this._version = trip.version;
if (fromElsewhere) {
this._points.forEach((p) => p.marker.remove());
this._points = [];
trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav, passed: !!p.passed }));
this._editing = trip.editing;
this._avoid = { ...trip.avoid };
this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => (input.checked = !!this._avoid[input.name]));
if (trip.vehicle && trip.vehicle !== this._vehicleId) {
if (this._selectVehicle) this._selectVehicle(trip.vehicle);
else this._vehicleId = trip.vehicle;
}
this._renderPoints();
}
this._route = trip.route;
this._showResult(trip.route, trip.error ? `No route: ${trip.error}` : "");
}
_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 ---------------------------------------------------------------
// A named place (a saved point, a search result) is shown in navigation
// by default; a plain map click only shapes the route.
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = 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, nav, marker };
this._setPassed(point, passed);
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();
// Back to the vehicle it was planned for, if that profile still exists.
if (this._vehicles?.some((v) => v.id === feature.properties.vehicle?.id)) this._selectVehicle(feature.properties.vehicle.id);
const named = feature.properties.via_points || [];
feature.properties.via.forEach((lngLat, i) => this._addPoint(lngLat, named[i]?.name || null, { quiet: true, nav: !!named[i]?.nav }));
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
this._setOpen(true);
this._changed();
}
// For the driving mode's Trip menu (driving.js): the stops, and editing
// them by index — the same points the panel edits, so the shared trip,
// routing and markers follow as from the panel.
// passed: marked (by a reroute or by hand) — not routed — or behind the
// car by the dashboard's progress along the route; both shown dimmed.
stops() {
return this._points.map((p, i) => ({ name: p.name, lngLat: p.lngLat, label: i === 0 ? "Start" : i === this._points.length - 1 ? "End" : `Via ${i}`,
leg: this._leg(i), passed: p.passed, behind: this._behind(i) }));
}
togglePassed(index) {
const point = this._points[index];
if (!point) return;
this._setPassed(point, !point.passed);
this._changed();
}
_setPassed(point, passed) {
point.passed = !!passed;
point.marker.getElement().classList.toggle("route-marker--passed", point.passed);
}
// The points routed: the ones not passed.
_active() {
return this._points.filter((p) => !p.passed);
}
// The way to point i from the routed one before: { km, s } of the route's
// leg, null for the first routed point, a passed one, or while the route
// doesn't match the points (routing).
_leg(i) {
const { legs_km: km, legs_s: s } = this._route?.properties || {};
const active = this._active();
const at = active.indexOf(this._points[i]);
if (at < 1 || !km || km.length !== active.length - 1) return null;
return { km: km[at - 1], s: s?.[at - 1] };
}
// Behind the car: the dashboard's km along the route past this point's.
_behind(i) {
if (this._progressKm == null || this._points[i]?.passed) return false;
const { legs_km: km } = this._route?.properties || {};
const active = this._active();
const at = active.indexOf(this._points[i]);
if (at < 0 || !km || km.length !== active.length - 1) return false;
return km.slice(0, at).reduce((sum, length) => sum + length, 0) <= this._progressKm + 0.03;
}
onStopsChanged(callback) {
(this._stopListeners ??= []).push(callback);
}
moveStop(index, step) {
if (this._points[index]) this._move(this._points[index], step);
}
removeStop(index) {
if (this._points[index]) this._removePoint(this._points[index]);
}
// A stop before the end (the trip goes on to where it was going), or the
// end itself while there's no route yet.
addStop(lngLat, name = null) {
this._addPoint(lngLat, name, { quiet: true });
if (this._points.length > 2) this._points.splice(this._points.length - 2, 0, this._points.pop());
this._changed();
}
// The start moved to where the car is (GNSS, else the browser's position).
startHere() {
const set = (lngLat) => {
if (this._points[0]?.name === "My position") this._removePoint(this._points[0]);
this._addPoint(lngLat, "My position", { quiet: true });
this._points.unshift(this._points.pop());
this._changed();
};
const fix = this._gnss?.getPosition();
if (fix) return set([fix.lng, fix.lat]);
navigator.geolocation.getCurrentPosition((p) => set([p.coords.longitude, p.coords.latitude]), () => window.alert("Could not determine your location."), { enableHighAccuracy: true });
}
_removePoint(point, { quiet = false } = {}) {
point.marker.remove();
this._points = this._points.filter((p) => p !== point);
if (!quiet) this._changed();
}
_clear() {
this._points.forEach((p) => p.marker.remove());
this._points = [];
this._editing = null;
this._changed();
}
_changed() {
this._renderPoints();
this._fetchRoute();
}
// The Desktop artboard's list: a grip to drag the point to another place,
// its letter (the same on its marker), name and role, then the leg to the
// next one as a dashed line between them.
_renderPoints() {
this._list.innerHTML = "";
const last = this._points.length - 1;
this._points.forEach((point, index) => {
const letter = String.fromCharCode(65 + (index % 26));
const role = index === 0 ? "Start" : index === last ? "End" : `Via ${index}`;
point.marker.getElement().textContent = letter;
const leg = this._leg(index);
if (leg) {
this._list.appendChild(Object.assign(document.createElement("li"), {
className: "route-panel__leg",
textContent: `${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}`,
}));
}
const li = document.createElement("li");
li.className = "route-panel__stop";
li.classList.toggle("route-panel__passed", !!point.passed || this._behind(index));
const grip = Object.assign(document.createElement("span"), { className: "route-panel__grip", textContent: "⋮⋮", title: "Drag to reorder" });
li.draggable = true;
li.addEventListener("dragstart", (event) => {
this._dragging = point;
event.dataTransfer.effectAllowed = "move";
li.classList.add("route-panel__dragging");
});
li.addEventListener("dragend", () => li.classList.remove("route-panel__dragging"));
li.addEventListener("dragover", (event) => event.preventDefault());
li.addEventListener("drop", (event) => {
event.preventDefault();
const from = this._points.indexOf(this._dragging);
this._dragging = null;
if (from < 0 || from === index) return;
this._points.splice(index, 0, ...this._points.splice(from, 1));
this._changed();
});
const badge = Object.assign(document.createElement("span"), { className: "route-panel__badge", textContent: letter });
badge.classList.toggle("route-panel__badge--end", index === last && last > 0);
const text = document.createElement("span");
text.className = "route-panel__point";
text.append(
Object.assign(document.createElement("span"), { className: "route-panel__name", textContent: point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}` }),
Object.assign(document.createElement("small"), { className: "route-panel__role", textContent: role }),
);
li.append(grip, badge, text, this._navButton(point, role), 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._stopListeners?.forEach((callback) => callback());
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";
}
// The totals card: distance, time, climb (once the terrain's sampled),
// arrival if leaving now.
_renderTotals(route) {
this._totals.hidden = !route;
if (!route) return;
const { distance_km: km, time_s: seconds } = route.properties;
const arrive = new Date(Date.now() + seconds * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const cells = [
[`${km.toFixed(km < 10 ? 1 : 0)} km`, "distance"],
[formatDuration(seconds), "time"],
[route.elevation ? `${Math.round(route.elevation.gain)} m` : "…", "climb"],
[arrive, "arrive"],
];
this._totals.innerHTML = cells.map(([value, key]) => `<span><b>${value}</b><small>${key}</small></span>`).join("");
if (route.elevation) {
this._totals.insertAdjacentHTML("beforeend", `<span class="route-panel__totals-more">↓ ${Math.round(route.elevation.loss)} m · steepest ${route.elevation.maxGrade.toFixed(0)} %</span>`);
}
}
// Toggles whether the point is saved into the route as a navigation
// point (a course point on a Garmin); an unnamed one asks for a name.
_navButton(point, label) {
const button = this._pointButton("📍", "Show in navigation", true, () => {
if (!point.nav && !point.name) {
const name = window.prompt("Name shown in navigation:", label);
if (!name?.trim()) return;
point.name = name.trim();
}
point.nav = !point.nav;
this._renderPoints();
if (this._shared) this._pushTrip(); // the server keeps the route, only the flag changes
});
button.classList.add("route-panel__nav");
button.classList.toggle("active", !!point.nav);
button.setAttribute("aria-pressed", !!point.nav);
return button;
}
_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() {
if (this._shared) return this._pushTrip();
const request = ++this._request;
this._route = null;
if (this._active().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._active().map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
});
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();
notifyRouteChanged(route);
this._renderPoints(); // the legs' km and time next to the points (the Trip menu's too)
this._saveButton.hidden = !route || !isLoggedIn();
this._directions.hidden = !route;
this._profileButton.hidden = true;
this._showCountries(route?.properties.countries);
this._renderTotals(route);
this._summary.textContent = message;
if (!route) return;
const { maneuvers } = route.properties;
this._directions.querySelector(".route-panel__fold-meta").textContent = `${maneuvers.length} steps`;
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._renderTotals(route);
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",
vehicle_type: this._vehicle?.type || "car", // picks the default split length
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, vehicle: this._vehicleId, avoid: this._avoid }),
});
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 },
});
}
// the traffic signals on it as points next to the line
const signals = (this._route?.properties.signals || []).map(([lon, lat]) => ({ type: "Feature", geometry: { type: "Point", coordinates: [lon, lat] }, properties: {} }));
const data = { type: "FeatureCollection", features: this._route ? [this._route, ...signals] : [] };
const source = this._map.getSource(SOURCE);
if (source) {
source.setData(data);
return;
}
this._map.addSource(SOURCE, { type: "geojson", data, lineMetrics: true }); // line-progress for _showProgress
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 },
});
this._map.addLayer({
id: `${SOURCE}-signals`,
type: "circle",
source: SOURCE,
minzoom: 14,
filter: ["==", ["geometry-type"], "Point"],
paint: { "circle-radius": 5, "circle-color": "#222", "circle-stroke-color": "#f9a825", "circle-stroke-width": 2.5 },
});
}
// Navigated (km along the route, docs/design.adoc): the driven part
// dimmed, the rest magenta (--route-active); null: the planned blue.
_showProgress(km) {
if (!this._map.getLayer(`${SOURCE}-line`)) return;
const total = this._route?.properties.distance_km;
if (km == null || !total) {
this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient", undefined);
return;
}
const css = getComputedStyle(document.documentElement);
const active = css.getPropertyValue("--route-active").trim() || "#a21caf";
const driven = css.getPropertyValue("--ui-muted").trim() || "#6b6b66";
const fraction = Math.min(1, Math.max(0, km / total));
this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient",
fraction > 0 ? ["step", ["line-progress"], driven, fraction, active] : ["step", ["line-progress"], active, 1, active]);
}
// 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, speed_limits: _limits, signals: _signals, ...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),
via_points: this._points.map((p) => ({ name: p.name || null, nav: !!p.nav, passed: !!p.passed })),
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;
await this._saveNavPoints(path);
notifyGpxStoreChanged(path);
this._editing = { key: path, id: editing?.id ?? (await this._savedId(path)), name: name.trim() };
this._renderPoints();
this._summary.textContent = "Saved to the library";
}
// The route's points marked 📍 as points inside the route item (marked
// from_route, so points added to it by hand stay untouched): missing
// ones added, unmarked or moved ones removed.
async _saveNavPoints(key) {
const url = `/api/library/node/${encodeURIComponent(key)}`;
const id = (p) => `${p.lngLat[0].toFixed(6)},${p.lngLat[1].toFixed(6)},${p.name}`;
const { features } = await (await fetch(url)).json();
const existing = new Map(features.filter((f) => f.geometry.type === "Point" && f.properties.from_route).map((f) => [id({ lngLat: f.geometry.coordinates, name: f.properties.name }), f]));
const wanted = this._points.map((p, i) => ({ ...p, name: p.name || `Via ${i}` })).filter((p) => p.nav);
const wantedIds = new Set(wanted.map(id));
for (const [key2, f] of existing) {
if (!wantedIds.has(key2)) await fetch(`/api/library/notes?${new URLSearchParams({ path: key, id: f.properties.id })}`, { method: "DELETE" });
}
for (const p of wanted) {
if (existing.has(id(p))) continue;
const feature = { type: "Feature", geometry: { type: "Point", coordinates: p.lngLat }, properties: { name: p.name, from_route: true } };
await fetch(`${url}/points`, { method: "POST", body: new URLSearchParams({ feature: JSON.stringify(feature) }) });
}
}
// 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;
}
// "Saved point": a search over the library's points (GET /api/search,
// the "layers" source, nearest the map center first); a pick adds it.
_setupSavedPoints() {
const box = this._panel.querySelector(".route-panel__saved");
const input = box.querySelector("input");
const list = box.querySelector("ul");
let timer = null;
let request = 0;
this._panel.querySelector('[data-action="saved-point"]').addEventListener("click", () => {
box.hidden = !box.hidden;
if (!box.hidden) input.focus();
});
input.addEventListener("input", () => {
clearTimeout(timer);
timer = setTimeout(async () => {
const mine = ++request;
const center = this._map.getCenter();
const url = new URL("/api/search", window.location.origin);
url.search = new URLSearchParams({ q: input.value, sources: "layers", lat: center.lat, lng: center.lng });
let results = [];
try {
if (input.value.trim()) results = (await (await fetch(url)).json()).results;
} catch {}
if (mine !== request) return;
const points = results.filter(({ bbox }) => bbox && bbox[0] === bbox[2] && bbox[1] === bbox[3]);
list.replaceChildren(
...points.map(({ name, bbox, source_label: folder }) => {
const item = document.createElement("li");
const button = Object.assign(document.createElement("button"), { type: "button", textContent: name, title: folder });
button.addEventListener("click", () => {
this._addPoint(bbox.slice(0, 2), name);
box.hidden = true;
input.value = "";
list.replaceChildren();
});
item.appendChild(button);
return item;
}),
);
if (!points.length && input.value.trim()) list.replaceChildren(Object.assign(document.createElement("li"), { textContent: "No saved points found." }));
}, 250);
});
}
// Where the route needs a vignette or pays tolls, country by country.
_showCountries(countries) {
const rows = (countries || []).flatMap(({ code, motorway_km: motorway, toll_km: toll }) => {
if (VIGNETTE_COUNTRIES.has(code) && motorway > 0) {
return [`${code}: vignette, ${motorway.toFixed(0)} km motorway${toll > 0 ? ` (${toll.toFixed(0)} km tolled)` : ""}`];
}
return toll > 0 ? [`${code}: toll, ${toll.toFixed(0)} km`] : [];
});
this._countries.replaceChildren(...rows.map((text) => Object.assign(document.createElement("li"), { textContent: text })));
this._countries.hidden = rows.length === 0;
}
// Avoid tolls / motorways for the whole route; this browser's choice.
_setupAvoid() {
try {
this._avoid = JSON.parse(localStorage.getItem(AVOID_KEY)) || {};
} catch {
this._avoid = {};
}
this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => {
input.checked = Boolean(this._avoid[input.name]);
input.addEventListener("change", () => {
this._avoid[input.name] = input.checked;
try {
localStorage.setItem(AVOID_KEY, JSON.stringify(this._avoid));
} catch {}
this._fetchRoute();
});
});
}
// --- vehicle --------------------------------------------------------------
// Profiles (Car, Camper, ...) are shared and edited only when logged in;
// which one is in use is this browser's own choice. A change re-routes.
async _setupVehicle() {
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, select")];
const avoidRow = this._panel.querySelector(".route-panel__avoid");
try {
this._vehicles = await (await fetch(VEHICLES_URL)).json();
} catch {
return;
}
const current = () => this._vehicles.find((v) => v.id === this._vehicleId) || this._vehicles[0];
const fill = () => {
select.replaceChildren(...this._vehicles.map((v) => new Option(v.name, v.id)));
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;
try {
localStorage.setItem(VEHICLE_KEY, id);
} catch {}
fill();
};
const save = async () => {
const response = await fetch(VEHICLES_URL, { method: "PUT", body: JSON.stringify(this._vehicles) });
const data = await response.json().catch(() => ({}));
if (response.ok) {
this._vehicles = data;
} else {
window.alert(data.error || "Could not save the vehicles.");
this._vehicles = await (await fetch(VEHICLES_URL)).json();
}
fill();
this._fetchRoute();
};
try {
// the shared trip's vehicle, when it came in before the vehicles did
this._vehicleId = this._version >= 0 && this._vehicleId ? this._vehicleId : localStorage.getItem(VEHICLE_KEY);
} catch {}
fill();
select.addEventListener("change", () => {
this._selectVehicle(select.value);
this._fetchRoute();
});
editButton.hidden = !isLoggedIn();
editButton.addEventListener("click", () => (fieldset.hidden = !fieldset.hidden));
inputs.forEach((input) =>
input.addEventListener("change", () => {
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();
}),
);
fieldset.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => {
const id = `v${Date.now().toString(36)}`;
this._vehicles.push({ ...current(), id, name: "New vehicle" });
this._selectVehicle(id);
save();
});
fieldset.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => {
if (this._vehicles.length < 2 || !window.confirm(`Delete the vehicle "${current().name}"?`)) return;
this._vehicles = this._vehicles.filter((v) => v !== current());
this._selectVehicle(this._vehicles[0].id);
save();
});
}
}
// 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));
}
export function formatDuration(seconds) {
const minutes = Math.round(seconds / 60);
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
}