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

Polygon-Line euclidean distance fix #226

Merged
merged 5 commits into from
May 16, 2018
Merged
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
Prev Previous commit
Next Next commit
Correctly implement Line-Polygon distance
  • Loading branch information
urschrei committed May 16, 2018
commit 4c5a2889951cf64e66bac28de700cb5397173d76
38 changes: 34 additions & 4 deletions geo/src/algorithm/euclidean_distance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,12 +324,29 @@ where
// Line to Polygon distance
impl<T> EuclideanDistance<T, Polygon<T>> for Line<T>
where
T: Float + FloatConst + Signed + SpadeFloat,
T: Float + Signed + SpadeFloat,
{
fn euclidean_distance(&self, other: &Polygon<T>) -> T {
self.start
.euclidean_distance(other)
.min(self.end.euclidean_distance(other))
if other.contains(self) || self.intersects(other) {
return T::zero();
}
// point-line distance between each exterior polygon point and the line
let exterior_min = other.exterior.points().fold(T::max_value(), |acc, point| {
acc.min(self.euclidean_distance(point))
});
// point-line distance between each interior ring point and the line
// if there are no rings this just evaluates to max_float
let interior_min = other
.interiors
.iter()
.map(|ring| {
ring.points().fold(T::max_value(), |acc, point| {
acc.min(self.euclidean_distance(point))
})
})
.fold(T::max_value(), |acc, ring_min| acc.min(ring_min));
// return smaller of the two values
exterior_min.min(interior_min)
}
}

Expand Down Expand Up @@ -828,4 +845,17 @@ mod test {
let in_ring_ls: LineString<f64> = in_ring.into();
assert_eq!(ring_ls.euclidean_distance(&in_ring_ls), 5.992772737231033);
}
#[test]
// Line-Polygon test: closest point on Polygon is NOT nearest to a Line end-point
fn flibble() {
let line = Line::new(Point::new(0.0, 0.0), Point::new(0.0, 3.0));
let v = vec![
(5.0, 1.0),
(5.0, 2.0),
(0.25, 1.5),
(5.0, 1.0)
];
let poly = Polygon::new(v.into(), vec![]);
assert_eq!(line.euclidean_distance(&poly), 0.25);
}
}