azimuth method

double azimuth(
  1. Coordinates target
)

Calculates the azimuth (bearing) from this coordinate to target.

The azimuth is computed according to the ellipsoid model of WGS84 and returned in degrees. If the points are effectively identical or invalid, the method returns 0.0.

Parameters

  • target: The destination Coordinates to which the azimuth is calculated.

Returns

  • Azimuth in degrees from this coordinate to target.

Implementation

double azimuth(Coordinates target) {
  double result = 0.0;

  double lat1 = latitude;
  double lon1 = longitude;
  double lat2 = target.latitude;
  double lon2 = target.longitude;

  final int intLat1 = (0.5 + lat1 * 360000.0).toInt();
  final int intLon1 = (0.5 + lon1 * 360000.0).toInt();
  final int intLat2 = (0.5 + lat2 * 360000.0).toInt();
  final int intLon2 = (0.5 + lon2 * 360000.0).toInt();

  double degToRad(double deg) => deg * pi / 180.0;
  double radToDeg(double rad) => rad * 180.0 / pi;

  if (intLat1 != intLat2 || intLon1 != intLon2) {
    if (intLon1 != intLon2) {
      lat1 = degToRad(lat1);
      lon1 = degToRad(lon1);
      lat2 = degToRad(lat2);
      lon2 = degToRad(lon2);

      final double diff = lon2 - lon1;
      final double cosLat2 = cos(lat2);
      final double c = acos(
        sin(lat2) * sin(lat1) + cosLat2 * cos(lat1) * cos(diff),
      );
      result = radToDeg(asin(cosLat2 * sin(diff) / sin(c)));

      if (intLat2 > intLat1 && intLon2 > intLon1) {
      } else if ((intLat2 < intLat1 && intLon2 < intLon1) ||
          (intLat2 < intLat1 && intLon2 > intLon1)) {
        result = 180.0 - result;
      } else if (intLat2 > intLat1 && intLon2 < intLon1) {
        result += 360.0;
      }
    } else if (intLat1 > intLat2) {
      result = 180.0;
    }
  }
  return result;
}