gpt4 book ai didi

vba - 计算坐标之间的距离(以公里为单位)

转载 作者:行者123 更新时间:2023-12-03 02:25:43 25 4
gpt4 key购买 nike

我正在尝试使用半正矢公式计算两个地理坐标之间的距离(以公里为单位)。

代码:

Dim dbl_dLat As Double
Dim dbl_dLon As Double
Dim dbl_a As Double

dbl_P = WorksheetFunction.Pi / 180
dbl_dLat = dbl_P * (dbl_Latitude2 - dbl_Latitude1)
dbl_dLon = dbl_P * (dbl_Longitude2 - dbl_Longitude1)

dbl_a = Sin(dbl_dLat / 2) * Sin(dbl_dLat / 2) + Cos(dbl_Latitude1 * dbl_P) * Cos(dbl_Latitude2 * dbl_P) * Sin(dbl_dLon / 2) * Sin(dbl_dLon / 2)

dbl_Distance_KM = 6371 * 2 * WorksheetFunction.Atan2(Sqr(dbl_a), Sqr(1 - dbl_a))

我正在使用这些坐标进行测试:

dbl_Longitude1 = 55.629178
dbl_Longitude2 = 29.846686
dbl_Latitude1 = 37.659466
dbl_Latitude2 = 30.24441

代码返回20015.09,这显然是错误的。根据 Yandex map ,应该是 642 公里。

我哪里错了?经度和纬度格式是否错误?

最佳答案

据我所知,问题是 atan2() 的参数顺序因语言而异。以下对我有用*:

Option Explicit

Public Sub Distance()
Dim dbl_Longitude1 As Double, dbl_Longitude2 As Double, dbl_Latitude1 As Double, dbl_Latitude2 As Double

dbl_Longitude1 = 55.629178
dbl_Longitude2 = 29.846686
dbl_Latitude1 = 37.659466
dbl_Latitude2 = 30.24441

Dim dbl_dLat As Double
Dim dbl_dLon As Double
Dim dbl_a As Double
Dim dbl_P As Double

dbl_P = WorksheetFunction.Pi / 180
dbl_dLat = dbl_P * (dbl_Latitude2 - dbl_Latitude1) 'to radians
dbl_dLon = dbl_P * (dbl_Longitude2 - dbl_Longitude1) 'to radians

dbl_a = Sin(dbl_dLat / 2) * Sin(dbl_dLat / 2) + _
Cos(dbl_Latitude1 * dbl_P) * Cos(dbl_Latitude2 * dbl_P) * Sin(dbl_dLon / 2) * Sin(dbl_dLon / 2)

Dim c As Double
Dim dbl_Distance_KM As Double
c = 2 * WorksheetFunction.Atan2(Sqr(1 - dbl_a), Sqr(dbl_a)) ' *** swapped arguments to Atan2
dbl_Distance_KM = 6371 * c

Debug.Print dbl_Distance_KM
End Sub

*输出:2507.26205401321,尽管 gcmap.com答案是2512公里。这可能是一个精度问题——我认为它足够接近,可以算作有效。 (编辑也可能是 gcmap 使用本地地球半径而不是平均半径;我不确定。)

说明

我找到了this description大圆距离的半正矢公式,这就是您正在实现的。该页面上的 JavaScript 实现给出了 c 的计算结果:

var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

在 JavaScript 中,atan2()接受参数yx。但是,在 Excel VBA 中,WorksheetFunction.Atan2接受参数 xy。您的原始代码将 Sqr(dbl_a) 作为第一个参数传递,就像在 JavaScript 中一样。但是,Sqr(dbl_a) 需要是 Excel VBA 中的第二参数。

命名评论

基于@JohnColeman 的观点,有很多方法可以命名变量。在这种情况下,我建议使用单位前缀而不是类型前缀:例如,deg_Latitude1RadPerDeg = Pi/180rad_dLat = RadPerDeg * ( deg_Latitude2 - deg_Latitude1)。我个人认为这有助于避免 unit-conversion mishaps .

关于vba - 计算坐标之间的距离(以公里为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48008116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com