Hey Team,
Has anyone used the Google Maps API with VBA to get Travel Distance and Time? For some reason I am getting it to work with Travel Time but I can only get some of my Travel distances to report correctly. My VBA Function is giving me an #VALUE error.
For some reason my formula will not work for Travel Distance. When using the Test HTTP It works and I get Travel Time and Distance but in Excel only Travel Time works 100% of the time while Travel Distance only works 50% of the Time.
Google Maps API:
Code:
Has anyone used the Google Maps API with VBA to get Travel Distance and Time? For some reason I am getting it to work with Travel Time but I can only get some of my Travel distances to report correctly. My VBA Function is giving me an #VALUE error.
For some reason my formula will not work for Travel Distance. When using the Test HTTP It works and I get Travel Time and Distance but in Excel only Travel Time works 100% of the time while Travel Distance only works 50% of the Time.
Google Maps API:
Excel Function to Calculate Travel Time and Distance using Google Maps API with VBA - Syntax Byte
In this article, we will create an Excel function to calculate the distance between two addresses using the Google Maps directions API. This will allow you to get the travel time between the two locations. The format of the function will be as follows: =TRAVELTIME(origin, destination, api_key)...
syntaxbytetutorials.com
Code:
VBA Code:
Function TRAVELTIME(origin, destination, apikey)
Dim strUrl As String
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
Set httpReq = CreateObject("MSXML2.XMLHTTP")
With httpReq
.Open "GET", strUrl, False
.Send
End With
Dim Response As String
Response = httpReq.ResponseText
Dim parsed As Dictionary
Set parsed = JsonConverter.ParseJson(Response)
Dim seconds As Integer
For Each leg In parsed("routes")(1)("legs")
seconds = seconds + leg("duration")("value")
Next leg
TRAVELTIME = seconds
End Function
Function TRAVELDISTANCE(origin, destination, apikey)
Dim strUrl As String
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
Set httpReq = CreateObject("MSXML2.XMLHTTP")
With httpReq
.Open "GET", strUrl, False
.Send
End With
Dim Response As String
Response = httpReq.ResponseText
Dim parsed As Dictionary
Set parsed = JsonConverter.ParseJson(Response)
Dim meters As Integer
For Each leg In parsed("routes")(1)("legs")
meters = meters + leg("distance")("value")
Next leg
TRAVELDISTANCE = meters
End Function