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
return
the distance in meters (assuming spherical earth)
Implementation
static double distanceToLine(
final Point p, final Point start, final Point end) {
if (start == end) {
return SphericalUtils.computeDistanceBetween(end, p);
}
final double s0lat = SphericalUtils.toRadians(p.x);
final double s0lng = SphericalUtils.toRadians(p.y);
final double s1lat = SphericalUtils.toRadians(start.x);
final double s1lng = SphericalUtils.toRadians(start.y);
final double s2lat = SphericalUtils.toRadians(end.x);
final double s2lng = SphericalUtils.toRadians(end.y);
double s2s1lat = s2lat - s1lat;
double s2s1lng = s2lng - s1lng;
final double 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);
}
Point latLng =
Point(start.x + u * (end.x - start.x), start.y + u * (end.y - start.y));
return SphericalUtils.computeDistanceBetween(p, latLng);
}