Extract right value from a HTTP response (Google API Distance)

most

Board Regular
Joined
Feb 22, 2011
Messages
99
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
  2. Mobile
I found a great implementation of Google distance API at analystcave.com, it works great!
Now I would like to expand it by adding status and destination to the output.
But I don't quite understand how the code does the lookup in the response and there are no help to get at analystcave.

My try to extract destination address, but the output is not what I expect, I only get "20" (as in Sveavägen 20).
VBA Code:
Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """destination_addresses"".*?([0-9]+)": regex.Global = False
 Set matches = regex.Execute(objHTTP.responseText)
 tmpVal2 = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
 Debug.Print " Dest: " & tmpVal2

My try to extract status, results in a run-time error.
VBA Code:
    Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """status"".*?([0-9]+)": regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)
    tmpVal3 = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
    Debug.Print " Stat: " & tmpVal3

The response...
Screenshot_1.jpg


The whole code, BUT it won't work unless you have a API key.
VBA Code:
Sub GDistance()
'Get and update distance
Dim myFrom As String, myTo As String
 myFrom = Range("B5").Value
 myTo = Range("G1").Value
   If myTo = "" Or myFrom = "" Then
     MsgBox "Startplats eller destination saknas!", vbOKOnly + vbExclamation
     Exit Sub
   End If
 MyDistance = Round((GetDistance(myFrom, myTo) / 1000), 1)
 Range("G2").Value = MyDistance
End Sub
'Calculate Google Maps distance between two addresses
'https://analystcave.com/excel-calculate-distances-between-addresses/
Public Function GetDistance(start As String, dest As String)
   Dim firstVal As String, secondVal As String, lastVal As String
   firstVal = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="
   secondVal = "&destinations="
   lastVal = "&mode=driving&sensor=false&key=" & Range("gmapkey").Value
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+") & lastVal
Debug.Print URL
    objHTTP.Open "GET", URL, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
    Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """value"".*?([0-9]+)": regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)
    tmpVal1 = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
    GetDistance = CDbl(tmpVal1)
    
   'My trial code
    Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """destination_addresses"".*?([0-9]+)": regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)
    tmpVal2 = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
    Debug.Print " Dest: " & tmpVal2
   'My trial code
    
    Exit Function
ErrorHandl:
    GetDistance = -1
End Function
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
I would never use Regex to parse something as complicated as this data.

Why not use a JSON converter, for example VBA-JSON, to parse the response? There are examples on this forum showing how to use it.

Alternatively, here is code which requests and parses the XML response from the Distance Matrix API:

 
Upvote 0
Thanks, will look into it.
 
Upvote 0

Forum statistics

Threads
1,213,549
Messages
6,114,264
Members
448,558
Latest member
aivin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top