Google Maps API两点之间的距离会返回不同的路径

时间:2016-01-17 19:08:55

标签: excel google-maps excel-vba google-maps-api-3 vbscript vba

在Excel中,我使用VB来计算两点之间的英里距离。当我这样做时,我似乎无法获得两点之间多条路线的距离。当我调用函数GetDistance(" Alabama"," Georgia")时,它给出了从阿拉巴马州和佐治亚州开始的一条路线的距离,并且在谷歌地图上显示它们是从A点到A点的多条路线。 B距离不等。当我使用MsgBox objHTTP.responseText显示所有路由距离时,它只显示一个路由距离,如屏幕截图所示。如何以英里显示所有路线距离?

objHTTP.responceText screenshot

'Calculate Google Maps distance between two addresses
Public Function GetDistance(start As String, dest As String, unit As Integer)
    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=true&units=Imperical"


    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 ("")
    MsgBox objHTTP.responseText

    If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
    Set regex = CreateObject("VBScript.RegExp")
    regex.Pattern = """text"".*?([0-9]+)"
    regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)


    tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))

    GetDistance = CDbl(tmpVal) / 1.609344
    Exit Function
ErrorHandl:
    GetDistance = -1
End Function

Sub PrintValue(str As String)

Range("B1") = str
End Sub

1 个答案:

答案 0 :(得分:2)

DistanceMatrix仅提供一个距离。如果您需要相同两点之间的多条路线的距离,请使用带有参数alternatives=true的DistanceService:

来自the documentation

  

替代方案 - 如果设置为true,则指定路线服务可在响应中提供多个路径替代方案。请注意,提供路由选择可能会增加服务器的响应时间。