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 'DOMDocument60
Set DOMdoc = CreateObject("MSXML2.DOMDocument") 'New DOMDocument60
Dim StatusNode As Object 'IXMLDOMNode
Dim originAddressNodes As Object 'IXMLDOMNodeList
Dim destinationAddressNodes As Object 'IXMLDOMNodeList
Dim rowNodes As Object 'IXMLDOMNodeList
Dim elementNodes As Object 'IXMLDOMNodeList
Dim element As Object 'IXMLDOMNode
Dim r As Long, c As Long
origins = Join(Array("postcode1", "postcode2"), "|") 'SPECIFY ACTUAL POSTCODES
destinations = Join(Array("postcode3", "postcode4"), "|") 'SPECIFY ACTUAL POSTCODES
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