-1

google api无法在Excel VBA中查找源和目标之间的距离

我尝试更改 API,但它不是 API,而是代码。

Public Function GetDistance(start As String, dest As String)
    Dim firstVal As String, secondVal As String, lastVal As String
    firstVal = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
    secondVal = "&destinations="
    lastVal = "&mode=car&language=pl&sensor=false&key=MyKey"
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    Url = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+") & lastVal
    objHTTP.Open "GET", Url, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
    Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """value"".*?([0-9]+)": regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)
    tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
    GetDistance = CDbl(tmpVal)
    Exit Function
ErrorHandl:
    GetDistance = -1
End Function
4

1 回答 1

0

由于您要返回 a JSON,因此您可以更轻松地使用JSON解析器来获取结果。

我用

' VBA-JSON v2.3.0
' (c) Tim Hall - https://github.com/VBA-tools/VBA-JSON
'
' JSON Converter for VBA

以下代码将返回两个位置之间的行驶距离:

Option Explicit
Function getDistance(sStart As String, Dest As String)
    Const API As String = "key=myAPI"
    Const sURL1 As String = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial"
    Dim sURL() As String
    Dim sOrigin As String, sDest As String
    Dim xhrRequest As XMLHTTP60

Dim strJSON As String, JSON As Object

sOrigin = Replace("origins=" & sStart, " ", "+")
sDest = Replace("destinations=" & Dest, " ", "+")

'Many ways to create the URL to send
ReDim sURL(3)
    sURL(0) = sURL1
    sURL(1) = sOrigin
    sURL(2) = sDest
    sURL(3) = API

Set xhrRequest = New XMLHTTP60
With xhrRequest
    .Open "Get", Join(sURL, "&"), False
    .sEnd
    strJSON = .responseText
End With

Set JSON = parsejson(strJSON)


'"text" returns a string in local language
'"value" returns the distance in meters
getDistance = JSON("rows")(1)("elements")(1)("distance")("text")

End Function

还有其他选项,您可以阅读目前位于 Google Distance-Matrix Developers Guide的 API 文档

如果在监视窗口中展开 JSON 对象,您可以弄清楚它是如何构造的,以创建返回所需值的字符串。

于 2019-10-14T21:08:04.897 回答