Calculating bearing between two CLLocationCoordinate2Ds Calculating bearing between two CLLocationCoordinate2Ds ios ios

Calculating bearing between two CLLocationCoordinate2Ds


Here the code modified with the changes suggested by Oren Trutner and from myself:

#define degreesToRadians(x) (M_PI * x / 180.0)#define radiansToDegrees(x) (x * 180.0 / M_PI)- (float)getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc{    float fLat = degreesToRadians(fromLoc.latitude);    float fLng = degreesToRadians(fromLoc.longitude);    float tLat = degreesToRadians(toLoc.latitude);    float tLng = degreesToRadians(toLoc.longitude);    float degree = radiansToDegrees(atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng)));    if (degree >= 0) {        return degree;    } else {        return 360+degree;    }}


Your math is correct, with the following exceptions:

  1. Make sure to convert fLat, fLon, tLat, and tLon to radians before applying any sin() or cos() to them. Divide by 180.0 and multiply by PI.

  2. Enter the delta between tLng and fLng as tLng-fLng, and not the other way around. Note that this difference appears twice in the expression.

With those changes, I am getting 1.18660677830947 radians with double precision math and the values in the question.


Swift 3:

extension CLLocationCoordinate2D {    func bearing(to point: CLLocationCoordinate2D) -> Double {        func degreesToRadians(_ degrees: Double) -> Double { return degrees * Double.pi / 180.0 }        func radiansToDegrees(_ radians: Double) -> Double { return radians * 180.0 / Double.pi }        let lat1 = degreesToRadians(latitude)        let lon1 = degreesToRadians(longitude)        let lat2 = degreesToRadians(point.latitude);        let lon2 = degreesToRadians(point.longitude);        let dLon = lon2 - lon1;        let y = sin(dLon) * cos(lat2);        let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);        let radiansBearing = atan2(y, x);        return radiansToDegrees(radiansBearing)    }}