计算两个CLLocationCoordinate2D之间的方位

Jam*_*s J 38 objective-c core-location coordinates ios

非常"简单"的问题:给定两个CLLocationCoordinate2Ds,如何从第一个到第二个获得方位(以弧度为单位)?我已经做了很多研究和研究,特别是一般问题和Objective-C/Cocoa Touch/iOS.

这是我的实现:

- (float) getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
    float fLat = fromLoc.latitude;
    float fLng = fromLoc.longitude;
    float tLat = toLoc.latitude;
    float tLng = toLoc.longitude;

    return atan2(sin(fLng-tLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(fLng-tLng));         
}
Run Code Online (Sandbox Code Playgroud)

但是,这种方法并没有为我返回一致的结果.如果轴承接近正北或正南,看起来很好,但是,任何其他方向似乎都会返回不一致的数据,例如:

从50.405018,8.437500

至51.339802,12.403340

我的方法返回:5.918441弧度

应该是1.18660576弧度

(见http://www.movable-type.co.uk/scripts/latlong.htmlhttp://www.movable-type.co.uk/scripts/latlong-map.html?lat1=50.405018&long1=8.437500 &lat2 = 51.339802&long2 = 12.403340)

我已经双重和三重检查公式是正确的.我也发现了一些像上面的例子一样的值,有些是正确的,有些是错的.我玩过各种模数或返回值的界限,也没有运气.

有任何想法吗?我的代码有问题吗?也许我误解了数学函数是如何工作的?

meg*_*bri 52

这里的代码修改了Oren Trutner和我自己建议的变化:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这些不应该是双打而不是漂浮物吗? (4认同)

Ore*_*ner 31

你的数学是正确的,但有以下例外:

  1. 确保在对它们应用任何sin()cos()之前将fLat,fLon,tLattLon转换为弧度.除以180.0并乘以PI.

  2. 输入tLngfLng之间的增量为tLng-fLng,而不是相反.请注意,此差异在表达式中出现两次.

随着这些变化,我得到1.18660677830947弧度与双精度数学和问题中的值.


Sah*_*oor 10

斯威夫特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)
    }
}
Run Code Online (Sandbox Code Playgroud)