Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Haversine distance #62

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Implement Haversine distance
  • Loading branch information
tmcw authored and frewsxcv committed Jan 17, 2017
commit 81271dae1b8aee41686f0d4967c39017611106ad
46 changes: 46 additions & 0 deletions src/algorithm/haversine_distance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use num::{Float, FromPrimitive};
use types::{Point};

/// Returns the distance between two geometries.

pub trait HaversineDistance<T, Rhs = Self>
{
/// Returns the distance between two points:
///
/// ```
/// use geo::{COORD_PRECISION, Point};
/// use geo::algorithm::haversine_distance::HaversineDistance;
///
/// let p = Point::new(-72.1235, 42.3521);
/// let dist = p.haversine_distance(&Point::new(-72.1260, 42.45));
/// assert_eq!(dist, 10900.115612674515)
/// ```
fn haversine_distance(&self, rhs: &Rhs) -> T;
}

impl<T> HaversineDistance<T, Point<T>> for Point<T>
where T: Float + FromPrimitive
{
fn haversine_distance(&self, p: &Point<T>) -> T {
let a = (self.y().to_radians().sin() * p.y().to_radians().sin()) +
(self.y().to_radians().cos() * p.y().to_radians().cos()) *
(p.x() - self.x()).to_radians().cos();
T::from_i32(6378137).unwrap() * a.acos().min(T::one())
}
}

#[cfg(test)]
mod test {
use types::{Point};
use algorithm::haversine_distance::{HaversineDistance};
#[test]
fn distance1_test() {
assert_eq!(Point::<f64>::new(0., 0.).haversine_distance(&Point::<f64>::new(1., 0.)), 111319.49079326246_f64);
}
#[test]
fn distance2_test() {
// Point::new(-72.1235, 42.3521).distance(&Point::new(72.1260, 70.612)) = 146.99163308930207
let dist = Point::new(-72.1235, 42.3521).haversine_distance(&Point::new(72.1260, 70.612));
assert_eq!(dist, 6378137_f64);
}
}
2 changes: 2 additions & 0 deletions src/algorithm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ pub mod area;
pub mod length;
/// Returns the distance between two geometries.
pub mod distance;
/// Returns the distance between two geometries.
pub mod haversine_distance;
/// Returns the Bbox of a geometry.
pub mod boundingbox;
/// Simplifies a `LineString` using the Ramer-Douglas-Peucker algorithm.
Expand Down