Offline routing phase 2: route panel, /api/route via Valhalla, vehicle profile, save a route to the library
This commit is contained in:
1 parent
d93c77727f
commit
3146478c23
11 files changed
+577
-12
No files matched your search
@@ -2256,3 +2256,99 @@ html, body {
|
||||
white-space: normal;
|
||||
max-width: 200px;
|
||||
}
|
||||
|
||||
/* Route panel (public/js/route.js) */
|
||||
.route-panel__body {
|
||||
padding: 10px 12px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.route-panel__hint,
|
||||
.route-panel__summary {
|
||||
margin: 0 0 8px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.route-panel__summary {
|
||||
color: #222;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.route-panel__points {
|
||||
margin: 0 0 8px;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.route-panel__points li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 3px 0;
|
||||
}
|
||||
|
||||
.route-panel__remove {
|
||||
border: none;
|
||||
background: none;
|
||||
color: #999;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.route-panel__remove:hover {
|
||||
color: #e63946;
|
||||
}
|
||||
|
||||
.route-panel__buttons {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.route-panel__buttons button {
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
background: #fff;
|
||||
padding: 4px 8px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.route-panel__buttons button[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.route-panel__directions {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.route-panel__directions ol {
|
||||
margin: 6px 0 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.route-panel__vehicle {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 6px;
|
||||
border: 1px solid #eee;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.route-panel__vehicle input {
|
||||
width: 4.5em;
|
||||
}
|
||||
|
||||
.route-marker {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
background: #1d6fdc;
|
||||
border: 2px solid #fff;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
|
||||
color: #fff;
|
||||
font: 600 11px/22px sans-serif;
|
||||
text-align: center;
|
||||
cursor: grab;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { PluginsControl } from "/js/plugins.js";
|
||||
import { LocateControl } from "/js/locate.js";
|
||||
import { SearchControl } from "/js/search.js";
|
||||
import { OfflineDataControl } from "/js/offline_data.js";
|
||||
import { RoutePanelControl } from "/js/route.js";
|
||||
import { LAYERS_ICON, WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON } from "/js/icons.js";
|
||||
import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
|
||||
@@ -584,6 +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).mount(sidebar);
|
||||
new OfflineDataControl().mount(sidebar);
|
||||
|
||||
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`);
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { ROUTE_ICON } from "/js/icons.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged } from "/js/panels.js";
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
|
||||
const ROUTE_URL = "/api/route";
|
||||
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) {
|
||||
this._map = map;
|
||||
this._points = []; // [{ lngLat: [lon, lat], marker }]
|
||||
this._route = null; // the last /api/route Feature
|
||||
this._request = 0; // so a slow older response can't overwrite a newer one
|
||||
|
||||
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._saveButton.addEventListener("click", () => this._save());
|
||||
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) {
|
||||
const element = document.createElement("div");
|
||||
element.className = "route-marker";
|
||||
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
|
||||
const point = { lngLat, marker };
|
||||
marker.on("dragend", () => {
|
||||
const { lng, lat } = marker.getLngLat();
|
||||
point.lngLat = [lng, lat];
|
||||
this._changed();
|
||||
});
|
||||
this._points.push(point);
|
||||
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._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.textContent = `${label} · ${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`;
|
||||
const remove = document.createElement("button");
|
||||
remove.type = "button";
|
||||
remove.className = "route-panel__remove";
|
||||
remove.title = "Remove";
|
||||
remove.textContent = "×";
|
||||
remove.addEventListener("click", () => this._removePoint(point));
|
||||
li.append(text, remove);
|
||||
this._list.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
// --- 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;
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
_draw() {
|
||||
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`,
|
||||
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.
|
||||
async _save() {
|
||||
const name = window.prompt("Route name:", `Route ${new Date().toLocaleDateString()}`);
|
||||
if (!name || !name.trim()) return;
|
||||
|
||||
const { maneuvers, ...properties } = this._route.properties;
|
||||
const feature = {
|
||||
type: "Feature",
|
||||
geometry: this._route.geometry,
|
||||
properties: { ...properties, name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
|
||||
};
|
||||
const response = await fetch(NOTES_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ 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 } = await response.json();
|
||||
notifyGpxStoreChanged(path);
|
||||
this._summary.textContent += ` · saved to "${SAVE_FOLDER}"`;
|
||||
}
|
||||
|
||||
// --- 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();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function formatDuration(seconds) {
|
||||
const minutes = Math.round(seconds / 60);
|
||||
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
|
||||
}
|
||||
Reference in new issue
Block a user