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
@@ -86,7 +86,8 @@ 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
|
||||
** [ ] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
|
||||
** [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
|
||||
** [ ] Phase 3: elevation profile from terrain.pmtiles, isochrones
|
||||
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
|
||||
|
||||
|
||||
@@ -447,6 +447,33 @@ module Maptool
|
||||
json Routing.build_status(DATA_DIR)
|
||||
end
|
||||
|
||||
# A route through the posted points ({"locations": [[lon, lat], ...]})
|
||||
# for the stored vehicle. Open to anyone, like viewing the map; only
|
||||
# saving it to the library needs a login.
|
||||
post "/api/route" do
|
||||
locations = JSON.parse(request.body.read)["locations"]
|
||||
halt 400, json(error: "locations must be a list of [lon, lat]") unless locations.is_a?(Array) && locations.all?(Array)
|
||||
|
||||
json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR))
|
||||
rescue JSON::ParserError
|
||||
halt 400, json(error: "invalid JSON")
|
||||
rescue Routing::RouteError => e
|
||||
halt 422, json(error: e.message)
|
||||
rescue Routing::Unavailable => e
|
||||
halt 503, json(error: e.message)
|
||||
end
|
||||
|
||||
get "/api/vehicle" do
|
||||
json Routing.vehicle(DATA_DIR)
|
||||
end
|
||||
|
||||
put "/api/vehicle" do
|
||||
require_login!
|
||||
json Routing.save_vehicle(DATA_DIR, params)
|
||||
rescue ArgumentError, KeyError => e
|
||||
halt 400, json(error: e.message)
|
||||
end
|
||||
|
||||
# Same reasoning as DELETE /api/offline-tiles above.
|
||||
delete "/api/terrain-tiles" do
|
||||
require_login!
|
||||
|
||||
+19
-11
@@ -2,7 +2,7 @@
|
||||
:toc:
|
||||
:toclevels: 1
|
||||
|
||||
Status: *phase 1 implemented* (the container, builds, status in the Offline data panel); phases 2–3 proposed.
|
||||
Status: *phases 1–2 implemented* (the container and builds; the route panel, vehicle profile and saving a route); phase 3 proposed.
|
||||
|
||||
== Goal
|
||||
|
||||
@@ -128,16 +128,24 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
|
||||
three. A routing request made while the offline map is still
|
||||
downloading extracts waits for it (`Routing.offline_build_finished`).
|
||||
The row says whether the service answers.
|
||||
* `POST /api/route` proxies to Valhalla `/route` with `costing: truck`
|
||||
and the vehicle profile filled in. It's open to everyone, like the
|
||||
map. Login is required only to save the result.
|
||||
* Vehicle profile: height, width, length, weight. Stored server-side,
|
||||
one for now, editable in the route panel.
|
||||
* Route panel: start, end and via points (map click, search result, GPS
|
||||
position, a library point), the route drawn with distance, time and
|
||||
turn list. "Save to library" stores it as a `route` item, so the
|
||||
route goes to OsmAnd/Locus through the same export as everything
|
||||
else.
|
||||
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
|
||||
Valhalla `/route` and returns the route as a GeoJSON line with
|
||||
distance, time and turn instructions. It's open to everyone, like the
|
||||
map; only saving needs a login. The costing depends on the weight:
|
||||
up to 3.5 t it's `auto` with the vehicle's height and width, because a
|
||||
camper shouldn't be kept off roads closed to lorries (`hgv=no`). Above
|
||||
3.5 t it's `truck` with every dimension.
|
||||
* Vehicle profile: height, width, length, weight in `data/vehicle.json`
|
||||
(`GET`/`PUT /api/vehicle`), one for now, edited in the route panel.
|
||||
The default is a camper: 3.0 m, 2.3 m, 7 m, 3.5 t.
|
||||
* Route panel (`public/js/route.js`): while it's open, a map click adds a
|
||||
point; markers drag; Reverse, Clear. The route is drawn with distance,
|
||||
time and directions. "Save to library" stores it as a `route` item in
|
||||
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.
|
||||
|
||||
== Phases
|
||||
|
||||
|
||||
@@ -114,6 +114,84 @@ module Maptool
|
||||
end
|
||||
private_class_method :write_json
|
||||
|
||||
class RouteError < StandardError; end
|
||||
class Unavailable < StandardError; end
|
||||
|
||||
# A camper by default; one profile for now (docs/routing-design.adoc).
|
||||
DEFAULT_VEHICLE = { height: 3.0, width: 2.3, length: 7.0, weight: 3.5 }.freeze
|
||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
|
||||
# Up to this weight Valhalla's "auto" costing (with height/width) fits
|
||||
# better than "truck": a camper isn't kept off roads closed to lorries.
|
||||
CAR_MAX_WEIGHT = 3.5
|
||||
|
||||
def self.vehicle(data_dir)
|
||||
DEFAULT_VEHICLE.merge(read_json(File.join(data_dir, "vehicle.json")) || {})
|
||||
end
|
||||
|
||||
def self.save_vehicle(data_dir, values)
|
||||
vehicle = VEHICLE_LIMITS.to_h do |key, range|
|
||||
value = Float(values.fetch(key.to_s), exception: false)
|
||||
raise ArgumentError, "#{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
|
||||
|
||||
[key, value]
|
||||
end
|
||||
write_json(File.join(data_dir, "vehicle.json"), vehicle)
|
||||
vehicle
|
||||
end
|
||||
|
||||
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
|
||||
# (km), time (s) and the turn-by-turn instructions.
|
||||
def self.route(valhalla_url, locations, vehicle)
|
||||
raise RouteError, "at least two points are needed" if locations.size < 2
|
||||
raise Unavailable, "routing is not set up" if valhalla_url.to_s.empty?
|
||||
|
||||
car = vehicle[:weight] <= CAR_MAX_WEIGHT
|
||||
costing = car ? "auto" : "truck"
|
||||
options = car ? vehicle.slice(:height, :width) : vehicle
|
||||
body = { locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
|
||||
costing: costing, costing_options: { costing => options }, units: "kilometers" }
|
||||
uri = URI("#{valhalla_url}/route")
|
||||
response = begin
|
||||
Net::HTTP.start(uri.host, uri.port, open_timeout: 2, read_timeout: 60) do |http|
|
||||
http.post(uri.path, JSON.generate(body), "Content-Type" => "application/json")
|
||||
end
|
||||
rescue SystemCallError, Net::OpenTimeout, SocketError
|
||||
raise Unavailable, "the routing service is not running"
|
||||
end
|
||||
data = JSON.parse(response.body)
|
||||
raise RouteError, data["error"] || "no route found" unless response.is_a?(Net::HTTPSuccess)
|
||||
|
||||
legs = data["trip"]["legs"]
|
||||
{ type: "Feature",
|
||||
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
||||
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
||||
time_s: data["trip"]["summary"]["time"],
|
||||
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
|
||||
rescue ArgumentError, TypeError
|
||||
raise RouteError, "invalid coordinates"
|
||||
end
|
||||
|
||||
# Valhalla's encoded polyline (precision 6) → [[lon, lat], ...].
|
||||
def self.decode_polyline(encoded)
|
||||
values = []
|
||||
value = shift = 0
|
||||
encoded.each_byte do |byte|
|
||||
byte -= 63
|
||||
value |= (byte & 0x1f) << shift
|
||||
shift += 5
|
||||
next if byte >= 0x20
|
||||
|
||||
values << ((value & 1).zero? ? value >> 1 : ~(value >> 1))
|
||||
value = shift = 0
|
||||
end
|
||||
lat = lon = 0
|
||||
values.each_slice(2).map do |dlat, dlon|
|
||||
lat += dlat
|
||||
lon += dlon
|
||||
[lon / 1e6, lat / 1e6]
|
||||
end
|
||||
end
|
||||
|
||||
def self.reset!
|
||||
MUTEX.synchronize { @pending = false }
|
||||
end
|
||||
|
||||
@@ -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`;
|
||||
}
|
||||
@@ -230,6 +230,21 @@ class AppTest < Minitest::Test
|
||||
assert_equal 409, request.patch("/api/library/folder/Van", params: { name: "Bus" }, **logged_in_env).status
|
||||
end
|
||||
|
||||
def test_routing_without_a_valhalla_service_says_so
|
||||
assert_equal 503, request.post("/api/route", input: JSON.generate(locations: [[17.1, 48.1], [17.2, 48.2]]), "CONTENT_TYPE" => "application/json").status
|
||||
assert_equal 400, request.post("/api/route", input: JSON.generate(locations: "x"), "CONTENT_TYPE" => "application/json").status
|
||||
end
|
||||
|
||||
def test_the_vehicle_is_readable_by_anyone_but_saved_only_when_logged_in
|
||||
assert_equal 3.0, json_body(request.get("/api/vehicle"))["height"]
|
||||
vehicle = { height: 3.3, width: 2.3, length: 7, weight: 3.5 }
|
||||
assert_equal 401, request.put("/api/vehicle", params: vehicle).status
|
||||
assert_equal 3.3, json_body(request.put("/api/vehicle", params: vehicle, **logged_in_env))["height"]
|
||||
assert_equal 400, request.put("/api/vehicle", params: vehicle.merge(weight: 0), **logged_in_env).status
|
||||
ensure
|
||||
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicle.json"))
|
||||
end
|
||||
|
||||
def test_invalid_folder_path_is_rejected
|
||||
assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status
|
||||
end
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/routing"
|
||||
require "socket"
|
||||
|
||||
class RoutingTest < Minitest::Test
|
||||
def setup
|
||||
@@ -58,4 +59,54 @@ class RoutingTest < Minitest::Test
|
||||
File.write(File.join(@routing, "status.json"), JSON.generate(state: "running", step: "packing tiles"))
|
||||
assert_equal "packing tiles", Maptool::Routing.build_status(@data)[:step]
|
||||
end
|
||||
|
||||
def test_the_vehicle_is_validated_and_stored
|
||||
assert_equal Maptool::Routing::DEFAULT_VEHICLE, Maptool::Routing.vehicle(@data)
|
||||
Maptool::Routing.save_vehicle(@data, "height" => "3.4", "width" => "2.4", "length" => "8", "weight" => "4.2")
|
||||
assert_equal 4.2, Maptool::Routing.vehicle(@data)[:weight]
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicle(@data, "height" => "30", "width" => "2", "length" => "8", "weight" => "3") }
|
||||
end
|
||||
|
||||
def test_decode_polyline_reads_valhallas_precision_6
|
||||
# Two points, encoded with Valhalla's (Google-style, 1e6) polyline.
|
||||
assert_equal [[9.521006, 47.140956], [9.521034, 47.140974]], Maptool::Routing.decode_polyline("wdg|xA{ubdQc@w@")
|
||||
end
|
||||
|
||||
def test_route_picks_the_costing_by_weight_and_returns_a_line
|
||||
shape = "wdg|xA{ubdQc@w@"
|
||||
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
|
||||
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] })
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLE)
|
||||
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
|
||||
end
|
||||
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
|
||||
|
||||
request = serve_once("HTTP/1.1 400 Bad Request\r\nContent-Length: 20\r\n\r\n{\"error\":\"no route\"}") do |url|
|
||||
error = assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.route(url, [[1, 2], [3, 4]], Maptool::Routing::DEFAULT_VEHICLE.merge(weight: 7.5)) }
|
||||
assert_equal "no route", error.message
|
||||
end
|
||||
assert_includes request, %("costing":"truck")
|
||||
assert_raises(Maptool::Routing::Unavailable) { Maptool::Routing.route("", [[1, 2], [3, 4]], {}) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Answers one HTTP request with `response`; returns what was received.
|
||||
def serve_once(response)
|
||||
server = TCPServer.new("127.0.0.1", 0)
|
||||
received = +""
|
||||
thread = Thread.new do
|
||||
client = server.accept
|
||||
received << client.readpartial(65_536)
|
||||
received << client.readpartial(65_536) unless received.include?("{")
|
||||
client.write(response)
|
||||
client.close
|
||||
end
|
||||
yield "http://127.0.0.1:#{server.addr[1]}"
|
||||
thread.join
|
||||
received
|
||||
ensure
|
||||
server&.close
|
||||
end
|
||||
end
|
||||
@@ -104,6 +104,35 @@
|
||||
<div class="debug-panel__body"></div>
|
||||
</div>
|
||||
|
||||
<div id="route-panel" class="basemap-panel" hidden>
|
||||
<div class="basemap-panel__header">
|
||||
<strong>Route</strong>
|
||||
<button type="button" class="basemap-panel__close" aria-label="Close">×</button>
|
||||
</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>
|
||||
<ol class="route-panel__points"></ol>
|
||||
<div class="route-panel__buttons">
|
||||
<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>
|
||||
</div>
|
||||
<p class="route-panel__summary"></p>
|
||||
<details class="route-panel__directions" hidden>
|
||||
<summary>Directions</summary>
|
||||
<ol></ol>
|
||||
</details>
|
||||
<fieldset class="route-panel__vehicle">
|
||||
<legend>Vehicle</legend>
|
||||
<label>Height <input type="number" name="height" step="0.1" min="1" max="6"> m</label>
|
||||
<label>Width <input type="number" name="width" step="0.1" min="1" max="4"> m</label>
|
||||
<label>Length <input type="number" name="length" step="0.5" min="2" max="25"> m</label>
|
||||
<label>Weight <input type="number" name="weight" step="0.1" min="0.5" max="60"> t</label>
|
||||
</fieldset>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="offline-data-panel" class="basemap-panel" hidden>
|
||||
<div class="basemap-panel__header">
|
||||
<strong>Offline data</strong>
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"/js/panels.js": "/js/panels.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/plugins.js": "/js/plugins.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/radar.js": "/js/radar.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/route.js": "/js/route.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/share_import.js": "/js/share_import.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/search.js": "/js/search.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/shadow.js": "/js/shadow.js?v=<%= ASSET_VERSION %>",
|
||||
|
||||
Reference in new issue
Block a user