Last active
May 14, 2019 17:11
-
-
Save mauroa/ebbdfa03e525f224ad02a8dd264e1409 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Public Function GetDistanceCoord(ByVal lat1 As Double, ByVal lon1 As Double, ByVal lat2 As Double, ByVal lon2 As Double, ByVal unit As String) As Double | |
Dim theta As Double: theta = lon1 - lon2 | |
Dim dist As Double: dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta)) | |
dist = WorksheetFunction.Acos(dist) | |
dist = rad2deg(dist) | |
dist = dist * 60 * 1.1515 | |
If unit = "K" Then | |
dist = dist * 1.609344 | |
ElseIf unit = "N" Then | |
dist = dist * 0.8684 | |
End If | |
GetDistanceCoord= dist | |
End Function | |
Function deg2rad(ByVal deg As Double) As Double | |
deg2rad = (deg * WorksheetFunction.Pi / 180#) | |
End Function | |
Function rad2deg(ByVal rad As Double) As Double | |
rad2deg = rad / WorksheetFunction.Pi * 180# | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment