Route panel: points from search, GPS and library points, reordering, editing a saved route
This commit is contained in:
1 parent
3146478c23
commit
abde7fe5f9
10 files changed
+214
-25
No files matched your search
@@ -87,7 +87,7 @@ Deprioritized for now — revisit after the sections above land.
|
||||
* [ ] Offline routing with vehicle parameters (height, weight, width) — Valhalla in its own container, design in `docs/routing-design.adoc`
|
||||
** [x] Phase 1: `valhalla` compose service (`bin/routing-service.sh`), builds from the offline map's extracts, "Offline routing" row in the Offline data panel
|
||||
** [x] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
|
||||
** [ ] Route points from search / GPS / a library point, reordering, re-editing a saved route
|
||||
** [x] Route points from search / GPS / a library point, reordering, re-editing a saved route
|
||||
** [ ] Phase 3: elevation profile from terrain.pmtiles, isochrones
|
||||
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
|
||||
|
||||
|
||||
@@ -144,8 +144,13 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
|
||||
the "Routes" folder through the notes endpoint, with its points (`via`)
|
||||
and vehicle in `properties`. That way it goes to OsmAnd/Locus through
|
||||
the same export as everything else.
|
||||
* Not yet: adding a point from search, GPS or a library point; reordering
|
||||
points; editing a saved route again.
|
||||
* Points also come from "+" on a search result, "Add to route" in a
|
||||
library point's popup, or "+ My position" (the GNSS fix, else the
|
||||
browser's position). These go through events in `panels.js`, the same
|
||||
way the library refresh does. ↑/↓ reorder points.
|
||||
* "Edit route" in a saved route's menu in the tree loads its points
|
||||
back. Save then updates that item instead of adding a copy. A route
|
||||
imported from GPX has no `via`, so it can't be edited this way.
|
||||
|
||||
== Phases
|
||||
|
||||
|
||||
@@ -2352,3 +2352,42 @@ html, body {
|
||||
text-align: center;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.route-panel__remove:disabled {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.route-panel__point {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.route-panel__editing {
|
||||
margin: 0 0 8px;
|
||||
color: #1d6fdc;
|
||||
}
|
||||
|
||||
.route-panel__editing[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.search-panel__route,
|
||||
.gpx-popup__route {
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
background: #fff;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.search-panel__route {
|
||||
float: right;
|
||||
margin-left: 6px;
|
||||
padding: 0 6px;
|
||||
}
|
||||
|
||||
.gpx-popup__route {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
padding: 3px 8px;
|
||||
}
|
||||
+25
-1
@@ -11,7 +11,7 @@ import {
|
||||
POI_ICONS,
|
||||
PARK4NIGHT_TAGS,
|
||||
} from "/js/icons.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpxStoreChanged } from "/js/panels.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpxStoreChanged, addRoutePoint, editRoute } from "/js/panels.js";
|
||||
import { formatActivityType } from "/js/track_profile.js";
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
|
||||
@@ -366,6 +366,7 @@ export class GpxPanelControl {
|
||||
{ label: "Color…", run: () => this._pickColor(file) },
|
||||
file.color && { label: "Default color", run: () => this._patchNode(file.path, { color: "" }) },
|
||||
file.layer && { label: "Split into items", run: () => this._splitLayer(file) },
|
||||
(file.kinds || []).includes("route") && { label: "Edit route", run: () => this._editRoute(file) },
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -757,6 +758,17 @@ export class GpxPanelControl {
|
||||
.setHTML(popupHtml(feature.properties, { editable }))
|
||||
.addTo(this._map);
|
||||
if (editable) this._wireNoteActions(popup, path, feature);
|
||||
if (feature.geometry.type === "Point") {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "gpx-popup__route";
|
||||
button.textContent = "Add to route";
|
||||
button.addEventListener("click", () => {
|
||||
addRoutePoint(feature.geometry.coordinates, feature.properties.name);
|
||||
popup.remove();
|
||||
});
|
||||
popup.getElement().querySelector(".maplibregl-popup-content").appendChild(button);
|
||||
}
|
||||
}
|
||||
|
||||
// Edit swaps the popup's content for a plain textarea + Save/Cancel (the
|
||||
@@ -1123,6 +1135,18 @@ export class GpxPanelControl {
|
||||
}
|
||||
}
|
||||
|
||||
// A route saved from the route panel keeps its points (properties.via);
|
||||
// one without them (an imported GPX route) can't be re-routed.
|
||||
async _editRoute(file) {
|
||||
const { features } = await (await fetch(gpxFileUrl(file.path))).json();
|
||||
const route = features.find((f) => f.geometry.type === "LineString" && Array.isArray(f.properties.via));
|
||||
if (!route) {
|
||||
window.alert("This route has no saved route points, so it can't be edited.");
|
||||
return;
|
||||
}
|
||||
editRoute(file.path, route);
|
||||
}
|
||||
|
||||
async _splitLayer(file) {
|
||||
if (!window.confirm(`Split "${file.name}" into separate points and tracks? This can't be undone.`)) return;
|
||||
|
||||
|
||||
+1
-1
@@ -585,7 +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 RoutePanelControl(map, gnssControl).mount(sidebar);
|
||||
new OfflineDataControl().mount(sidebar);
|
||||
|
||||
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`);
|
||||
|
||||
@@ -31,3 +31,25 @@ export function notifyGpxStoreChanged(path) {
|
||||
export function onGpxStoreChanged(callback) {
|
||||
document.addEventListener(STORE_CHANGED_EVENT, (event) => callback(event.detail));
|
||||
}
|
||||
|
||||
// Anything with a location (a search result, a library point) hands it to
|
||||
// the route panel (route.js) the same decoupled way.
|
||||
const ROUTE_POINT_EVENT = "route-point";
|
||||
const ROUTE_EDIT_EVENT = "route-edit";
|
||||
|
||||
export function addRoutePoint(lngLat, name) {
|
||||
document.dispatchEvent(new CustomEvent(ROUTE_POINT_EVENT, { detail: { lngLat, name } }));
|
||||
}
|
||||
|
||||
export function onRoutePoint(callback) {
|
||||
document.addEventListener(ROUTE_POINT_EVENT, (event) => callback(event.detail));
|
||||
}
|
||||
|
||||
// A saved route (its library node key and feature) back into the panel.
|
||||
export function editRoute(key, feature) {
|
||||
document.dispatchEvent(new CustomEvent(ROUTE_EDIT_EVENT, { detail: { key, feature } }));
|
||||
}
|
||||
|
||||
export function onRouteEdit(callback) {
|
||||
document.addEventListener(ROUTE_EDIT_EVENT, (event) => callback(event.detail));
|
||||
}
|
||||
+92
-19
@@ -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 --------------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { SEARCH_ICON } from "/js/icons.js";
|
||||
import { escapeHtml } from "/js/gpx.js";
|
||||
import { addRoutePoint } from "/js/panels.js";
|
||||
|
||||
const NOMINATIM_API = "https://nominatim.openstreetmap.org/search";
|
||||
// "lat, lng" / "lat lng" decimal degrees — the same plain-text shape the
|
||||
@@ -208,6 +209,7 @@ export class SearchControl {
|
||||
result.status
|
||||
? `<li class="search-panel__status">${escapeHtml(result.status)}</li>`
|
||||
: `<li class="search-panel__result" data-index="${i}">
|
||||
${result.lat != null || result.bbox ? `<button type="button" class="search-panel__route" title="Add to route" aria-label="Add to route">+</button>` : ""}
|
||||
${escapeHtml(result.name)}
|
||||
<span class="search-panel__where">${escapeHtml(
|
||||
[result.where, result.distanceKm != null && formatKm(result.distanceKm)].filter(Boolean).join(" · "),
|
||||
@@ -215,6 +217,13 @@ export class SearchControl {
|
||||
</li>`,
|
||||
)
|
||||
.join("") + tail;
|
||||
this._resultsEl.querySelectorAll(".search-panel__route").forEach((button) => {
|
||||
button.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
const { lat, lng, bbox, name } = this._results[Number(button.closest("li").dataset.index)];
|
||||
addRoutePoint(lat != null ? [lng, lat] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], name);
|
||||
});
|
||||
});
|
||||
this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => {
|
||||
el.addEventListener("click", () => {
|
||||
const result = this._results[Number(el.dataset.index)];
|
||||
|
||||
@@ -130,6 +130,21 @@ class LibraryTest < Minitest::Test
|
||||
assert_raises(Maptool::Library::InvalidValue) { library.move_folder("c/x", "a") }
|
||||
end
|
||||
|
||||
def test_a_saved_route_is_a_route_node_and_editing_replaces_it
|
||||
route = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => [[17.1, 48.1], [17.2, 48.2]] },
|
||||
"properties" => { "name" => "To the lake", "kind" => "route", "via" => [[17.1, 48.1], [17.2, 48.2]] } }
|
||||
library = open_library
|
||||
key = library.add_note(route, "Routes")
|
||||
node = library.tree["children"].first["children"].first
|
||||
assert_equal [key, ["route"]], node.values_at("path", "kinds")
|
||||
|
||||
id = JSON.parse(library.geojson(key))["features"].first["properties"]["id"]
|
||||
edited = route.merge("properties" => route["properties"].merge("name" => "Lake, scenic", "via" => [[17.1, 48.1], [17.15, 48.3], [17.2, 48.2]]))
|
||||
library.update_feature(key, id, edited)
|
||||
features = JSON.parse(library.geojson(key))["features"]
|
||||
assert_equal [["Lake, scenic", 3]], features.map { |f| [f["properties"]["name"], f["properties"]["via"].size] }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def open_library
|
||||
|
||||
+3
-1
@@ -111,9 +111,11 @@
|
||||
</div>
|
||||
<!-- Filled by RoutePanelControl (public/js/route.js). -->
|
||||
<div class="route-panel__body">
|
||||
<p class="route-panel__hint">Click the map to add points; drag a marker to move it.</p>
|
||||
<p class="route-panel__hint">Click the map to add points (or "Add to route" on a search result or a library point); drag a marker to move it.</p>
|
||||
<p class="route-panel__editing" hidden></p>
|
||||
<ol class="route-panel__points"></ol>
|
||||
<div class="route-panel__buttons">
|
||||
<button type="button" data-action="position">+ My position</button>
|
||||
<button type="button" data-action="reverse">Reverse</button>
|
||||
<button type="button" data-action="clear">Clear</button>
|
||||
<button type="button" data-action="save" hidden>Save to library</button>
|
||||
|
||||
Reference in new issue
Block a user