algorithms_edu/algo/geometry/
geographical_coordinate.rs

1#[derive(Debug, Copy, Clone)]
2pub struct GeographicalCoordinate {
3    longitude: f64,
4    latitude: f64,
5}
6
7impl GeographicalCoordinate {
8    pub fn new(longitude: f64, latitude: f64) -> Self {
9        Self {
10            longitude,
11            latitude,
12        }
13    }
14    /// See: <https://en.wikipedia.org/wiki/Haversine_formula>
15    pub fn distance(self, other: Self) -> f64 {
16        const EARTH_RADIUS: f64 = 6378.1; // kilometers
17
18        let (lat1, lon1) = (self.latitude.to_radians(), self.longitude.to_radians());
19        let (lat2, lon2) = (other.latitude.to_radians(), other.longitude.to_radians());
20
21        let delta_lat = lat2 - lat1;
22        let delta_lon = lon2 - lon1;
23        let x = (delta_lat / 2.0).sin().powi(2)
24            + lat1.cos() * lat2.cos() * (delta_lon / 2.0).sin().powi(2);
25        2.0 * EARTH_RADIUS * x.sqrt().atan()
26    }
27}