distanceToLine static method

num distanceToLine(
  1. LatLng p,
  2. LatLng start,
  3. LatLng end
)

Computes the distance on the sphere between the point p and the line segment start to end.

@param p the point to be measured @param start the beginning of the line segment @param end the end of the line segment @return the distance in meters (assuming spherical earth)

Implementation

static num distanceToLine(
    final LatLng p, final LatLng start, final LatLng end) {
  if (start == end) {
    return SphericalUtil.computeDistanceBetween(end, p);
  }

  final s0lat = MathUtil.toRadians(p.latitude);
  final s0lng = MathUtil.toRadians(p.longitude);
  final s1lat = MathUtil.toRadians(start.latitude);
  final s1lng = MathUtil.toRadians(start.longitude);
  final s2lat = MathUtil.toRadians(end.latitude);
  final s2lng = MathUtil.toRadians(end.longitude);

  final s2s1lat = s2lat - s1lat;
  final s2s1lng = s2lng - s1lng;
  final u = ((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng) /
      (s2s1lat * s2s1lat + s2s1lng * s2s1lng);
  if (u <= 0) {
    return SphericalUtil.computeDistanceBetween(p, start);
  }
  if (u >= 1) {
    return SphericalUtil.computeDistanceBetween(p, end);
  }
  final su = LatLng(start.latitude + u * (end.latitude - start.latitude),
      start.longitude + u * (end.longitude - start.longitude));
  return SphericalUtil.computeDistanceBetween(p, su);
}