Route panel: points from search, GPS and library points, reordering, editing a saved route

This commit is contained in:
randy committed 2026-11-13 22:37:49 +01:00
1 parent 3146478c23
commit abde7fe5f9
10 files changed
+214 -25

No files matched your search

+92 -19
View File
@@ -1,6 +1,6 @@
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 { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js";
const ROUTE_URL = "/api/route";
@@ -15,11 +15,19 @@ const SAVE_FOLDER = "Routes";
// them comes from POST /api/route (Valhalla, for the stored vehicle). The
// route stays drawn after the panel closes, until Clear.
export class RoutePanelControl {
constructor(map) {
constructor(map, gnssControl) {
this._map = map;
this._points = []; // [{ lngLat: [lon, lat], marker }]
this._gnss = gnssControl;
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;
@@ -47,6 +55,8 @@ export class RoutePanelControl {
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._setupVehicle();
@@ -67,17 +77,49 @@ export class RoutePanelControl {
// --- points ---------------------------------------------------------------
_addPoint(lngLat) {
_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, marker };
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();
}
@@ -90,6 +132,7 @@ export class RoutePanelControl {
_clear() {
this._points.forEach((p) => p.marker.remove());
this._points = [];
this._editing = null;
this._changed();
}
@@ -105,16 +148,31 @@ export class RoutePanelControl {
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);
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)),
);
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 ----------------------------------------------------------------
@@ -193,9 +251,10 @@ export class RoutePanelControl {
}
// A route item in the library ("Routes" folder), keeping its points and
// vehicle so it can be routed again later.
// vehicle so it can be routed again later; an edited one is updated in
// place.
async _save() {
const name = window.prompt("Route name:", `Route ${new Date().toLocaleDateString()}`);
const name = window.prompt("Route name:", this._editing?.name || `Route ${new Date().toLocaleDateString()}`);
if (!name || !name.trim()) return;
const { maneuvers, ...properties } = this._route.properties;
@@ -204,10 +263,15 @@ export class RoutePanelControl {
geometry: this._route.geometry,
properties: { ...properties, name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
};
const editing = this._editing;
const response = await fetch(NOTES_URL, {
method: "POST",
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ feature: JSON.stringify(feature), folder: SAVE_FOLDER }),
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";
@@ -217,9 +281,18 @@ export class RoutePanelControl {
window.alert("Could not save the route.");
return;
}
const { path } = await response.json();
const path = editing ? editing.key : (await response.json()).path;
notifyGpxStoreChanged(path);
this._summary.textContent += ` · saved to "${SAVE_FOLDER}"`;
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 --------------------------------------------------------------