Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a1fc266b7 | ||
|
|
916b016da1 | ||
|
|
69aa284e36 | ||
|
|
58ca871662 |
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ serving swaps the tiles in, and a truck route with dimensions comes back.
|
||||
* "Offline routing" row in the Offline data panel, next to the offline
|
||||
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
|
||||
three. A routing request made while the offline map is still
|
||||
downloading extracts waits for it (`Routing.offline_build_finished`).
|
||||
downloading extracts waits for the downloads only, then runs alongside Planetiler (`Routing.extracts_ready`).
|
||||
The row says whether the service answers.
|
||||
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
|
||||
Valhalla `/route` and returns the route as a GeoJSON line with
|
||||
@@ -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
|
||||
|
||||
@@ -164,6 +164,7 @@ module Maptool
|
||||
# for those.
|
||||
def self.reset!
|
||||
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.replace(state: "idle") }
|
||||
@fetching_extracts = false
|
||||
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.replace(state: "idle") }
|
||||
end
|
||||
|
||||
@@ -241,14 +242,29 @@ module Maptool
|
||||
raise BuildError, "select at least one region first" if codes.empty?
|
||||
|
||||
begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS)
|
||||
@fetching_extracts = true
|
||||
Thread.new do
|
||||
run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
|
||||
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
|
||||
end
|
||||
extracts_ready(data_dir) # no-op unless the build failed before its extracts were in
|
||||
end
|
||||
end
|
||||
|
||||
# True while an offline build may still be replacing the extracts that
|
||||
# a routing build reads; Planetiler afterwards doesn't touch them.
|
||||
def self.fetching_extracts?
|
||||
@fetching_extracts
|
||||
end
|
||||
|
||||
# A routing build requested meanwhile waited for these extracts.
|
||||
Routing.offline_build_finished(data_dir) if defined?(Routing)
|
||||
end
|
||||
def self.extracts_ready(data_dir)
|
||||
return unless @fetching_extracts
|
||||
|
||||
@fetching_extracts = false
|
||||
Routing.extracts_ready(data_dir) if defined?(Routing)
|
||||
end
|
||||
private_class_method :extracts_ready
|
||||
|
||||
# fetch_manifest: same injectable-seam reasoning as download_extract
|
||||
# above, for the one Mapterhorn manifest lookup this needs.
|
||||
@@ -334,6 +350,7 @@ module Maptool
|
||||
report_step.call(progress_step("fetching #{code}", codes, i))
|
||||
cached_extract(code, slug, data_dir, download_extract, fetch_last_modified)
|
||||
end
|
||||
extracts_ready(data_dir)
|
||||
|
||||
osm_path =
|
||||
if sources.size == 1
|
||||
|
||||
+89
-23
@@ -33,13 +33,13 @@ module Maptool
|
||||
|
||||
# Routing covers the offline map's selected countries. While an offline
|
||||
# build is running (it may be downloading those very extracts), the
|
||||
# request waits for it — PmtilesBuilder calls offline_build_finished.
|
||||
# request waits for its downloads — PmtilesBuilder calls extracts_ready.
|
||||
def self.request_build(data_dir)
|
||||
codes = PmtilesBuilder.selected_regions(data_dir)
|
||||
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
|
||||
|
||||
MUTEX.synchronize do
|
||||
if PmtilesBuilder.offline_status[:state] == "running"
|
||||
if PmtilesBuilder.fetching_extracts?
|
||||
@pending = true
|
||||
return
|
||||
end
|
||||
@@ -67,17 +67,18 @@ module Maptool
|
||||
# one merged file. Its image has no osmium; this container does.
|
||||
def self.merge_and_request(data_dir, codes)
|
||||
merged = File.join(dir(data_dir), "merged.osm.pbf")
|
||||
part = File.join(dir(data_dir), "merged.part.osm.pbf") # osmium picks the format by extension
|
||||
inputs = codes.map { |code| extract_path(data_dir, code) }
|
||||
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", "#{merged}.part")
|
||||
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", part)
|
||||
raise PmtilesBuilder::BuildError, "osmium merge failed: #{(stderr + stdout)[-2000..] || stderr + stdout}" unless status.success?
|
||||
|
||||
File.rename("#{merged}.part", merged)
|
||||
File.rename(part, merged)
|
||||
MUTEX.synchronize do
|
||||
write_request(data_dir, codes, "routing/merged.osm.pbf")
|
||||
@merging = nil
|
||||
end
|
||||
rescue StandardError => e
|
||||
FileUtils.rm_f("#{merged}.part")
|
||||
FileUtils.rm_f(part)
|
||||
MUTEX.synchronize { @merging = { state: "error", message: e.message, finished_at: Time.now.utc.iso8601 } }
|
||||
end
|
||||
private_class_method :merge_and_request
|
||||
@@ -88,7 +89,7 @@ module Maptool
|
||||
end
|
||||
private_class_method :write_request
|
||||
|
||||
def self.offline_build_finished(data_dir)
|
||||
def self.extracts_ready(data_dir)
|
||||
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
|
||||
request_build(data_dir) if pending
|
||||
rescue PmtilesBuilder::BuildError
|
||||
@@ -99,7 +100,7 @@ module Maptool
|
||||
# started_at, message.
|
||||
def self.build_status(data_dir)
|
||||
pending, merging = MUTEX.synchronize { [@pending, @merging] }
|
||||
return { state: "running", step: "waiting for the offline map build" } if pending
|
||||
return { state: "running", step: "waiting for the offline map downloads" } if pending
|
||||
return merging if merging
|
||||
status = read_json(File.join(dir(data_dir), "status.json"))
|
||||
return status if status&.dig(:state) == "running" # the container is building; a queued request runs next
|
||||
@@ -162,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")
|
||||
@@ -197,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)
|
||||
@@ -220,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
|
||||
|
||||
|
||||
Generated
+4
-4
@@ -9,7 +9,7 @@
|
||||
"flag-icons": "7.6.0",
|
||||
"maplibre-contour": "0.1.1",
|
||||
"maplibre-gl": "6.18.0",
|
||||
"maplibre-gl-lanes": "1.5.0",
|
||||
"maplibre-gl-lanes": "1.6.0",
|
||||
"pmtiles": "4.5.0",
|
||||
"suncalc": "2.1.4"
|
||||
}
|
||||
@@ -210,9 +210,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/maplibre-gl-lanes": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.5.0.tgz",
|
||||
"integrity": "sha512-oiqErfZuvgRNMolvYNYhZYmldk0oHNcMFDGEKzEHJ9mXzf98GLOGA90RuMXhh5k2E49J1Y3foaVOCYIu4s1YFw==",
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.6.0.tgz",
|
||||
"integrity": "sha512-cnHkrQW9LYD9j0HtVoptOMq2LG/HjEC3pWqLpwhElIzViF3ho+BP8E+YH3wS0Af/J34Wum2mlrRFFWAvw88H1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
"flag-icons": "7.6.0",
|
||||
"maplibre-contour": "0.1.1",
|
||||
"maplibre-gl": "6.18.0",
|
||||
"maplibre-gl-lanes": "1.5.0",
|
||||
"maplibre-gl-lanes": "1.6.0",
|
||||
"pmtiles": "4.5.0",
|
||||
"suncalc": "2.1.4"
|
||||
}
|
||||
|
||||
@@ -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
@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+18
-6
@@ -3,6 +3,7 @@ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { en
|
||||
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
||||
|
||||
// src/core/graph.ts
|
||||
var ONEWAY_VALUES = /* @__PURE__ */ new Set(["yes", "true", "1", "-1", !0, 1, -1]);
|
||||
function lngLatToMercator(lng, lat) {
|
||||
let x = (lng + 180) / 360, s = Math.sin(lat * Math.PI / 180), y = 0.5 - 0.25 * Math.log((1 + s) / (1 - s)) / Math.PI;
|
||||
return [x, y];
|
||||
@@ -12,7 +13,7 @@ function mercatorToLngLat(x, y) {
|
||||
return [lng, lat];
|
||||
}
|
||||
function buildLineGraph(features, opts = {}) {
|
||||
let routeProp = opts.routeProperty ?? "route", colorProp = opts.colorProperty ?? "color", nameProp = opts.nameProperty ?? "name", snap = opts.snapDegrees ?? 1e-7, uniform = opts.uniformProperties ?? [], routes = /* @__PURE__ */ new Map(), vertexPos = /* @__PURE__ */ new Map(), elem = /* @__PURE__ */ new Map(), adjacency = /* @__PURE__ */ new Map(), keyOf = (lng, lat) => {
|
||||
let routeProp = opts.routeProperty ?? "route", colorProp = opts.colorProperty ?? "color", nameProp = opts.nameProperty ?? "name", snap = opts.snapDegrees ?? 1e-7, onewayProp = opts.onewayProperty, uniform = onewayProp && !(opts.uniformProperties ?? []).includes(onewayProp) ? [...opts.uniformProperties ?? [], onewayProp] : opts.uniformProperties ?? [], routes = /* @__PURE__ */ new Map(), vertexPos = /* @__PURE__ */ new Map(), elem = /* @__PURE__ */ new Map(), adjacency = /* @__PURE__ */ new Map(), keyOf = (lng, lat) => {
|
||||
let kx = Math.round(lng / snap), ky = Math.round(lat / snap);
|
||||
return `${kx},${ky}`;
|
||||
};
|
||||
@@ -101,7 +102,13 @@ function buildLineGraph(features, opts = {}) {
|
||||
direction.set(r, d === 0 ? 0 : walkForward ? d : -d);
|
||||
}
|
||||
let edge = { id, a, b, coords, routes: [...first.routes.keys()].sort(), direction, order: [] };
|
||||
first.props && (edge.properties = first.props), edges.push(edge), nodes[a].ports.push({ edge: id, end: "a" }), nodes[b].ports.push({ edge: id, end: "b" });
|
||||
if (first.props)
|
||||
if (onewayProp && ONEWAY_VALUES.has(first.props[onewayProp]) && (edge.oneway = !0), onewayProp && !opts.uniformProperties?.includes(onewayProp)) {
|
||||
let { [onewayProp]: _, ...rest } = first.props;
|
||||
Object.keys(rest).length && (edge.properties = rest);
|
||||
} else
|
||||
edge.properties = first.props;
|
||||
edges.push(edge), nodes[a].ports.push({ edge: id, end: "a" }), nodes[b].ports.push({ edge: id, end: "b" });
|
||||
};
|
||||
for (let vk of adjacency.keys())
|
||||
if (isJunction(vk))
|
||||
@@ -124,7 +131,12 @@ function deriveChains(nodes, edges, routes) {
|
||||
}
|
||||
let l = Math.hypot(dx, dy) || 1;
|
||||
return [dx / l, dy / l];
|
||||
};
|
||||
}, flowAt = (rid, edge, end) => {
|
||||
let e = edges[edge];
|
||||
if (!e.oneway) return 0;
|
||||
let d = e.direction.get(rid) ?? 0;
|
||||
return d ? end === "b" == d > 0 ? 1 : -1 : 0;
|
||||
}, clash = (a, b) => a !== 0 && a === b;
|
||||
for (let rid of routes.keys()) {
|
||||
let routeEdges = edges.filter((e) => e.routes.includes(rid));
|
||||
if (!routeEdges.length) {
|
||||
@@ -158,9 +170,9 @@ function deriveChains(nodes, edges, routes) {
|
||||
steps.push({ edge: nextEdge.id, forward }), unused.delete(nextEdge.id);
|
||||
let far = forward ? nextEdge.b : nextEdge.a, farEnd = forward ? "b" : "a", d = outDir(nextEdge.id, farEnd);
|
||||
arriving = [-d[0], -d[1]], node = far;
|
||||
let best = null, bestDot = -1 / 0;
|
||||
let best = null, bestDot = -1 / 0, arrFlow = flowAt(rid, nextEdge.id, farEnd), arrEdge = nextEdge.id, hasAgreeing = arrFlow !== 0 && nodes[node].ports.some((p) => p.edge !== arrEdge && edges[p.edge].routes.includes(rid) && flowAt(rid, p.edge, p.end) === -arrFlow);
|
||||
for (let p of nodes[node].ports) {
|
||||
if (!unused.has(p.edge)) continue;
|
||||
if (!unused.has(p.edge) || hasAgreeing && clash(arrFlow, flowAt(rid, p.edge, p.end))) continue;
|
||||
let o = outDir(p.edge, p.end), dot = o[0] * arriving[0] + o[1] * arriving[1];
|
||||
(dot > bestDot + 1e-9 || Math.abs(dot - bestDot) <= 1e-9 && best && p.edge < best.id) && (bestDot = dot, best = edges[p.edge]);
|
||||
}
|
||||
@@ -181,7 +193,7 @@ function deriveChains(nodes, edges, routes) {
|
||||
if (n.ports.forEach((p, i) => {
|
||||
if (i === ce.port || !edges[p.edge].routes.includes(rid)) return;
|
||||
let o = outDir(p.edge, p.end), dot = o[0] * arriveDir[0] + o[1] * arriveDir[1];
|
||||
dot > bestDot && (bestDot = dot, best = i);
|
||||
clash(flowAt(rid, own.edge, own.end), flowAt(rid, p.edge, p.end)) && (dot -= 4), dot > bestDot && (bestDot = dot, best = i);
|
||||
}), best < 0) continue;
|
||||
let key = `${ce.node}:${Math.min(ce.port, best)}:${Math.max(ce.port, best)}`;
|
||||
seen.has(key) || (seen.add(key), n.transitions.push({ route: rid, from: ce.port, to: best }), ce.end === "start" ? ce.chain.mergeStart = n.ports[best].edge : ce.chain.mergeEnd = n.ports[best].edge);
|
||||
|
||||
+7
-7
@@ -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
|
||||
|
||||
+50
-18
@@ -25,16 +25,18 @@ class RoutingTest < Minitest::Test
|
||||
assert_equal "waiting for the routing container", Maptool::Routing.build_status(@data)[:step]
|
||||
end
|
||||
|
||||
def test_a_request_during_an_offline_build_waits_for_it
|
||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
||||
def test_a_request_while_the_offline_build_downloads_waits_for_the_extracts_only
|
||||
Maptool::PmtilesBuilder.instance_variable_set(:@fetching_extracts, true)
|
||||
Maptool::Routing.request_build(@data)
|
||||
assert_equal "waiting for the offline map build", Maptool::Routing.build_status(@data)[:step]
|
||||
assert_equal "waiting for the offline map downloads", Maptool::Routing.build_status(@data)[:step]
|
||||
refute File.exist?(File.join(@routing, "build-request.json"))
|
||||
|
||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "done")
|
||||
# Planetiler still running doesn't matter, the extracts are in.
|
||||
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
||||
Maptool::Routing.offline_build_finished(@data)
|
||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
||||
Maptool::PmtilesBuilder.send(:extracts_ready, @data)
|
||||
assert File.exist?(File.join(@routing, "build-request.json"))
|
||||
refute Maptool::PmtilesBuilder.fetching_extracts?
|
||||
end
|
||||
|
||||
def test_update_check_compares_regions_and_extract_age
|
||||
@@ -92,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
|
||||
@@ -108,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], {}) }
|
||||
@@ -146,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
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user