ios - 计算两个 CLLocationCoordinate2D 之间的方位

非常“简单”的问题:给定两个 CLLocationCoordinate2D,我怎样才能得到从第一个到第二个的方位角(以弧度表示)?我在这方面做了很多研究和研究,包括一般问题和具体的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));         
}

但是,此方法不会为我返回一致的结果。如果方位接近正北或正南,似乎没问题,但是,任何其他方向似乎返回不一致的数据,例如:

从 50.405018、8.437500

至 51.339802、12.403340

我的方法返回:5.918441 弧度

应该是 1.18660576 弧度

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

我已经两次和三次检查公式是否正确。我还抽查了上面示例中的一堆值,有些正确,有些错误。我玩过各种模数或返回值的边界,也没有运气。

有什么想法吗?我的代码有问题吗?也许我误解了数学函数的工作原理?

最佳答案

这里是使用 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;
    }
}

https://stackoverflow.com/questions/3809337/

相关文章:

objective-c - Objective C 中的多个委托(delegate)

c - 在 Objective-C 类中混合 C 函数

iphone - 如何以编程方式区分 iphone 4 和 iphone 4S?

objective-c - 在 mac 包中嵌入字体

iphone - 在 Objective-C 中随机化 NSArray 的规范方法

objective-c - 如何从 C 方法调用 Objective-C 方法?

iphone - 从 float 或 double 实例化 NSDecimalNumber 的正确方

objective-c - 如何在没有 Interface Builder 的情况下创建 Cocoa

ios - 使用钩子(Hook)在 Instagram 上发布视频

objective-c - 在 ARC 之后,我应该为调度队列使用什么属性?