67 lines
2.5 KiB
Ruby
67 lines
2.5 KiB
Ruby
module Maptool
|
||
# A corridor either side of a route ([[lon, lat], ...]): what a plugin run
|
||
# along the trip's route covers (lib/maptool/plugins.rb). Flat-earth
|
||
# distances (equirectangular per segment) — fine for a few km either side.
|
||
module Corridor
|
||
KM_PER_DEG = 111.32
|
||
|
||
def self.km(a, b)
|
||
Math.hypot((b[0] - a[0]) * Math.cos((a[1] + b[1]) / 2 * Math::PI / 180), b[1] - a[1]) * KM_PER_DEG
|
||
end
|
||
|
||
# The route's vertices at least step_km apart (its ends kept): a short
|
||
# enough line for a query (Overpass' around: takes a polyline).
|
||
def self.thin(coords, step_km)
|
||
kept = [coords.first]
|
||
coords.each { |c| kept << c if km(kept.last, c) >= step_km }
|
||
kept << coords.last unless kept.last == coords.last
|
||
kept
|
||
end
|
||
|
||
# Circles ([[lon, lat], radius km]) covering the corridor half_km either
|
||
# side: centers every 1.5 × half_km along the line, radius 1.25 × half_km
|
||
# (√(0.75² + 1²) = 1.25, so no gap between two of them at the corridor's edge).
|
||
def self.circles(coords, half_km)
|
||
step = 1.5 * half_km
|
||
centers = [coords.first]
|
||
left = step
|
||
coords.each_cons(2) do |a, b|
|
||
length = km(a, b)
|
||
at = 0.0
|
||
while length - at >= left
|
||
at += left
|
||
t = at / length
|
||
centers << [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
|
||
left = step
|
||
end
|
||
left -= length - at
|
||
end
|
||
centers << coords.last unless centers.last == coords.last
|
||
centers.map { |c| [c, 1.25 * half_km] }
|
||
end
|
||
|
||
# Shortest distance (km) from a point to the line.
|
||
def self.distance_km(point, coords)
|
||
lat0 = point[1] * Math::PI / 180
|
||
xy = ->(c) { [(c[0] - point[0]) * Math.cos(lat0) * KM_PER_DEG, (c[1] - point[1]) * KM_PER_DEG] }
|
||
return Math.hypot(*xy.(coords.first)) if coords.size == 1
|
||
|
||
coords.each_cons(2).map do |a, b|
|
||
(ax, ay), (bx, by) = xy.(a), xy.(b)
|
||
dx, dy = bx - ax, by - ay
|
||
len2 = dx * dx + dy * dy
|
||
t = len2.zero? ? 0.0 : (-(ax * dx + ay * dy) / len2).clamp(0.0, 1.0)
|
||
Math.hypot(ax + t * dx, ay + t * dy)
|
||
end.min
|
||
end
|
||
|
||
# [south, west, north, east] around the line, half_km wider each way.
|
||
def self.bbox(coords, half_km)
|
||
lons, lats = coords.map(&:first), coords.map { |c| c[1] }
|
||
dlat = half_km / KM_PER_DEG
|
||
dlon = half_km / (KM_PER_DEG * Math.cos(lats.map(&:abs).max * Math::PI / 180))
|
||
[lats.min - dlat, lons.min - dlon, lats.max + dlat, lons.max + dlon]
|
||
end
|
||
end
|
||
end
|