Offline routing phase 2: route panel, /api/route via Valhalla, vehicle profile, save a route to the library

This commit is contained in:
randy committed 2026-11-13 22:34:47 +01:00
1 parent d93c77727f
commit 3146478c23
11 files changed
+577 -12

No files matched your search

+78
View File
@@ -114,6 +114,84 @@ module Maptool
end
private_class_method :write_json
class RouteError < StandardError; end
class Unavailable < StandardError; end
# A camper by default; one profile for now (docs/routing-design.adoc).
DEFAULT_VEHICLE = { height: 3.0, width: 2.3, length: 7.0, weight: 3.5 }.freeze
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
# Up to this weight Valhalla's "auto" costing (with height/width) fits
# better than "truck": a camper isn't kept off roads closed to lorries.
CAR_MAX_WEIGHT = 3.5
def self.vehicle(data_dir)
DEFAULT_VEHICLE.merge(read_json(File.join(data_dir, "vehicle.json")) || {})
end
def self.save_vehicle(data_dir, values)
vehicle = VEHICLE_LIMITS.to_h do |key, range|
value = Float(values.fetch(key.to_s), exception: false)
raise ArgumentError, "#{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
[key, value]
end
write_json(File.join(data_dir, "vehicle.json"), vehicle)
vehicle
end
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
# (km), time (s) and the turn-by-turn instructions.
def self.route(valhalla_url, locations, vehicle)
raise RouteError, "at least two points are needed" if locations.size < 2
raise Unavailable, "routing is not set up" if valhalla_url.to_s.empty?
car = vehicle[:weight] <= CAR_MAX_WEIGHT
costing = car ? "auto" : "truck"
options = car ? vehicle.slice(:height, :width) : vehicle
body = { locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers" }
uri = URI("#{valhalla_url}/route")
response = begin
Net::HTTP.start(uri.host, uri.port, open_timeout: 2, read_timeout: 60) do |http|
http.post(uri.path, JSON.generate(body), "Content-Type" => "application/json")
end
rescue SystemCallError, Net::OpenTimeout, SocketError
raise Unavailable, "the routing service is not running"
end
data = JSON.parse(response.body)
raise RouteError, data["error"] || "no route found" unless response.is_a?(Net::HTTPSuccess)
legs = data["trip"]["legs"]
{ type: "Feature",
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
time_s: data["trip"]["summary"]["time"],
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates"
end
# Valhalla's encoded polyline (precision 6) → [[lon, lat], ...].
def self.decode_polyline(encoded)
values = []
value = shift = 0
encoded.each_byte do |byte|
byte -= 63
value |= (byte & 0x1f) << shift
shift += 5
next if byte >= 0x20
values << ((value & 1).zero? ? value >> 1 : ~(value >> 1))
value = shift = 0
end
lat = lon = 0
values.each_slice(2).map do |dlat, dlon|
lat += dlat
lon += dlon
[lon / 1e6, lat / 1e6]
end
end
def self.reset!
MUTEX.synchronize { @pending = false }
end