distanceToLine static method

num distanceToLine(
  1. Point<num> p,
  2. Point<num> start,
  3. Point<num> end
)

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 num distanceToLine(final Point p, final Point start, final Point end) {
  if (start == end) {
    return SphericalUtils.computeDistanceBetween(end, p);
  }

  final num s0lat = SphericalUtils.toRadians(p.x);
  final num s0lng = SphericalUtils.toRadians(p.y);
  final num s1lat = SphericalUtils.toRadians(start.x);
  final num s1lng = SphericalUtils.toRadians(start.y);
  final num s2lat = SphericalUtils.toRadians(end.x);
  final num s2lng = SphericalUtils.toRadians(end.y);

  num s2s1lat = s2lat - s1lat;
  num s2s1lng = s2lng - s1lng;
  final num 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);
}