【问题标题】:How can I extract the distance from Google Directions API via Excel web query?如何通过 Excel 网络查询从 Google Directions API 中提取距离?
【发布时间】:2012-08-24 18:34:42
【问题描述】:

我在 Excel 中有一个很长的起点和目的地列表,使用 webquery 我可以填写城市和邮政编码来提供如下 webquery:

http://maps.googleapis.com/maps/api/directions/xml?origin=Scoresby&destination=Melborne&sensor=false

这会返回一个很长的 XML 文件,但我需要的只是距离。有没有办法只提取距离值?

或者我应该只运行一个宏脚本来逐个提取距离吗? (因为每次我询问服务器时格式都大致相同)

【问题讨论】:

    标签: excel api vba distance


    【解决方案1】:

    简短的回答是XPath - 如果您要使用任何类型的 XML,都值得学习

    在 Excel 的宏编辑器中,转到工具 > 引用并添加对“Microsoft XML,v6.0”的引用,现在插入 > 模块并添加以下代码:

    Sub getDistances()
    
    Dim xhrRequest As XMLHTTP60
    Dim domDoc As DOMDocument60
    Dim ixnlDistanceNodes As IXMLDOMNodeList
    Dim ixnNode As IXMLDOMNode
    Dim lOutputRow As Long
    
    ' Read the data from the website
    Set xhrRequest = New XMLHTTP60
    xhrRequest.Open "GET", "http://maps.googleapis.com/maps/api/directions/xml?origin=Scoresby&destination=Melborne&sensor=false", False
    xhrRequest.send
    
    ' Copy the results into a format we can manipulate with XPath
    Set domDoc = New DOMDocument60
    domDoc.loadXML xhrRequest.responseText
    
    ' The important bit: select every node called "value" which is the child of a node called "distance" which is
    ' in turn the child of a node called "step"
    Set ixnlDistanceNodes = domDoc.selectNodes("//step/distance/value")
    
    ' Basic stuff to output the distances
    lOutputRow = 1
    With Worksheets("Sheet1")
        .UsedRange.ClearContents
        For Each ixnNode In ixnlDistanceNodes
            .Cells(lOutputRow, 1).Value = ixnNode.Text
            lOutputRow = lOutputRow + 1
        Next ixnNode
    End With
    
    Set ixnNode = Nothing
    Set ixnlDistanceNodes = Nothing
    Set domDoc = Nothing
    Set xhrRequest = Nothing
    
    End Sub
    

    要将其扩展为涵盖多次旅行,您只需遍历所需的起点和目的地,将每一对作为参数传递给此过程,然后以您需要的任何格式输出结果

    【讨论】:

    • 非常好的例子。提醒一下(我不想成为一个有趣的人):使用 Google Maps API 确实需要您显示 Google Map(“Directions API 只能与在谷歌地图”,code.google.com/intl/en/apis/maps/documentation/directions/…) 虽然在这个特定的例子中我看不出它是如何以一种有用的方式完成的。只是说。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多