distanceToLine static method
Computes the distance on the sphere between the point p and the line segment start to end.
p the point to be measured
start the beginning of the line segment
end the end of the line segment
Returns the distance in meters (assuming spherical earth)
Implementation
static double distanceToLine(final Point<double> p, final Point<double> start,
final Point<double> end) {
if (start == end) {
return SphericalUtils.computeDistanceBetween(end, p);
}
final s0lat = SphericalUtils.toRadians(p.x);
final s0lng = SphericalUtils.toRadians(p.y);
final s1lat = SphericalUtils.toRadians(start.x);
final s1lng = SphericalUtils.toRadians(start.y);
final s2lat = SphericalUtils.toRadians(end.x);
final s2lng = SphericalUtils.toRadians(end.y);
final s2s1lat = s2lat - s1lat;
final s2s1lng = s2lng - s1lng;
final u = ((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng) /
(s2s1lat * s2s1lat + s2s1lng * s2s1lng);
if (u <= 0) {
return SphericalUtils.computeDistanceBetween(p, start);
} else if (u >= 1) {
return SphericalUtils.computeDistanceBetween(p, end);
}
final latLng = Point(
start.x + u * (end.x - start.x),
start.y + u * (end.y - start.y),
);
return SphericalUtils.computeDistanceBetween(p, latLng);
}