Skip to main content

strata_web_api/
geolocation.rs

1//! W3C Geolocation API with Coordinate Math and Great-Circle Distance Solving.
2
3use std::fmt;
4use std::sync::{Arc, RwLock};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7/// W3C Geographic coordinates.
8#[derive(Debug, Clone, PartialEq)]
9pub struct GeoCoordinates {
10    pub latitude: f64,
11    pub longitude: f64,
12    pub altitude: Option<f64>,
13    pub accuracy: f64,
14    pub altitude_accuracy: Option<f64>,
15    pub heading: Option<f64>,
16    pub speed: Option<f64>,
17}
18
19impl GeoCoordinates {
20    pub fn new(latitude: f64, longitude: f64, accuracy: f64) -> Self {
21        Self {
22            latitude,
23            longitude,
24            altitude: None,
25            accuracy,
26            altitude_accuracy: None,
27            heading: None,
28            speed: None,
29        }
30    }
31}
32
33/// A complete W3C Geolocation position snapshot.
34#[derive(Debug, Clone, PartialEq)]
35pub struct GeolocationPosition {
36    pub coords: GeoCoordinates,
37    pub timestamp: u64,
38}
39
40impl GeolocationPosition {
41    pub fn new(coords: GeoCoordinates) -> Self {
42        let timestamp = SystemTime::now()
43            .duration_since(UNIX_EPOCH)
44            .map(|d| d.as_millis() as u64)
45            .unwrap_or(0);
46        Self { coords, timestamp }
47    }
48}
49
50/// Errors occurring during geolocation lookups.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum GeolocationError {
53    PermissionDenied(String),
54    PositionUnavailable(String),
55    Timeout(String),
56}
57
58impl fmt::Display for GeolocationError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            Self::PermissionDenied(s) => write!(f, "Geolocation permission denied: {s}"),
62            Self::PositionUnavailable(s) => write!(f, "Position unavailable: {s}"),
63            Self::Timeout(s) => write!(f, "Geolocation lookup timed out: {s}"),
64        }
65    }
66}
67
68impl std::error::Error for GeolocationError {}
69
70/// Options for acquiring geolocation.
71#[derive(Debug, Clone)]
72pub struct GeolocationOptions {
73    pub enable_high_accuracy: bool,
74    pub timeout_ms: u64,
75    pub maximum_age_ms: u64,
76}
77
78impl Default for GeolocationOptions {
79    fn default() -> Self {
80        Self {
81            enable_high_accuracy: false,
82            timeout_ms: 10000,
83            maximum_age_ms: 0,
84        }
85    }
86}
87
88/// Thread-safe Geolocation controller.
89#[derive(Clone)]
90pub struct Geolocation {
91    current_position: Arc<RwLock<Option<GeolocationPosition>>>,
92}
93
94impl Default for Geolocation {
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100impl Geolocation {
101    pub fn new() -> Self {
102        Self {
103            current_position: Arc::new(RwLock::new(None)),
104        }
105    }
106
107    /// Configures or injects a mock coordinate (e.g. for testing or headless simulation).
108    pub fn set_mock_position(&self, coords: GeoCoordinates) {
109        if let Ok(mut pos) = self.current_position.write() {
110            *pos = Some(GeolocationPosition::new(coords));
111        }
112    }
113
114    /// Retrieves the current device position snapshot.
115    pub fn get_current_position(&self) -> Result<GeolocationPosition, GeolocationError> {
116        let pos = self
117            .current_position
118            .read()
119            .map_err(|e| GeolocationError::PositionUnavailable(e.to_string()))?;
120
121        pos.clone().ok_or_else(|| {
122            GeolocationError::PositionUnavailable(
123                "No position available from device provider".into(),
124            )
125        })
126    }
127}
128
129/// Calculates great-circle distance between two WGS84 coordinates using the Haversine formula.
130/// Returns distance in meters.
131pub fn haversine_distance_meters(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
132    const EARTH_RADIUS_METERS: f64 = 6_371_000.0;
133
134    let d_lat = (lat2 - lat1).to_radians();
135    let d_lon = (lon2 - lon1).to_radians();
136
137    let rad_lat1 = lat1.to_radians();
138    let rad_lat2 = lat2.to_radians();
139
140    let a =
141        (d_lat / 2.0).sin().powi(2) + rad_lat1.cos() * rad_lat2.cos() * (d_lon / 2.0).sin().powi(2);
142
143    let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
144
145    EARTH_RADIUS_METERS * c
146}
147
148/// Calculates the initial bearing (forward azimuth) from coordinate 1 to coordinate 2 in degrees [0, 360).
149pub fn initial_bearing_degrees(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
150    let d_lon = (lon2 - lon1).to_radians();
151    let rad_lat1 = lat1.to_radians();
152    let rad_lat2 = lat2.to_radians();
153
154    let y = d_lon.sin() * rad_lat2.cos();
155    let x = rad_lat1.cos() * rad_lat2.sin() - rad_lat1.sin() * rad_lat2.cos() * d_lon.cos();
156
157    let bearing_rad = y.atan2(x);
158    let bearing_deg = bearing_rad.to_degrees();
159
160    (bearing_deg + 360.0) % 360.0
161}