计算两个 GPS 位置之间的距离
如果我有两个 GPS 位置,例如 51.507222、-0.1275 和 48.856667、2.350833,我可以使用什么公式来计算两者之间的距离?我听说过很多关于半正矢公式的信息,但找不到任何有关它的信息,或者如何将其应用到 C 中。
我编写了以下代码,但是,它非常不准确。有人知道为什么吗?我想不通。问题出在函数本身,但我不知道它是什么。
float calcDistance(float A, float B, float C, float D)
{
float dLat;
float dLon;
dLat = (C - A);
dLon = (D - B);
dLat /= 57.29577951;
dLon /= 57.29577951;
float v_a;
float v_c;
float distance;
v_a = sin(dLat/2) * sin(dLat/2) + cos(A) * cos(C) * sin(dLon/2) * sin(dLon/2);
v_c = 2 * atan2(sqrt(v_a),sqrt(1-v_a));
distance = r * v_c;
return distance;
}
If I have two GPS locations, say 51.507222, -0.1275 and 48.856667, 2.350833, what formula could I use to calculate the distance between the two? I've heard a lot about a haversine formula, but can't find any information about it, or how to apply it to C.
I've written the following code, however, it's very innacurate. Anybody know why? I can't figure it out. The problem comes from the function itself, but I don't know what it is.
float calcDistance(float A, float B, float C, float D)
{
float dLat;
float dLon;
dLat = (C - A);
dLon = (D - B);
dLat /= 57.29577951;
dLon /= 57.29577951;
float v_a;
float v_c;
float distance;
v_a = sin(dLat/2) * sin(dLat/2) + cos(A) * cos(C) * sin(dLon/2) * sin(dLon/2);
v_c = 2 * atan2(sqrt(v_a),sqrt(1-v_a));
distance = r * v_c;
return distance;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的代码是绝对正确的。
我会将参数
A
、B
、C
和D
重命名为lat1
、<代码>lon1、lat2
和lon2
。它返回以公里为单位的距离。您需要将
r
定义为 6371,大致为 地球半径。Your code is absolutely correct.
I would rename parameters
A
,B
,C
andD
tolat1
,lon1
,lat2
andlon2
.It returns the distance in kilometers. You need to define
r
as 6371, roughly the radius of the earth.此页面有一段Javascript,我相信你可以在 C 中很容易适应:
This page has a block of Javascript which I'm sure you could adapt easily enough in C:
这是计算不准确的原因:
-> A 和 C(lat1 和 lat2)也必须从度数转换为弧度
This is the reason of the inaccurate calculation:
-> A and C (lat1 and lat2) must also be converted from degree to radians