Public Sub Google_Distance_Matrix_API()
Const APIkey = "Your_Google_API_key"
Dim origins As String
Dim destinations As String
Dim URL As String
Dim DOMdoc As Object
Set DOMdoc = CreateObject("MSXML2.DOMDocument")
Dim StatusNode As Object
Dim originAddressNodes As Object
Dim destinationAddressNodes As Object
Dim rowNodes As Object
Dim elementNodes As Object
Dim element As Object
Dim r As Long, c As Long
origins = Join(Array("postcode1", "postcode2"), "|")
destinations = Join(Array("postcode3", "postcode4"), "|")
URL = "https://maps.googleapis.com/maps/api/distancematrix/xml?" & _
"origins=" & Application.WorksheetFunction.EncodeURL(origins) & _
"&destinations=" & Application.WorksheetFunction.EncodeURL(destinations) & _
"&mode=driving&key=" & APIkey
With DOMdoc
.async = False
.Load URL
Set StatusNode = .SelectSingleNode("/DistanceMatrixResponse/status")
Set originAddressNodes = .selectNodes("/DistanceMatrixResponse/origin_address")
Set destinationAddressNodes = .selectNodes("/DistanceMatrixResponse/destination_address")
Set rowNodes = .selectNodes("/DistanceMatrixResponse/row")
End With
If StatusNode.Text = "OK" Then
For r = 0 To rowNodes.Length - 1
Set elementNodes = rowNodes(r).selectNodes("element")
For c = 0 To elementNodes.Length - 1
Set element = elementNodes(c)
If element.SelectSingleNode("status").nodeTypedValue = "OK" Then
If originAddressNodes(r).Text <> destinationAddressNodes(c).Text Then
Debug.Print originAddressNodes(r).Text & " to " & destinationAddressNodes(c).Text
Debug.Print element.SelectSingleNode("distance/text").Text & ", " & _
element.SelectSingleNode("duration/text").Text
End If
End If
Next
Next
Else
Debug.Print StatusNode.Text
End If
End Sub