查找不同坐标之间的距离

时间:2020-04-23 14:30:11

标签: excel vba excel-formula geocoding

我有1000个位置的位置数据(经度和纬度),并且需要一次计算两个组合中每个位置之间的距离。

示例:

让我们说我有四个位置数据(纬度和经度数据),想计算它们之间的距离

    Location      Latitude    Longitude

 1. New York(L1)  40.7128° N  74.0060° W
 2. Paris(L2)     48.8566° N   2.3522° E
 3. London(L3)    51.5074° N   0.1278° W
 4. Moscow(L4)    55.7558° N  37.6173° E

需要计算可能的组合之间的距离,即L1&L2L1&L3L1&L4L2&L3L2&L4L3&L4之间的距离< / p>

我用来计算距离的Excel公式是

=ACOS(COS(RADIANS(90-Lat1)) *COS(RADIANS(90-Lat2)) +SIN(RADIANS(90-Lat1)) *SIN(RADIANS(90-Lat2)) *COS(RADIANS(Long1-Long2))) *6371

如何计算大型数据集(例如100或1000个位置)?

2 个答案:

答案 0 :(得分:3)

或者,您可以创建一个VBA函数,然后遍历表。

将此代码添加到VBA编辑器中的模块中:

Public Function DistBetweenCoord(Lat1 As Double, Long1 As Double, Lat2 As Double, Long2 As Double)
    'Cell Formula
    'ACOS(COS(RADIANS(90-Lat1)) *COS(RADIANS(90-Lat2)) +SIN(RADIANS(90-Lat1)) *SIN(RADIANS(90-Lat2)) *COS(RADIANS(Long1-Long2))) *6371

    With WorksheetFunction
        A = Cos(.Radians(90 - Lat1))
        B = Cos(.Radians(90 - Lat2))
        C = Sin(.Radians(90 - Lat1))
        D = Sin(.Radians(90 - Lat2))
        E = Cos(.Radians(Long1 - Long2))

        DistBetweenCoord = .Acos(A * B + C * D * E) * 6371
    End With
End Function

现在您可以通过代码或在单元格中访问它。这是单元内示例:

=DistBetweenCoord(C1,D1,C2,D2)

这里是如何遍历另一个Sub中所有可能的组合的方法。输出在即时窗口中。

Sub CalcAllDistances()
    With Worksheets("Sheet1")
        For i = 1 To 4
            For j = i To 4
                If i <> j Then
                    Debug.Print .Cells(i, 2) & " to " & .Cells(j, 2) & ": " & DistBetweenCoord(.Cells(i, 3), .Cells(i, 4), .Cells(j, 3), .Cells(j, 4))
                End If
            Next j
        Next i
    End With
End Sub

enter image description here


编辑-要将输出更改为Sheet2,请尝试以下操作:

Sub CalcAllDistances()
    Dim wks_Output As Worksheet
    Set wks_Output = Worksheets("Sheet2")

    Dim OutputRow As Long: OutputRow = 1

    With Worksheets("Sheet1")
        For i = 1 To 4
            For j = i To 4
                If i <> j Then
                    wks_Output.Cells(OutputRow, 1).Value = .Cells(i, 2) & " to " & .Cells(j, 2)
                    wks_Output.Cells(OutputRow, 2).Value = DistBetweenCoord(.Cells(i, 3), .Cells(i, 4), .Cells(j, 3), .Cells(j, 4))
                    OutputRow = OutputRow + 1
                End If
            Next j
        Next i
    End With
End Sub

enter image description here

答案 1 :(得分:2)

我会使用一个矩阵。 为地理编码创建一张工作表(例如“ GeocodeList”或类似内容),例如问题中的城市|拉特|洛恩。然后为矩阵创建一张工作表(例如“ Distances”),其中列和行标签为城市名称。然后,您可以使用V.LOOKUP来参数excel公式,这些V.LOOKUP可以从GeocodeList中查找确切的代码。

公式如下所示(X是行号,Y是列字母。):

=ACOS(COS(RADIANS(90-VLOOKUP($A(X); GEOCODETABLE, LATCOLINDEX, 0)))
*COS(RADIANS(90-VLOOKUP((Y)$1; GEOCODETABLE; LATCOLINDEX, 0)))
+SIN(RADIANS(90-VLOOKUP($A(X); GEOCODETABLE, LATCOLINDEX, 0)))
*SIN(RADIANS(90-VLOOKUP((Y)$1; GEOCODETABLE; LATCOLINDEX, 0)))
*COS(RADIANS(VLOOKUP($A(X); GEOCODETABLE, LATCOLINDEX, 0)-VLOOKUP((Y)$1; GEOCODETABLE; LONCOLINDEX, 0))))
*6371

因此,基本上,VLOOKUP会自动获取您的参数,并且您可以扩展整个矩阵的公式。