Vehicle profiles (Car, Camper, ...), avoid tolls/motorways, per-country vignette and toll km for a route
CI / check (push) Successful in 19s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-11-14 21:20:23 +01:00
1 parent 58ca871662
commit 69aa284e36
8 files changed
+320 -72

No files matched your search

+13 -10
View File
@@ -448,13 +448,14 @@ module Maptool
end
# A route through the posted points ({"locations": [[lon, lat], ...]})
# for the stored vehicle. Open to anyone, like viewing the map; only
# for the vehicle profile "vehicle" (an id, default the first). 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"]
body = JSON.parse(request.body.read)
locations = body["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))
json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"])
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
@@ -463,11 +464,11 @@ module Maptool
halt 503, json(error: e.message)
end
# Where the stored vehicle gets in each of `minutes` from `center`
# Where the vehicle profile gets in each of `minutes` from `center`
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
post "/api/isochrone" do
body = JSON.parse(request.body.read)
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR))
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"])
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
@@ -476,14 +477,16 @@ module Maptool
halt 503, json(error: e.message)
end
get "/api/vehicle" do
json Routing.vehicle(DATA_DIR)
get "/api/vehicles" do
json Routing.vehicles(DATA_DIR)
end
put "/api/vehicle" do
put "/api/vehicles" do
require_login!
json Routing.save_vehicle(DATA_DIR, params)
rescue ArgumentError, KeyError => e
json Routing.save_vehicles(DATA_DIR, JSON.parse(request.body.read))
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue ArgumentError => e
halt 400, json(error: e.message)
end
+15 -3
View File
@@ -139,9 +139,21 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
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.
* Vehicle profiles in `data/vehicles.json` (`GET`/`PUT /api/vehicles`,
saving needs a login): a name plus optional height, width, length,
weight (missing: no limit). Defaults: Car (no limits) and Camper
(3.0 m, 2.3 m, 7 m, 3.5 t; an older single `vehicle.json` becomes the
camper). The route panel picks one per browser (localStorage) and sends
its id with `/api/route` and `/api/isochrone`; Edit shows the fields.
* Avoid tolls / motorways (`"avoid": {"tolls": true, "highways": true}`)
sets Valhalla's `use_tolls` / `use_highways` to 0 for the whole route.
Per country isn't possible in one Valhalla request.
* Vignettes and tolls: `/api/route` adds `countries`, the km, motorway km
and toll km per country, from `/trace_attributes` (edge_walk on each
leg's shape). The panel lists vignette countries (fixed list in
route.js) with motorway km, other countries with toll km. In vignette
countries every motorway km counts, since OSM doesn't tag those as toll
reliably.
* 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
+81 -16
View File
@@ -163,33 +163,68 @@ module Maptool
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 profiles: a name plus optional limits (nil: no limit, a plain
# car). Stored for everyone, picked per browser (route.js).
DEFAULT_VEHICLES = [
{ id: "car", name: "Car" },
{ id: "camper", name: "Camper", 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")) || {})
def self.vehicles(data_dir)
read_json(File.join(data_dir, "vehicles.json")) || begin
# The single vehicle stored before profiles became the camper.
old = read_json(File.join(data_dir, "vehicle.json"))
old ? [DEFAULT_VEHICLES[0], DEFAULT_VEHICLES[1].merge(old.slice(*VEHICLE_LIMITS.keys))] : DEFAULT_VEHICLES
end
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)
# The profile with this id, or the first one.
def self.vehicle(data_dir, id = nil)
list = vehicles(data_dir)
list.find { |v| v[:id] == id } || list.first
end
# Replaces the whole list: [{ "id", "name", "height", ... }, ...].
def self.save_vehicles(data_dir, list)
raise ArgumentError, "at least one vehicle is needed" unless list.is_a?(Array) && list.any? && list.size <= 20
vehicles = list.map do |values|
raise ArgumentError, "invalid vehicle" unless values.is_a?(Hash)
name = values["name"].to_s.strip
id = values["id"].to_s
raise ArgumentError, "every vehicle needs a name" if name.empty? || name.size > 40
raise ArgumentError, "invalid vehicle id" unless id.match?(/\A[\w-]{1,40}\z/)
limits = VEHICLE_LIMITS.to_h do |key, range|
raw = values[key.to_s]
next [key, nil] if raw.nil? || raw.to_s.strip.empty?
value = Float(raw, exception: false)
raise ArgumentError, "#{name}: #{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
{ id: id, name: name, **limits.compact }
end
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
write_json(File.join(data_dir, "vehicles.json"), vehicles)
vehicles
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)
# (km), time (s), the turn-by-turn instructions and, per country, the
# km on motorways and toll roads (for vignettes and tolls).
# avoid: {"tolls" => true, "highways" => true}, for the whole route.
def self.route(valhalla_url, locations, vehicle, avoid = {})
raise RouteError, "at least two points are needed" if locations.size < 2
costing, options = costing(vehicle)
costing, options = costing(vehicle, avoid)
data = valhalla(valhalla_url, "/route",
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers")
@@ -198,21 +233,46 @@ module Maptool
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"],
countries: countries(valhalla_url, legs, costing, options),
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates"
end
# [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route order, from
# Valhalla's per-edge attributes. nil if that lookup fails: it's extra.
def self.countries(valhalla_url, legs, costing, options)
totals = {}
legs.each do |leg|
data = valhalla(valhalla_url, "/trace_attributes",
encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing,
costing_options: { costing => options },
filters: { attributes: %w[edge.length edge.road_class edge.toll node.admin_index admin.country_code], action: "include" })
codes = data["admins"].map { |admin| admin["country_code"] }
data["edges"].each do |edge|
code = codes[edge.dig("end_node", "admin_index").to_i] || "?"
row = totals[code] ||= { code: code, km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
row[:km] += edge["length"]
row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway"
row[:toll_km] += edge["length"] if edge["toll"]
end
end
totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } }
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
nil
end
private_class_method :countries
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
# GeoJSON FeatureCollection of polygons, largest first.
def self.isochrone(valhalla_url, center, minutes, vehicle)
def self.isochrone(valhalla_url, center, minutes, vehicle, avoid = {})
lon, lat = center
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
costing, options = costing(vehicle)
costing, options = costing(vehicle, avoid)
valhalla(valhalla_url, "/isochrone",
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
contours: minutes.map { |m| { time: m } }, polygons: true)
@@ -221,8 +281,13 @@ module Maptool
end
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
def self.costing(vehicle)
vehicle[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", vehicle.slice(:height, :width)] : ["truck", vehicle]
def self.costing(vehicle, avoid = {})
limits = vehicle.slice(*VEHICLE_LIMITS.keys).compact
costing, options = limits[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", limits.slice(:height, :width)] : ["truck", limits]
avoid = {} unless avoid.is_a?(Hash)
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
options = options.merge(use_highways: 0.0) if avoid["highways"]
[costing, options]
end
private_class_method :costing
+37
View File
@@ -2336,10 +2336,47 @@ html, body {
border-radius: 4px;
}
.route-panel__vehicle[hidden] {
display: none;
}
.route-panel__vehicle input {
width: 4.5em;
}
.route-panel__avoid {
display: flex;
gap: 8px;
align-items: center;
}
.route-panel__countries {
margin: 0;
padding-left: 1.2em;
font-size: 0.9em;
}
.route-panel__vehicle-row {
display: flex;
gap: 6px;
align-items: center;
}
.route-panel__vehicle-name,
.route-panel__vehicle-hint {
grid-column: 1 / -1;
}
.route-panel__vehicle-name input {
width: 12em;
}
.route-panel__vehicle-hint {
margin: 0;
font-size: 0.85em;
color: #666;
}
.route-marker {
width: 22px;
height: 22px;
+105 -17
View File
@@ -10,7 +10,12 @@ 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 VEHICLE_URL = "/api/vehicle";
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";
@@ -62,6 +67,8 @@ export class RoutePanelControl {
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();
@@ -141,6 +148,8 @@ export class RoutePanelControl {
// 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);
@@ -219,7 +228,7 @@ export class RoutePanelControl {
const response = await fetch(ROUTE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat) }),
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})`;
@@ -237,6 +246,7 @@ export class RoutePanelControl {
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;
@@ -287,7 +297,7 @@ export class RoutePanelControl {
const response = await fetch(ISOCHRONE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ center, minutes }),
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})`);
@@ -392,31 +402,109 @@ export class RoutePanelControl {
return features.find((f) => f.geometry.type === "LineString")?.properties.id;
}
// 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 --------------------------------------------------------------
// Readable by anyone, saved only when logged in; a change re-routes.
// 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 inputs = [...this._panel.querySelectorAll(".route-panel__vehicle input")];
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")];
try {
this._vehicle = await (await fetch(VEHICLE_URL)).json();
this._vehicles = await (await fetch(VEHICLES_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 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] ?? ""));
};
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) {
window.alert(data.error || "Could not save the vehicle.");
input.value = this._vehicle[input.name];
return;
if (response.ok) {
this._vehicles = data;
} else {
window.alert(data.error || "Could not save the vehicles.");
this._vehicles = await (await fetch(VEHICLES_URL)).json();
}
this._vehicle = data;
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 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();
});
}
}
+7 -7
View File
@@ -237,14 +237,14 @@ class AppTest < Minitest::Test
assert_equal 422, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [999]), "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
def test_vehicles_are_readable_by_anyone_but_saved_only_when_logged_in
assert_equal "Car", json_body(request.get("/api/vehicles")).first["name"]
vehicles = JSON.generate([{ id: "car", name: "Car" }, { id: "van", name: "Van", height: 3.3 }])
assert_equal 401, request.put("/api/vehicles", input: vehicles).status
assert_equal 3.3, json_body(request.put("/api/vehicles", input: vehicles, **logged_in_env)).last["height"]
assert_equal 400, request.put("/api/vehicles", input: "[]", **logged_in_env).status
ensure
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicle.json"))
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicles.json"))
end
def test_changes_and_exports_need_login
+43 -13
View File
@@ -94,11 +94,22 @@ class RoutingTest < Minitest::Test
refute File.exist?(File.join(@routing, "build-request.json"))
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") }
def test_vehicle_profiles_are_validated_and_stored
assert_equal %w[car camper], Maptool::Routing.vehicles(@data).map { |v| v[:id] }
assert_equal "Car", Maptool::Routing.vehicle(@data, "nope")[:name]
Maptool::Routing.save_vehicles(@data, [{ "id" => "car", "name" => "Car", "height" => "" },
{ "id" => "van", "name" => "Van", "height" => "3.4", "weight" => "4.2" }])
assert_equal({ id: "van", name: "Van", height: 3.4, weight: 4.2 }, Maptool::Routing.vehicle(@data, "van"))
assert_equal({ id: "car", name: "Car" }, Maptool::Routing.vehicle(@data, "car"))
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", "height" => "30" }]) }
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "" }]) }
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, []) }
end
def test_the_old_single_vehicle_becomes_the_camper
File.write(File.join(@data, "vehicle.json"), JSON.generate(height: 3.3, width: 2.3, length: 7, weight: 3.5))
assert_equal 3.3, Maptool::Routing.vehicle(@data, "camper")[:height]
end
def test_decode_polyline_reads_valhallas_precision_6
@@ -110,24 +121,40 @@ class RoutingTest < Minitest::Test
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)
# The per-country lookup failing (400) leaves the route as it is.
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}") do |url|
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLES[1])
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)) }
error = assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.route(url, [[1, 2], [3, 4]], Maptool::Routing::DEFAULT_VEHICLES[1].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
def test_a_route_sums_motorway_and_toll_km_per_country_and_can_avoid_tolls
route = JSON.generate(trip: { summary: { length: 3, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
attributes = JSON.generate(admins: [{ country_code: "AT" }, { country_code: "SK" }],
edges: [{ length: 1.0, road_class: "motorway", toll: false, end_node: { admin_index: 0 } },
{ length: 0.5, road_class: "primary", toll: false, end_node: { admin_index: 0 } },
{ length: 1.5, road_class: "motorway", toll: true, end_node: { admin_index: 1 } }])
ok = ->(body) { "HTTP/1.1 200 OK\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}" }
request = serve_once(ok.(route), ok.(attributes)) do |url|
countries = Maptool::Routing.route(url, [[1, 2], [3, 4]], { id: "car" }, { "tolls" => true })[:properties][:countries]
assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], countries
end
assert_includes request, %("costing_options":{"auto":{"use_tolls":0.0}})
assert_includes request, "/trace_attributes"
end
def test_isochrone_asks_valhalla_for_each_time_and_checks_them
reply = JSON.generate(type: "FeatureCollection", features: [])
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
assert_equal "FeatureCollection", Maptool::Routing.isochrone(url, [17.1, 48.1], [60, 30, 60], Maptool::Routing::DEFAULT_VEHICLE)["type"]
assert_equal "FeatureCollection", Maptool::Routing.isochrone(url, [17.1, 48.1], [60, 30, 60], Maptool::Routing::DEFAULT_VEHICLES[1])["type"]
end
assert_includes request, %("contours":[{"time":30},{"time":60}])
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", [17.1, 48.1], [600], {}) }
@@ -148,17 +175,20 @@ class RoutingTest < Minitest::Test
ENV.delete("OSMIUM_BIN")
end
# Answers one HTTP request with `response`; returns what was received.
def serve_once(response)
# Answers one HTTP request per response, in order; returns what was received.
def serve_once(*responses)
server = TCPServer.new("127.0.0.1", 0)
received = +""
thread = Thread.new do
responses.each do |response|
client = server.accept
received << client.readpartial(65_536)
received << client.readpartial(65_536) unless received.include?("{")
request = client.readpartial(65_536)
request << client.readpartial(65_536) unless request.include?("{")
received << request
client.write(response)
client.close
end
end
yield "http://127.0.0.1:#{server.addr[1]}"
thread.join
received
+19 -6
View File
@@ -121,6 +121,7 @@
<button type="button" data-action="save" hidden>Save to library</button>
</div>
<p class="route-panel__summary"></p>
<ul class="route-panel__countries" hidden></ul>
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
<details class="route-panel__directions" hidden>
<summary>Directions</summary>
@@ -138,12 +139,24 @@
<button type="button" data-action="reach-clear" hidden>Hide</button>
</div>
<p class="route-panel__reach-status" hidden></p>
<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>
<div class="route-panel__vehicle-row">
<label>Vehicle <select class="route-panel__vehicle-select"></select></label>
<button type="button" data-action="vehicle-edit" hidden>Edit</button>
</div>
<div class="route-panel__avoid">
Avoid
<label><input type="checkbox" name="tolls"> tolls</label>
<label><input type="checkbox" name="highways"> motorways</label>
</div>
<fieldset class="route-panel__vehicle" hidden>
<label class="route-panel__vehicle-name">Name <input type="text" name="name" maxlength="40"></label>
<label>Height <input type="number" name="height" step="0.1" min="1" max="6" placeholder="–"> m</label>
<label>Width <input type="number" name="width" step="0.1" min="1" max="4" placeholder="–"> m</label>
<label>Length <input type="number" name="length" step="0.5" min="2" max="25" placeholder="–"> m</label>
<label>Weight <input type="number" name="weight" step="0.1" min="0.5" max="60" placeholder="–"> t</label>
<p class="route-panel__vehicle-hint">Empty: no limit. Over 3.5 t routes as a truck.</p>
<button type="button" data-action="vehicle-add">+ New vehicle</button>
<button type="button" data-action="vehicle-delete">Delete</button>
</fieldset>
</div>
</div>