Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88854

Calculating distance between adresses using Google API in Excel (VBA)

$
0
0

I'm working on my master's thesis and really need your help with some distance calculations.

I am really struggling with some code I found online in order to calculate the distance between several addresses (~10k pairs). I tried two different codes from two websites, and they both give me an error.

I already created my own Google API, and activated billing (using the URL test actually works for me) and tried some suggestions from other forums.

1. Approach Found on: https://analystcave.com/excel-calculate-distances-between-addresses/

Code

'Calculate Google Maps distance between two addresses
   Public Function GetDistance(start As String, dest As String)
       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=false&key=YOUR_KEY"
       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 ("")
       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)
       tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
       GetDistance = CDbl(tmpVal)
       Exit Function
   ErrorHandl:
       GetDistance = -1
   End Function

Every time I'm applying the formula, I get a "-1" i.e. error message.

2. Approach Found on: https://syntaxbytetutorials.com/excel-function-to-calculate-distance-using-google-maps-api-with-vba/

Here I also added VBA-JSON and activated references as suggested by the author.

Code

' Returns the number of seconds it would take to get from one place to another
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

    Dim leg As Dictionary


    For Each leg In parsed("routes")(1)("legs")
        meters = meters + leg("distance")("value")
    Next leg



    TRAVELDISTANCE = meters

End Function 

Here, the functions actually do not compile due to an error in the line
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin="& origin & "&destination="& destination & "&key="& apikey

It returns the "Expected: end of statement" error.

I am completely lost and would be so grateful if anyone of you could provide some help.

Best, Felix


Viewing all articles
Browse latest Browse all 88854


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>