In Excel, Im using VB to calculate the distance in miles between two points. When I do so, I can't seem to get the distance of multiple routes between the two points. When I call the function GetDistance("Alabama","Georgia"), it gives the distance for one route from Alabama and Georgia and clearly on Google Maps their are multiple routes from point A to B with varied distances. When I used MsgBox objHTTP.responseText to display all the routes distance, it shows only one route distance as shown here in screenshot. How can I display all the routes distance in miles?
'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