Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
604beca236 |
No files matched your search
@@ -448,14 +448,13 @@ module Maptool
|
|||||||
end
|
end
|
||||||
|
|
||||||
# A route through the posted points ({"locations": [[lon, lat], ...]})
|
# A route through the posted points ({"locations": [[lon, lat], ...]})
|
||||||
# for the vehicle profile "vehicle" (an id, default the first). Open to anyone, like viewing the map; only
|
# for the stored vehicle. Open to anyone, like viewing the map; only
|
||||||
# saving it to the library needs a login.
|
# saving it to the library needs a login.
|
||||||
post "/api/route" do
|
post "/api/route" do
|
||||||
body = JSON.parse(request.body.read)
|
locations = JSON.parse(request.body.read)["locations"]
|
||||||
locations = body["locations"]
|
|
||||||
halt 400, json(error: "locations must be a list of [lon, lat]") unless locations.is_a?(Array) && locations.all?(Array)
|
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, body["vehicle"]), body["avoid"])
|
json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR))
|
||||||
rescue JSON::ParserError
|
rescue JSON::ParserError
|
||||||
halt 400, json(error: "invalid JSON")
|
halt 400, json(error: "invalid JSON")
|
||||||
rescue Routing::RouteError => e
|
rescue Routing::RouteError => e
|
||||||
@@ -464,11 +463,11 @@ module Maptool
|
|||||||
halt 503, json(error: e.message)
|
halt 503, json(error: e.message)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Where the vehicle profile gets in each of `minutes` from `center`
|
# Where the stored vehicle gets in each of `minutes` from `center`
|
||||||
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
|
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
|
||||||
post "/api/isochrone" do
|
post "/api/isochrone" do
|
||||||
body = JSON.parse(request.body.read)
|
body = JSON.parse(request.body.read)
|
||||||
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"])
|
json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR))
|
||||||
rescue JSON::ParserError
|
rescue JSON::ParserError
|
||||||
halt 400, json(error: "invalid JSON")
|
halt 400, json(error: "invalid JSON")
|
||||||
rescue Routing::RouteError => e
|
rescue Routing::RouteError => e
|
||||||
@@ -477,16 +476,14 @@ module Maptool
|
|||||||
halt 503, json(error: e.message)
|
halt 503, json(error: e.message)
|
||||||
end
|
end
|
||||||
|
|
||||||
get "/api/vehicles" do
|
get "/api/vehicle" do
|
||||||
json Routing.vehicles(DATA_DIR)
|
json Routing.vehicle(DATA_DIR)
|
||||||
end
|
end
|
||||||
|
|
||||||
put "/api/vehicles" do
|
put "/api/vehicle" do
|
||||||
require_login!
|
require_login!
|
||||||
json Routing.save_vehicles(DATA_DIR, JSON.parse(request.body.read))
|
json Routing.save_vehicle(DATA_DIR, params)
|
||||||
rescue JSON::ParserError
|
rescue ArgumentError, KeyError => e
|
||||||
halt 400, json(error: "invalid JSON")
|
|
||||||
rescue ArgumentError => e
|
|
||||||
halt 400, json(error: e.message)
|
halt 400, json(error: e.message)
|
||||||
end
|
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
|
* "Offline routing" row in the Offline data panel, next to the offline
|
||||||
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
|
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
|
||||||
three. A routing request made while the offline map is still
|
three. A routing request made while the offline map is still
|
||||||
downloading extracts waits for the downloads only, then runs alongside Planetiler (`Routing.extracts_ready`).
|
downloading extracts waits for it (`Routing.offline_build_finished`).
|
||||||
The row says whether the service answers.
|
The row says whether the service answers.
|
||||||
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
|
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
|
||||||
Valhalla `/route` and returns the route as a GeoJSON line with
|
Valhalla `/route` and returns the route as a GeoJSON line with
|
||||||
@@ -139,21 +139,9 @@ 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
|
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
|
camper shouldn't be kept off roads closed to lorries (`hgv=no`). Above
|
||||||
3.5 t it's `truck` with every dimension.
|
3.5 t it's `truck` with every dimension.
|
||||||
* Vehicle profiles in `data/vehicles.json` (`GET`/`PUT /api/vehicles`,
|
* Vehicle profile: height, width, length, weight in `data/vehicle.json`
|
||||||
saving needs a login): a name plus optional height, width, length,
|
(`GET`/`PUT /api/vehicle`), one for now, edited in the route panel.
|
||||||
weight (missing: no limit). Defaults: Car (no limits) and Camper
|
The default is a camper: 3.0 m, 2.3 m, 7 m, 3.5 t.
|
||||||
(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
|
* 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,
|
point; markers drag; Reverse, Clear. The route is drawn with distance,
|
||||||
time and directions. "Save to library" stores it as a `route` item in
|
time and directions. "Save to library" stores it as a `route` item in
|
||||||
|
|||||||
@@ -164,7 +164,6 @@ module Maptool
|
|||||||
# for those.
|
# for those.
|
||||||
def self.reset!
|
def self.reset!
|
||||||
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.replace(state: "idle") }
|
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.replace(state: "idle") }
|
||||||
@fetching_extracts = false
|
|
||||||
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.replace(state: "idle") }
|
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.replace(state: "idle") }
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -242,30 +241,15 @@ module Maptool
|
|||||||
raise BuildError, "select at least one region first" if codes.empty?
|
raise BuildError, "select at least one region first" if codes.empty?
|
||||||
|
|
||||||
begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS)
|
begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS)
|
||||||
@fetching_extracts = true
|
|
||||||
Thread.new do
|
Thread.new do
|
||||||
run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
|
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)
|
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
|
||||||
end
|
end
|
||||||
extracts_ready(data_dir) # no-op unless the build failed before its extracts were in
|
# A routing build requested meanwhile waited for these extracts.
|
||||||
|
Routing.offline_build_finished(data_dir) if defined?(Routing)
|
||||||
end
|
end
|
||||||
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.
|
|
||||||
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
|
# fetch_manifest: same injectable-seam reasoning as download_extract
|
||||||
# above, for the one Mapterhorn manifest lookup this needs.
|
# above, for the one Mapterhorn manifest lookup this needs.
|
||||||
def self.build_terrain(data_dir:, fetch_manifest: method(:fetch_mapterhorn_manifest))
|
def self.build_terrain(data_dir:, fetch_manifest: method(:fetch_mapterhorn_manifest))
|
||||||
@@ -350,7 +334,6 @@ module Maptool
|
|||||||
report_step.call(progress_step("fetching #{code}", codes, i))
|
report_step.call(progress_step("fetching #{code}", codes, i))
|
||||||
cached_extract(code, slug, data_dir, download_extract, fetch_last_modified)
|
cached_extract(code, slug, data_dir, download_extract, fetch_last_modified)
|
||||||
end
|
end
|
||||||
extracts_ready(data_dir)
|
|
||||||
|
|
||||||
osm_path =
|
osm_path =
|
||||||
if sources.size == 1
|
if sources.size == 1
|
||||||
|
|||||||
+24
-90
@@ -33,13 +33,13 @@ module Maptool
|
|||||||
|
|
||||||
# Routing covers the offline map's selected countries. While an offline
|
# Routing covers the offline map's selected countries. While an offline
|
||||||
# build is running (it may be downloading those very extracts), the
|
# build is running (it may be downloading those very extracts), the
|
||||||
# request waits for its downloads — PmtilesBuilder calls extracts_ready.
|
# request waits for it — PmtilesBuilder calls offline_build_finished.
|
||||||
def self.request_build(data_dir)
|
def self.request_build(data_dir)
|
||||||
codes = PmtilesBuilder.selected_regions(data_dir)
|
codes = PmtilesBuilder.selected_regions(data_dir)
|
||||||
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
|
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
|
||||||
|
|
||||||
MUTEX.synchronize do
|
MUTEX.synchronize do
|
||||||
if PmtilesBuilder.fetching_extracts?
|
if PmtilesBuilder.offline_status[:state] == "running"
|
||||||
@pending = true
|
@pending = true
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
@@ -67,18 +67,17 @@ module Maptool
|
|||||||
# one merged file. Its image has no osmium; this container does.
|
# one merged file. Its image has no osmium; this container does.
|
||||||
def self.merge_and_request(data_dir, codes)
|
def self.merge_and_request(data_dir, codes)
|
||||||
merged = File.join(dir(data_dir), "merged.osm.pbf")
|
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) }
|
inputs = codes.map { |code| extract_path(data_dir, code) }
|
||||||
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", part)
|
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", "#{merged}.part")
|
||||||
raise PmtilesBuilder::BuildError, "osmium merge failed: #{(stderr + stdout)[-2000..] || stderr + stdout}" unless status.success?
|
raise PmtilesBuilder::BuildError, "osmium merge failed: #{(stderr + stdout)[-2000..] || stderr + stdout}" unless status.success?
|
||||||
|
|
||||||
File.rename(part, merged)
|
File.rename("#{merged}.part", merged)
|
||||||
MUTEX.synchronize do
|
MUTEX.synchronize do
|
||||||
write_request(data_dir, codes, "routing/merged.osm.pbf")
|
write_request(data_dir, codes, "routing/merged.osm.pbf")
|
||||||
@merging = nil
|
@merging = nil
|
||||||
end
|
end
|
||||||
rescue StandardError => e
|
rescue StandardError => e
|
||||||
FileUtils.rm_f(part)
|
FileUtils.rm_f("#{merged}.part")
|
||||||
MUTEX.synchronize { @merging = { state: "error", message: e.message, finished_at: Time.now.utc.iso8601 } }
|
MUTEX.synchronize { @merging = { state: "error", message: e.message, finished_at: Time.now.utc.iso8601 } }
|
||||||
end
|
end
|
||||||
private_class_method :merge_and_request
|
private_class_method :merge_and_request
|
||||||
@@ -89,7 +88,7 @@ module Maptool
|
|||||||
end
|
end
|
||||||
private_class_method :write_request
|
private_class_method :write_request
|
||||||
|
|
||||||
def self.extracts_ready(data_dir)
|
def self.offline_build_finished(data_dir)
|
||||||
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
|
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
|
||||||
request_build(data_dir) if pending
|
request_build(data_dir) if pending
|
||||||
rescue PmtilesBuilder::BuildError
|
rescue PmtilesBuilder::BuildError
|
||||||
@@ -100,7 +99,7 @@ module Maptool
|
|||||||
# started_at, message.
|
# started_at, message.
|
||||||
def self.build_status(data_dir)
|
def self.build_status(data_dir)
|
||||||
pending, merging = MUTEX.synchronize { [@pending, @merging] }
|
pending, merging = MUTEX.synchronize { [@pending, @merging] }
|
||||||
return { state: "running", step: "waiting for the offline map downloads" } if pending
|
return { state: "running", step: "waiting for the offline map build" } if pending
|
||||||
return merging if merging
|
return merging if merging
|
||||||
status = read_json(File.join(dir(data_dir), "status.json"))
|
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
|
return status if status&.dig(:state) == "running" # the container is building; a queued request runs next
|
||||||
@@ -163,68 +162,33 @@ module Maptool
|
|||||||
class Unavailable < StandardError; end
|
class Unavailable < StandardError; end
|
||||||
|
|
||||||
# A camper by default; one profile for now (docs/routing-design.adoc).
|
# A camper by default; one profile for now (docs/routing-design.adoc).
|
||||||
# Vehicle profiles: a name plus optional limits (nil: no limit, a plain
|
DEFAULT_VEHICLE = { height: 3.0, width: 2.3, length: 7.0, weight: 3.5 }.freeze
|
||||||
# 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
|
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
|
# 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.
|
# better than "truck": a camper isn't kept off roads closed to lorries.
|
||||||
CAR_MAX_WEIGHT = 3.5
|
CAR_MAX_WEIGHT = 3.5
|
||||||
|
|
||||||
def self.vehicles(data_dir)
|
def self.vehicle(data_dir)
|
||||||
read_json(File.join(data_dir, "vehicles.json")) || begin
|
DEFAULT_VEHICLE.merge(read_json(File.join(data_dir, "vehicle.json")) || {})
|
||||||
# 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
|
end
|
||||||
|
|
||||||
# The profile with this id, or the first one.
|
def self.save_vehicle(data_dir, values)
|
||||||
def self.vehicle(data_dir, id = nil)
|
vehicle = VEHICLE_LIMITS.to_h do |key, range|
|
||||||
list = vehicles(data_dir)
|
value = Float(values.fetch(key.to_s), exception: false)
|
||||||
list.find { |v| v[:id] == id } || list.first
|
raise ArgumentError, "#{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
|
||||||
end
|
|
||||||
|
|
||||||
# Replaces the whole list: [{ "id", "name", "height", ... }, ...].
|
[key, value]
|
||||||
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
|
|
||||||
{ id: id, name: name, **limits.compact }
|
|
||||||
end
|
end
|
||||||
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
|
write_json(File.join(data_dir, "vehicle.json"), vehicle)
|
||||||
|
vehicle
|
||||||
write_json(File.join(data_dir, "vehicles.json"), vehicles)
|
|
||||||
vehicles
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
|
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
|
||||||
# (km), time (s), the turn-by-turn instructions and, per country, the
|
# (km), time (s) and the turn-by-turn instructions.
|
||||||
# km on motorways and toll roads (for vignettes and tolls).
|
def self.route(valhalla_url, locations, vehicle)
|
||||||
# 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
|
raise RouteError, "at least two points are needed" if locations.size < 2
|
||||||
|
|
||||||
costing, options = costing(vehicle, avoid)
|
costing, options = costing(vehicle)
|
||||||
data = valhalla(valhalla_url, "/route",
|
data = valhalla(valhalla_url, "/route",
|
||||||
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
|
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
|
||||||
costing: costing, costing_options: { costing => options }, units: "kilometers")
|
costing: costing, costing_options: { costing => options }, units: "kilometers")
|
||||||
@@ -233,46 +197,21 @@ module Maptool
|
|||||||
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
||||||
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
||||||
time_s: data["trip"]["summary"]["time"],
|
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"] } } } } }
|
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
|
||||||
rescue ArgumentError, TypeError
|
rescue ArgumentError, TypeError
|
||||||
raise RouteError, "invalid coordinates"
|
raise RouteError, "invalid coordinates"
|
||||||
end
|
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
|
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
|
||||||
|
|
||||||
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
|
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
|
||||||
# GeoJSON FeatureCollection of polygons, largest first.
|
# GeoJSON FeatureCollection of polygons, largest first.
|
||||||
def self.isochrone(valhalla_url, center, minutes, vehicle, avoid = {})
|
def self.isochrone(valhalla_url, center, minutes, vehicle)
|
||||||
lon, lat = center
|
lon, lat = center
|
||||||
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
|
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) }
|
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, avoid)
|
costing, options = costing(vehicle)
|
||||||
valhalla(valhalla_url, "/isochrone",
|
valhalla(valhalla_url, "/isochrone",
|
||||||
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
|
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
|
||||||
contours: minutes.map { |m| { time: m } }, polygons: true)
|
contours: minutes.map { |m| { time: m } }, polygons: true)
|
||||||
@@ -281,13 +220,8 @@ module Maptool
|
|||||||
end
|
end
|
||||||
|
|
||||||
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
|
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
|
||||||
def self.costing(vehicle, avoid = {})
|
def self.costing(vehicle)
|
||||||
limits = vehicle.slice(*VEHICLE_LIMITS.keys).compact
|
vehicle[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", vehicle.slice(:height, :width)] : ["truck", vehicle]
|
||||||
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
|
end
|
||||||
private_class_method :costing
|
private_class_method :costing
|
||||||
|
|
||||||
|
|||||||
Generated
+4
-4
@@ -9,7 +9,7 @@
|
|||||||
"flag-icons": "7.6.0",
|
"flag-icons": "7.6.0",
|
||||||
"maplibre-contour": "0.1.1",
|
"maplibre-contour": "0.1.1",
|
||||||
"maplibre-gl": "6.18.0",
|
"maplibre-gl": "6.18.0",
|
||||||
"maplibre-gl-lanes": "1.6.0",
|
"maplibre-gl-lanes": "1.5.0",
|
||||||
"pmtiles": "4.5.0",
|
"pmtiles": "4.5.0",
|
||||||
"suncalc": "2.1.4"
|
"suncalc": "2.1.4"
|
||||||
}
|
}
|
||||||
@@ -210,9 +210,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/maplibre-gl-lanes": {
|
"node_modules/maplibre-gl-lanes": {
|
||||||
"version": "1.6.0",
|
"version": "1.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.5.0.tgz",
|
||||||
"integrity": "sha512-cnHkrQW9LYD9j0HtVoptOMq2LG/HjEC3pWqLpwhElIzViF3ho+BP8E+YH3wS0Af/J34Wum2mlrRFFWAvw88H1g==",
|
"integrity": "sha512-oiqErfZuvgRNMolvYNYhZYmldk0oHNcMFDGEKzEHJ9mXzf98GLOGA90RuMXhh5k2E49J1Y3foaVOCYIu4s1YFw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@
|
|||||||
"flag-icons": "7.6.0",
|
"flag-icons": "7.6.0",
|
||||||
"maplibre-contour": "0.1.1",
|
"maplibre-contour": "0.1.1",
|
||||||
"maplibre-gl": "6.18.0",
|
"maplibre-gl": "6.18.0",
|
||||||
"maplibre-gl-lanes": "1.6.0",
|
"maplibre-gl-lanes": "1.5.0",
|
||||||
"pmtiles": "4.5.0",
|
"pmtiles": "4.5.0",
|
||||||
"suncalc": "2.1.4"
|
"suncalc": "2.1.4"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2336,47 +2336,10 @@ html, body {
|
|||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.route-panel__vehicle[hidden] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.route-panel__vehicle input {
|
.route-panel__vehicle input {
|
||||||
width: 4.5em;
|
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 {
|
.route-marker {
|
||||||
width: 22px;
|
width: 22px;
|
||||||
height: 22px;
|
height: 22px;
|
||||||
|
|||||||
+21
-109
@@ -10,12 +10,7 @@ const ISOCHRONE_URL = "/api/isochrone";
|
|||||||
const REACH_SOURCE = "route-reach";
|
const REACH_SOURCE = "route-reach";
|
||||||
const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart
|
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 GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel
|
||||||
const VEHICLES_URL = "/api/vehicles";
|
const VEHICLE_URL = "/api/vehicle";
|
||||||
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 NOTES_URL = "/api/library/notes";
|
||||||
const SOURCE = "route";
|
const SOURCE = "route";
|
||||||
const COLOR = "#1d6fdc";
|
const COLOR = "#1d6fdc";
|
||||||
@@ -67,8 +62,6 @@ export class RoutePanelControl {
|
|||||||
this._list = this._panel.querySelector(".route-panel__points");
|
this._list = this._panel.querySelector(".route-panel__points");
|
||||||
this._summary = this._panel.querySelector(".route-panel__summary");
|
this._summary = this._panel.querySelector(".route-panel__summary");
|
||||||
this._directions = this._panel.querySelector(".route-panel__directions");
|
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._saveButton = this._panel.querySelector('[data-action="save"]');
|
||||||
this._panel.querySelector('[data-action="reverse"]').addEventListener("click", () => {
|
this._panel.querySelector('[data-action="reverse"]').addEventListener("click", () => {
|
||||||
this._points.reverse();
|
this._points.reverse();
|
||||||
@@ -148,8 +141,6 @@ export class RoutePanelControl {
|
|||||||
// A saved route's points back in the panel; Save then updates that item.
|
// A saved route's points back in the panel; Save then updates that item.
|
||||||
_edit(key, feature) {
|
_edit(key, feature) {
|
||||||
this._clear();
|
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 }));
|
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
|
||||||
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
|
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
|
||||||
this._setOpen(true);
|
this._setOpen(true);
|
||||||
@@ -228,7 +219,7 @@ export class RoutePanelControl {
|
|||||||
const response = await fetch(ROUTE_URL, {
|
const response = await fetch(ROUTE_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
|
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat) }),
|
||||||
});
|
});
|
||||||
data = await response.json().catch(() => ({}));
|
data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) error = data.error || `routing failed (${response.status})`;
|
if (!response.ok) error = data.error || `routing failed (${response.status})`;
|
||||||
@@ -246,7 +237,6 @@ export class RoutePanelControl {
|
|||||||
this._saveButton.hidden = !route || !isLoggedIn();
|
this._saveButton.hidden = !route || !isLoggedIn();
|
||||||
this._directions.hidden = !route;
|
this._directions.hidden = !route;
|
||||||
this._profileButton.hidden = true;
|
this._profileButton.hidden = true;
|
||||||
this._showCountries(route?.properties.countries);
|
|
||||||
if (!route) {
|
if (!route) {
|
||||||
this._summary.textContent = message;
|
this._summary.textContent = message;
|
||||||
return;
|
return;
|
||||||
@@ -297,7 +287,7 @@ export class RoutePanelControl {
|
|||||||
const response = await fetch(ISOCHRONE_URL, {
|
const response = await fetch(ISOCHRONE_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ center, minutes, vehicle: this._vehicleId, avoid: this._avoid }),
|
body: JSON.stringify({ center, minutes }),
|
||||||
});
|
});
|
||||||
const data = await response.json().catch(() => ({}));
|
const data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) throw new Error(data.error || `failed (${response.status})`);
|
if (!response.ok) throw new Error(data.error || `failed (${response.status})`);
|
||||||
@@ -402,109 +392,31 @@ export class RoutePanelControl {
|
|||||||
return features.find((f) => f.geometry.type === "LineString")?.properties.id;
|
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 --------------------------------------------------------------
|
// --- vehicle --------------------------------------------------------------
|
||||||
|
|
||||||
// Profiles (Car, Camper, ...) are shared and edited only when logged in;
|
// Readable by anyone, saved only when logged in; a change re-routes.
|
||||||
// which one is in use is this browser's own choice. A change re-routes.
|
|
||||||
async _setupVehicle() {
|
async _setupVehicle() {
|
||||||
const select = this._panel.querySelector(".route-panel__vehicle-select");
|
const inputs = [...this._panel.querySelectorAll(".route-panel__vehicle input")];
|
||||||
const editButton = this._panel.querySelector('[data-action="vehicle-edit"]');
|
|
||||||
const fieldset = this._panel.querySelector(".route-panel__vehicle");
|
|
||||||
const inputs = [...fieldset.querySelectorAll("input")];
|
|
||||||
try {
|
try {
|
||||||
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
this._vehicle = await (await fetch(VEHICLE_URL)).json();
|
||||||
} catch {
|
} catch {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const current = () => this._vehicles.find((v) => v.id === this._vehicleId) || this._vehicles[0];
|
inputs.forEach((input) => {
|
||||||
const fill = () => {
|
input.value = this._vehicle[input.name];
|
||||||
select.replaceChildren(...this._vehicles.map((v) => new Option(v.name, v.id)));
|
input.disabled = !isLoggedIn();
|
||||||
this._vehicle = current();
|
input.addEventListener("change", async () => {
|
||||||
this._vehicleId = select.value = this._vehicle.id;
|
const body = new URLSearchParams(inputs.map((i) => [i.name, i.value]));
|
||||||
inputs.forEach((input) => (input.value = this._vehicle[input.name] ?? ""));
|
const response = await fetch(VEHICLE_URL, { method: "PUT", body });
|
||||||
};
|
const data = await response.json().catch(() => ({}));
|
||||||
this._selectVehicle = (id) => {
|
if (!response.ok) {
|
||||||
this._vehicleId = id;
|
window.alert(data.error || "Could not save the vehicle.");
|
||||||
try {
|
input.value = this._vehicle[input.name];
|
||||||
localStorage.setItem(VEHICLE_KEY, id);
|
return;
|
||||||
} catch {}
|
}
|
||||||
fill();
|
this._vehicle = data;
|
||||||
};
|
this._fetchRoute();
|
||||||
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) {
|
|
||||||
this._vehicles = data;
|
|
||||||
} else {
|
|
||||||
window.alert(data.error || "Could not save the vehicles.");
|
|
||||||
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
|
||||||
}
|
|
||||||
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();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-18
@@ -3,7 +3,6 @@ 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);
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
||||||
|
|
||||||
// src/core/graph.ts
|
// src/core/graph.ts
|
||||||
var ONEWAY_VALUES = /* @__PURE__ */ new Set(["yes", "true", "1", "-1", !0, 1, -1]);
|
|
||||||
function lngLatToMercator(lng, lat) {
|
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;
|
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];
|
return [x, y];
|
||||||
@@ -13,7 +12,7 @@ function mercatorToLngLat(x, y) {
|
|||||||
return [lng, lat];
|
return [lng, lat];
|
||||||
}
|
}
|
||||||
function buildLineGraph(features, opts = {}) {
|
function buildLineGraph(features, opts = {}) {
|
||||||
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 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 kx = Math.round(lng / snap), ky = Math.round(lat / snap);
|
let kx = Math.round(lng / snap), ky = Math.round(lat / snap);
|
||||||
return `${kx},${ky}`;
|
return `${kx},${ky}`;
|
||||||
};
|
};
|
||||||
@@ -102,13 +101,7 @@ function buildLineGraph(features, opts = {}) {
|
|||||||
direction.set(r, d === 0 ? 0 : walkForward ? d : -d);
|
direction.set(r, d === 0 ? 0 : walkForward ? d : -d);
|
||||||
}
|
}
|
||||||
let edge = { id, a, b, coords, routes: [...first.routes.keys()].sort(), direction, order: [] };
|
let edge = { id, a, b, coords, routes: [...first.routes.keys()].sort(), direction, order: [] };
|
||||||
if (first.props)
|
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 (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())
|
for (let vk of adjacency.keys())
|
||||||
if (isJunction(vk))
|
if (isJunction(vk))
|
||||||
@@ -131,12 +124,7 @@ function deriveChains(nodes, edges, routes) {
|
|||||||
}
|
}
|
||||||
let l = Math.hypot(dx, dy) || 1;
|
let l = Math.hypot(dx, dy) || 1;
|
||||||
return [dx / l, dy / l];
|
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()) {
|
for (let rid of routes.keys()) {
|
||||||
let routeEdges = edges.filter((e) => e.routes.includes(rid));
|
let routeEdges = edges.filter((e) => e.routes.includes(rid));
|
||||||
if (!routeEdges.length) {
|
if (!routeEdges.length) {
|
||||||
@@ -170,9 +158,9 @@ function deriveChains(nodes, edges, routes) {
|
|||||||
steps.push({ edge: nextEdge.id, forward }), unused.delete(nextEdge.id);
|
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);
|
let far = forward ? nextEdge.b : nextEdge.a, farEnd = forward ? "b" : "a", d = outDir(nextEdge.id, farEnd);
|
||||||
arriving = [-d[0], -d[1]], node = far;
|
arriving = [-d[0], -d[1]], node = far;
|
||||||
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);
|
let best = null, bestDot = -1 / 0;
|
||||||
for (let p of nodes[node].ports) {
|
for (let p of nodes[node].ports) {
|
||||||
if (!unused.has(p.edge) || hasAgreeing && clash(arrFlow, flowAt(rid, p.edge, p.end))) continue;
|
if (!unused.has(p.edge)) continue;
|
||||||
let o = outDir(p.edge, p.end), dot = o[0] * arriving[0] + o[1] * arriving[1];
|
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]);
|
(dot > bestDot + 1e-9 || Math.abs(dot - bestDot) <= 1e-9 && best && p.edge < best.id) && (bestDot = dot, best = edges[p.edge]);
|
||||||
}
|
}
|
||||||
@@ -193,7 +181,7 @@ function deriveChains(nodes, edges, routes) {
|
|||||||
if (n.ports.forEach((p, i) => {
|
if (n.ports.forEach((p, i) => {
|
||||||
if (i === ce.port || !edges[p.edge].routes.includes(rid)) return;
|
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];
|
let o = outDir(p.edge, p.end), dot = o[0] * arriveDir[0] + o[1] * arriveDir[1];
|
||||||
clash(flowAt(rid, own.edge, own.end), flowAt(rid, p.edge, p.end)) && (dot -= 4), dot > bestDot && (bestDot = dot, best = i);
|
dot > bestDot && (bestDot = dot, best = i);
|
||||||
}), best < 0) continue;
|
}), best < 0) continue;
|
||||||
let key = `${ce.node}:${Math.min(ce.port, best)}:${Math.max(ce.port, best)}`;
|
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);
|
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
|
assert_equal 422, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [999]), "CONTENT_TYPE" => "application/json").status
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_vehicles_are_readable_by_anyone_but_saved_only_when_logged_in
|
def test_the_vehicle_is_readable_by_anyone_but_saved_only_when_logged_in
|
||||||
assert_equal "Car", json_body(request.get("/api/vehicles")).first["name"]
|
assert_equal 3.0, json_body(request.get("/api/vehicle"))["height"]
|
||||||
vehicles = JSON.generate([{ id: "car", name: "Car" }, { id: "van", name: "Van", height: 3.3 }])
|
vehicle = { height: 3.3, width: 2.3, length: 7, weight: 3.5 }
|
||||||
assert_equal 401, request.put("/api/vehicles", input: vehicles).status
|
assert_equal 401, request.put("/api/vehicle", params: vehicle).status
|
||||||
assert_equal 3.3, json_body(request.put("/api/vehicles", input: vehicles, **logged_in_env)).last["height"]
|
assert_equal 3.3, json_body(request.put("/api/vehicle", params: vehicle, **logged_in_env))["height"]
|
||||||
assert_equal 400, request.put("/api/vehicles", input: "[]", **logged_in_env).status
|
assert_equal 400, request.put("/api/vehicle", params: vehicle.merge(weight: 0), **logged_in_env).status
|
||||||
ensure
|
ensure
|
||||||
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicles.json"))
|
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicle.json"))
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_changes_and_exports_need_login
|
def test_changes_and_exports_need_login
|
||||||
|
|||||||
+21
-53
@@ -25,18 +25,16 @@ class RoutingTest < Minitest::Test
|
|||||||
assert_equal "waiting for the routing container", Maptool::Routing.build_status(@data)[:step]
|
assert_equal "waiting for the routing container", Maptool::Routing.build_status(@data)[:step]
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_a_request_while_the_offline_build_downloads_waits_for_the_extracts_only
|
def test_a_request_during_an_offline_build_waits_for_it
|
||||||
Maptool::PmtilesBuilder.instance_variable_set(:@fetching_extracts, true)
|
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
||||||
Maptool::Routing.request_build(@data)
|
Maptool::Routing.request_build(@data)
|
||||||
assert_equal "waiting for the offline map downloads", Maptool::Routing.build_status(@data)[:step]
|
assert_equal "waiting for the offline map build", Maptool::Routing.build_status(@data)[:step]
|
||||||
refute File.exist?(File.join(@routing, "build-request.json"))
|
refute File.exist?(File.join(@routing, "build-request.json"))
|
||||||
|
|
||||||
# Planetiler still running doesn't matter, the extracts are in.
|
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "done")
|
||||||
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
||||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
Maptool::Routing.offline_build_finished(@data)
|
||||||
Maptool::PmtilesBuilder.send(:extracts_ready, @data)
|
|
||||||
assert File.exist?(File.join(@routing, "build-request.json"))
|
assert File.exist?(File.join(@routing, "build-request.json"))
|
||||||
refute Maptool::PmtilesBuilder.fetching_extracts?
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_update_check_compares_regions_and_extract_age
|
def test_update_check_compares_regions_and_extract_age
|
||||||
@@ -94,22 +92,11 @@ class RoutingTest < Minitest::Test
|
|||||||
refute File.exist?(File.join(@routing, "build-request.json"))
|
refute File.exist?(File.join(@routing, "build-request.json"))
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_vehicle_profiles_are_validated_and_stored
|
def test_the_vehicle_is_validated_and_stored
|
||||||
assert_equal %w[car camper], Maptool::Routing.vehicles(@data).map { |v| v[:id] }
|
assert_equal Maptool::Routing::DEFAULT_VEHICLE, Maptool::Routing.vehicle(@data)
|
||||||
assert_equal "Car", Maptool::Routing.vehicle(@data, "nope")[:name]
|
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]
|
||||||
Maptool::Routing.save_vehicles(@data, [{ "id" => "car", "name" => "Car", "height" => "" },
|
assert_raises(ArgumentError) { Maptool::Routing.save_vehicle(@data, "height" => "30", "width" => "2", "length" => "8", "weight" => "3") }
|
||||||
{ "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
|
end
|
||||||
|
|
||||||
def test_decode_polyline_reads_valhallas_precision_6
|
def test_decode_polyline_reads_valhallas_precision_6
|
||||||
@@ -121,40 +108,24 @@ class RoutingTest < Minitest::Test
|
|||||||
shape = "wdg|xA{ubdQc@w@"
|
shape = "wdg|xA{ubdQc@w@"
|
||||||
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
|
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
|
||||||
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] })
|
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] })
|
||||||
# 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}") do |url|
|
||||||
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_VEHICLE)
|
||||||
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]]
|
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
|
||||||
end
|
end
|
||||||
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
|
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|
|
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_VEHICLES[1].merge(weight: 7.5)) }
|
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
|
assert_equal "no route", error.message
|
||||||
end
|
end
|
||||||
assert_includes request, %("costing":"truck")
|
assert_includes request, %("costing":"truck")
|
||||||
assert_raises(Maptool::Routing::Unavailable) { Maptool::Routing.route("", [[1, 2], [3, 4]], {}) }
|
assert_raises(Maptool::Routing::Unavailable) { Maptool::Routing.route("", [[1, 2], [3, 4]], {}) }
|
||||||
end
|
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
|
def test_isochrone_asks_valhalla_for_each_time_and_checks_them
|
||||||
reply = JSON.generate(type: "FeatureCollection", features: [])
|
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|
|
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_VEHICLES[1])["type"]
|
assert_equal "FeatureCollection", Maptool::Routing.isochrone(url, [17.1, 48.1], [60, 30, 60], Maptool::Routing::DEFAULT_VEHICLE)["type"]
|
||||||
end
|
end
|
||||||
assert_includes request, %("contours":[{"time":30},{"time":60}])
|
assert_includes request, %("contours":[{"time":30},{"time":60}])
|
||||||
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", [17.1, 48.1], [600], {}) }
|
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.isochrone("http://x", [17.1, 48.1], [600], {}) }
|
||||||
@@ -175,19 +146,16 @@ class RoutingTest < Minitest::Test
|
|||||||
ENV.delete("OSMIUM_BIN")
|
ENV.delete("OSMIUM_BIN")
|
||||||
end
|
end
|
||||||
|
|
||||||
# Answers one HTTP request per response, in order; returns what was received.
|
# Answers one HTTP request with `response`; returns what was received.
|
||||||
def serve_once(*responses)
|
def serve_once(response)
|
||||||
server = TCPServer.new("127.0.0.1", 0)
|
server = TCPServer.new("127.0.0.1", 0)
|
||||||
received = +""
|
received = +""
|
||||||
thread = Thread.new do
|
thread = Thread.new do
|
||||||
responses.each do |response|
|
client = server.accept
|
||||||
client = server.accept
|
received << client.readpartial(65_536)
|
||||||
request = client.readpartial(65_536)
|
received << client.readpartial(65_536) unless received.include?("{")
|
||||||
request << client.readpartial(65_536) unless request.include?("{")
|
client.write(response)
|
||||||
received << request
|
client.close
|
||||||
client.write(response)
|
|
||||||
client.close
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
yield "http://127.0.0.1:#{server.addr[1]}"
|
yield "http://127.0.0.1:#{server.addr[1]}"
|
||||||
thread.join
|
thread.join
|
||||||
|
|||||||
+6
-19
@@ -121,7 +121,6 @@
|
|||||||
<button type="button" data-action="save" hidden>Save to library</button>
|
<button type="button" data-action="save" hidden>Save to library</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="route-panel__summary"></p>
|
<p class="route-panel__summary"></p>
|
||||||
<ul class="route-panel__countries" hidden></ul>
|
|
||||||
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
|
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
|
||||||
<details class="route-panel__directions" hidden>
|
<details class="route-panel__directions" hidden>
|
||||||
<summary>Directions</summary>
|
<summary>Directions</summary>
|
||||||
@@ -139,24 +138,12 @@
|
|||||||
<button type="button" data-action="reach-clear" hidden>Hide</button>
|
<button type="button" data-action="reach-clear" hidden>Hide</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="route-panel__reach-status" hidden></p>
|
<p class="route-panel__reach-status" hidden></p>
|
||||||
<div class="route-panel__vehicle-row">
|
<fieldset class="route-panel__vehicle">
|
||||||
<label>Vehicle <select class="route-panel__vehicle-select"></select></label>
|
<legend>Vehicle</legend>
|
||||||
<button type="button" data-action="vehicle-edit" hidden>Edit</button>
|
<label>Height <input type="number" name="height" step="0.1" min="1" max="6"> m</label>
|
||||||
</div>
|
<label>Width <input type="number" name="width" step="0.1" min="1" max="4"> m</label>
|
||||||
<div class="route-panel__avoid">
|
<label>Length <input type="number" name="length" step="0.5" min="2" max="25"> m</label>
|
||||||
Avoid
|
<label>Weight <input type="number" name="weight" step="0.1" min="0.5" max="60"> t</label>
|
||||||
<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>
|
</fieldset>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in new issue
Block a user