Calculating bearing between two CLLocationCoordinate2Ds

前端 未结 4 1666
遇见更好的自我
遇见更好的自我 2020-11-27 13:07

Very \"simple\" problem: given two CLLocationCoordinate2Ds, how can I get the bearing (as radians) from the first to the second? I\'ve done a lot of research and studying on

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 14:06

    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;
        }
    }
    

提交回复
热议问题