distance method

  1. @override
double distance(
  1. GeoLatLng p1,
  2. GeoLatLng p2
)
override

Calculates distance with Vincenty algorithm.

Accuracy is about 0.5mm More on Wikipedia

Implementation

@override
double distance(final GeoLatLng p1, final GeoLatLng p2) {
  double a = EQUATOR_RADIUS,
      b = POLAR_RADIUS,
      f = FLATTENING; // WGS-84 ellipsoid params

  double L = p2.longitudeInRad - p1.longitudeInRad;
  double U1 = math.atan((1 - f) * math.tan(p1.latitudeInRad));
  double U2 = math.atan((1 - f) * math.tan(p2.latitudeInRad));
  double sinU1 = math.sin(U1), cosU1 = math.cos(U1);
  double sinU2 = math.sin(U2), cosU2 = math.cos(U2);

  double sinLambda,
      cosLambda,
      sinSigma,
      cosSigma,
      sigma,
      sinAlpha,
      cosSqAlpha,
      cos2SigmaM;
  double lambda = L, lambdaP;
  int maxIterations = 200;

  do {
    sinLambda = math.sin(lambda);
    cosLambda = math.cos(lambda);
    sinSigma = math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) +
        (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) *
            (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));

    if (sinSigma == 0) {
      return 0.0; // co-incident points
    }

    cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
    sigma = math.atan2(sinSigma, cosSigma);
    sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
    cosSqAlpha = 1 - sinAlpha * sinAlpha;
    cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;

    if (cos2SigmaM.isNaN) {
      cos2SigmaM = 0.0; // equatorial line: cosSqAlpha=0 (ยง6)
    }

    double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
    lambdaP = lambda;
    lambda = L +
        (1 - C) *
            f *
            sinAlpha *
            (sigma +
                C *
                    sinSigma *
                    (cos2SigmaM +
                        C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
  } while ((lambda - lambdaP).abs() > 1e-12 && --maxIterations > 0);

  if (maxIterations == 0) {
    throw new StateError("Distance calculation faild to converge!");
  }

  double uSq = cosSqAlpha * (a * a - b * b) / (b * b);
  double A =
      1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
  double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
  double deltaSigma = B *
      sinSigma *
      (cos2SigmaM +
          B /
              4 *
              (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
                  B /
                      6 *
                      cos2SigmaM *
                      (-3 + 4 * sinSigma * sinSigma) *
                      (-3 + 4 * cos2SigmaM * cos2SigmaM)));

  double dist = b * A * (sigma - deltaSigma);

  return dist;
}