Vehicle profiles (Car, Camper, ...), avoid tolls/motorways, per-country vignette and toll km for a route
This commit is contained in:
1 parent
58ca871662
commit
69aa284e36
8 files changed
+328
-80
No files matched your search
+82
-17
@@ -163,33 +163,68 @@ module Maptool
|
||||
class Unavailable < StandardError; end
|
||||
|
||||
# A camper by default; one profile for now (docs/routing-design.adoc).
|
||||
DEFAULT_VEHICLE = { height: 3.0, width: 2.3, length: 7.0, weight: 3.5 }.freeze
|
||||
# Vehicle profiles: a name plus optional limits (nil: no limit, a plain
|
||||
# car). Stored for everyone, picked per browser (route.js).
|
||||
DEFAULT_VEHICLES = [
|
||||
{ id: "car", name: "Car" },
|
||||
{ id: "camper", name: "Camper", height: 3.0, width: 2.3, length: 7.0, weight: 3.5 },
|
||||
].freeze
|
||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
|
||||
# Up to this weight Valhalla's "auto" costing (with height/width) fits
|
||||
# better than "truck": a camper isn't kept off roads closed to lorries.
|
||||
CAR_MAX_WEIGHT = 3.5
|
||||
|
||||
def self.vehicle(data_dir)
|
||||
DEFAULT_VEHICLE.merge(read_json(File.join(data_dir, "vehicle.json")) || {})
|
||||
def self.vehicles(data_dir)
|
||||
read_json(File.join(data_dir, "vehicles.json")) || begin
|
||||
# The single vehicle stored before profiles became the camper.
|
||||
old = read_json(File.join(data_dir, "vehicle.json"))
|
||||
old ? [DEFAULT_VEHICLES[0], DEFAULT_VEHICLES[1].merge(old.slice(*VEHICLE_LIMITS.keys))] : DEFAULT_VEHICLES
|
||||
end
|
||||
end
|
||||
|
||||
def self.save_vehicle(data_dir, values)
|
||||
vehicle = VEHICLE_LIMITS.to_h do |key, range|
|
||||
value = Float(values.fetch(key.to_s), exception: false)
|
||||
raise ArgumentError, "#{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
|
||||
# The profile with this id, or the first one.
|
||||
def self.vehicle(data_dir, id = nil)
|
||||
list = vehicles(data_dir)
|
||||
list.find { |v| v[:id] == id } || list.first
|
||||
end
|
||||
|
||||
[key, value]
|
||||
# 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
|
||||
{ id: id, name: name, **limits.compact }
|
||||
end
|
||||
write_json(File.join(data_dir, "vehicle.json"), vehicle)
|
||||
vehicle
|
||||
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
|
||||
|
||||
write_json(File.join(data_dir, "vehicles.json"), vehicles)
|
||||
vehicles
|
||||
end
|
||||
|
||||
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
|
||||
# (km), time (s) and the turn-by-turn instructions.
|
||||
def self.route(valhalla_url, locations, vehicle)
|
||||
# (km), time (s), the turn-by-turn instructions and, per country, the
|
||||
# km on motorways and toll roads (for vignettes and tolls).
|
||||
# avoid: {"tolls" => true, "highways" => true}, for the whole route.
|
||||
def self.route(valhalla_url, locations, vehicle, avoid = {})
|
||||
raise RouteError, "at least two points are needed" if locations.size < 2
|
||||
|
||||
costing, options = costing(vehicle)
|
||||
costing, options = costing(vehicle, avoid)
|
||||
data = valhalla(valhalla_url, "/route",
|
||||
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
|
||||
costing: costing, costing_options: { costing => options }, units: "kilometers")
|
||||
@@ -198,21 +233,46 @@ module Maptool
|
||||
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
||||
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
||||
time_s: data["trip"]["summary"]["time"],
|
||||
countries: countries(valhalla_url, legs, costing, options),
|
||||
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
|
||||
rescue ArgumentError, TypeError
|
||||
raise RouteError, "invalid coordinates"
|
||||
end
|
||||
|
||||
# [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route order, from
|
||||
# Valhalla's per-edge attributes. nil if that lookup fails: it's extra.
|
||||
def self.countries(valhalla_url, legs, costing, options)
|
||||
totals = {}
|
||||
legs.each do |leg|
|
||||
data = valhalla(valhalla_url, "/trace_attributes",
|
||||
encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing,
|
||||
costing_options: { costing => options },
|
||||
filters: { attributes: %w[edge.length edge.road_class edge.toll node.admin_index admin.country_code], action: "include" })
|
||||
codes = data["admins"].map { |admin| admin["country_code"] }
|
||||
data["edges"].each do |edge|
|
||||
code = codes[edge.dig("end_node", "admin_index").to_i] || "?"
|
||||
row = totals[code] ||= { code: code, km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
|
||||
row[:km] += edge["length"]
|
||||
row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway"
|
||||
row[:toll_km] += edge["length"] if edge["toll"]
|
||||
end
|
||||
end
|
||||
totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } }
|
||||
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
|
||||
nil
|
||||
end
|
||||
private_class_method :countries
|
||||
|
||||
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
|
||||
|
||||
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
|
||||
# GeoJSON FeatureCollection of polygons, largest first.
|
||||
def self.isochrone(valhalla_url, center, minutes, vehicle)
|
||||
def self.isochrone(valhalla_url, center, minutes, vehicle, avoid = {})
|
||||
lon, lat = center
|
||||
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
|
||||
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
|
||||
|
||||
costing, options = costing(vehicle)
|
||||
costing, options = costing(vehicle, avoid)
|
||||
valhalla(valhalla_url, "/isochrone",
|
||||
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
|
||||
contours: minutes.map { |m| { time: m } }, polygons: true)
|
||||
@@ -221,8 +281,13 @@ module Maptool
|
||||
end
|
||||
|
||||
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
|
||||
def self.costing(vehicle)
|
||||
vehicle[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", vehicle.slice(:height, :width)] : ["truck", vehicle]
|
||||
def self.costing(vehicle, avoid = {})
|
||||
limits = vehicle.slice(*VEHICLE_LIMITS.keys).compact
|
||||
costing, options = limits[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", limits.slice(:height, :width)] : ["truck", limits]
|
||||
avoid = {} unless avoid.is_a?(Hash)
|
||||
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
|
||||
options = options.merge(use_highways: 0.0) if avoid["highways"]
|
||||
[costing, options]
|
||||
end
|
||||
private_class_method :costing
|
||||
|
||||
|
||||
Reference in new issue
Block a user