计算两个CLLocationCoordinate2D之间的方位 [英] Calculating bearing between two CLLocationCoordinate2Ds

查看:363
本文介绍了计算两个CLLocationCoordinate2D之间的方位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 this, both the general problem and Objective-C/Cocoa Touch/iOS specifically.

这是我的实现:

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

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

However, this method isn't returning consistant results for me. If the bearing is close to due north or due south, it seems to be fine, however, any other direction seems to return inconsistant data, for example:

从50.405018开始, 8.437500

From 50.405018, 8.437500

至51.339802,12.403340

To 51.339802, 12.403340

我的方法返回:5.918441弧度

My method returns: 5.918441 radians

应为1.18660576弧度

Should be 1.18660576 radians

(参见 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

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

I've double and triple checked the formula is correct. I've also spot checked a bunch of values like the example above, some correct, some wrong. I've played around with various modulos or bounding of the return value, also no luck.

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

Any ideas? Is there an issue with my code? Maybe I've misunderstood something about how math functions work?

推荐答案

你的数学是正确的,除了以下例外:

Your math is correct, with the following exceptions:


  1. 确保转换 fLat fLon tLat sin() cos()应用于它们之前,em>和 tLon 为弧度。除以180.0并乘以PI。

  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.

输入 tLng fLng 之间的差值作为 tLng-fLng ,而不是相反。请注意,此差异在表达式中出现两次。

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.

通过这些更改,我获得了1.18660677830947弧度,具有双精度数学以及问题中的值。

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

这篇关于计算两个CLLocationCoordinate2D之间的方位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆