From 15bc16d21f43bb498924662ea977e3a8b2471045 Mon Sep 17 00:00:00 2001 From: konsumlamm <44230978+konsumlamm@users.noreply.github.com> Date: Fri, 24 May 2024 14:32:29 +0200 Subject: [PATCH] Better `distance` & add `nearest_stop` (#35) --- robusta/src/kvv.rs | 13 +++++++++++++ robusta/src/point.rs | 9 ++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/robusta/src/kvv.rs b/robusta/src/kvv.rs index 87cff18..cefe0ef 100644 --- a/robusta/src/kvv.rs +++ b/robusta/src/kvv.rs @@ -342,3 +342,16 @@ pub fn train_positions(departures_per_line: &LineDepartures, render_time: DateTi .flat_map(|(journey_ref, departures)| train_position_per_route(render_time, journey_ref, departures, stops)) .collect() } + +pub fn nearest_stop(pos: Point) -> &'static Stop { + let stops = KVV_STOPS.get().expect("KVV_STOPS not initialized"); + stops + .iter() + .min_by_key(|stop| { + pos.distance(Point { + latitude: stop.lat as f32, + longitude: stop.lon as f32, + }) as u64 + }) + .expect("no stops") +} diff --git a/robusta/src/point.rs b/robusta/src/point.rs index 63de632..28ec7e3 100644 --- a/robusta/src/point.rs +++ b/robusta/src/point.rs @@ -5,8 +5,15 @@ pub struct Point { } impl Point { + /// The approximate distance between two points in meters, using equirectangular projection. pub fn distance(self, other: Self) -> f32 { - f32::hypot(other.latitude - self.latitude, other.longitude - self.longitude) + // the radius of the earth in meters + const EARTH_RADIUS: f32 = 6371008.8; + + let delta_lat = (other.latitude - self.latitude).to_radians(); + let delta_lon = (other.longitude - self.longitude).to_radians(); + let mean_lat = (self.latitude + other.latitude) / 2.0; + EARTH_RADIUS * f32::hypot(delta_lat, f32::cos(mean_lat) * delta_lon) } /// Linear interpolation.