Files
maptool/public/js/route.js
T

617 lines
26 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, POSITION_ICON, SAVED_POINT_ICON, REVERSE_ICON, CLEAR_ICON, SAVE_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 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, 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._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());
const icons = { position: POSITION_ICON, "saved-point": SAVED_POINT_ICON, reverse: REVERSE_ICON, clear: CLEAR_ICON, save: SAVE_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);
}
_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();
// 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);
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), 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();
this._saveButton.hidden = !route || !isLoggedIn();
this._directions.hidden = !route;
this._profileButton.hidden = true;
this._showCountries(route?.properties.countries);
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",
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 },
});
}
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;
}
// "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 {
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));
}
function formatDuration(seconds) {
const minutes = Math.round(seconds / 60);
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
}