use crate::{helpers::ApproxEq, units::distance::Kilometers};
use std::{fmt, fmt::Display};
#[derive(Copy, Clone, Debug)]
pub struct Coordinate {
pub lat: f64,
pub lon: f64,
}
impl Coordinate {
pub fn zero() -> Coordinate {
Coordinate { lat: 0.0, lon: 0.0 }
}
pub fn from_decimicro(decimicro_lat: i32, decimicro_lon: i32) -> Coordinate {
Coordinate {
lat: (decimicro_lat as f64 * 1e-7) as f64,
lon: (decimicro_lon as f64 * 1e-7) as f64,
}
}
}
impl Eq for Coordinate {}
impl PartialEq for Coordinate {
fn eq(&self, other: &Coordinate) -> bool {
self.lat.approx_eq(&other.lat) && self.lon.approx_eq(&other.lon)
}
}
impl Display for Coordinate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(lat: {}, lon: {})", self.lat, self.lon)
}
}
pub fn haversine_distance_km(from: &Coordinate, to: &Coordinate) -> Kilometers {
let earth_mean_radius = 6_371.0;
let from_lat = from.lat as f64;
let from_lon = from.lon as f64;
let to_lat = to.lat as f64;
let to_lon = to.lon as f64;
let delta_lat = (from_lat - to_lat).to_radians();
let delta_lon = (from_lon - to_lon).to_radians();
let from_lat_rad = from_lat.to_radians();
let to_lat_rad = to_lat.to_radians();
let sin_lat = (delta_lat / 2.0).sin();
let sin_lon = (delta_lon / 2.0).sin();
Kilometers(
(sin_lat * sin_lat + from_lat_rad.cos() * to_lat_rad.cos() * sin_lon * sin_lon)
.sqrt()
.asin()
* (2.0 * earth_mean_radius),
)
}