Está en la página 1de 14

The Analyst Cave | Excel, VBA, programming and more






Home » Excel VBA Calculate distance between two addresses or

48 out of 5) JULY 24.googleapis. Of course open Google Maps and type each location one by one… and then choose the shortest connection. average: 4. 50 administration offices across my city I wanted to find the one that is closest to my workplace. The API is configured using GET HTTP Params. By why bother when we have Google Maps Distance Matrix API!!! This post includes information on how to calculate the distance in Excel:  Between any two ADDRESSES  Between any two COORDINATES To get the COORDINATES of any ADDRESS read this post Using the Google Maps Distance Matrix API Google has a lot of useful API out there and I encourage you to go sometime to the Google API Explorer and have a look at what other information you can easily utilize from Excel or your other|Seatt . Google facilitates Google Maps Distance Matrix API for limited usage.EXCEL VBA CALCULATE DISTANCE BETWEEN TWO ADDRESSES OR COORDINATES (25 votes. Say we want to get the distance between San Francisco and Victoria BC. Let’s however focus on getting the distance between two addresses. 2014 ANALYSTCAVE 131 COMMENTS FacebookGoogle+TwitterTumblrBlogg er PostEmail Ever wanted to calculate the distance between two addresses in Excel? I recently had the following issue: from a list of over approx. Copy this link into your browser: 1 https://maps. A simple example below. We want to get there by bicycle.

From: To: Mode: Google Maps Distance Matrix URL: Calculate distance between two addresses using Google Maps in Excel So I knocked up quickly this VBA Function in Excel which uses Google API distance matrix function to calculate the Google Maps distance. USA Google Distance Matrix Builder Want to quickly test the Google API? Below a simple form for building a quick Distance URL. select the transportation mode and hit Build URL!. BC.googleapis. See the VBA code here: Get Google Maps distance in meters 1 'Calculate Google Maps distance between two addresses Public Function GetDistance(start As String. dest As String) 2 Dim firstVal As String.ServerXMLHTTP") . secondVal As String. Simply type in the From an To addresses. Canada and San" 4 secondVal = "&destinations=" 5 lastVal = "&mode=car&language=pl&sensor=false" 6 Set objHTTP = CreateObject("MSXML2. Go here for more options for configuring the Google Maps Distance Matrix API. CA. Google Distance between Vancouver. lastVal As String 3 firstVal = "http://maps.

"+" 8 objHTTP. "Mozilla/4. """duration"" : {") = 0 Then GoTo ErrorHandl Set regex = CreateObject("VBScript.Open "GET".0 (compatible. Calculate distance between coordinates using a VBA function Taking into account the elliptic nature of Mother Earth you can easily calculate the distance between coordinates without using Google API .com/maps/api/distancematrix/json?origins=" 5 secondVal = "&destinations=" 6 lastVal = "&mode=car&language=en&sensor=false" Set objHTTP = CreateObject("MSXML2.".responseText.0 (compatible.Pattern = """value"". """distance"" : {") = 0 Then GoTo ErrorHandl Set regex = CreateObject("VBScript.Execute(objHTTP.|\n)* 12 Set matches = regex.0. URL. URL. " ". "+") & secondVal & Replace(dest. " ".Execute(objHTTP.". False 10 objHTTP.SubMatches(0). Application. "+" 9 objHTTP. " ".Pattern = "duration(?:.0.7 8 URL = firstVal & Replace(start.responseText) 14 tmpVal = Replace(matches(0). "Mozilla/4. MSIE 6.RegExp"): regex. lastVal As String 4 firstVal = "http://maps.googleapis. False 9 objHTTP.setRequestHeader "User-Agent". Application.send ("") 12 If InStr(objHTTP.setRequestHeader "User-Agent". dest As String) 3 Dim firstVal As String. Win 11 objHTTP. "+") & secondVal & Replace(dest.responseText) 13 tmpVal = Replace(matches(0).SubMatches(0).responseText. ". secondVal As String.send ("") 11 If InStr(objHTTP.*?([0-9 13 Set matches = regex.International(xlLi 14 GetDuration = CDbl(tmpVal) 15 Exit Function 16 ErrorHandl: GetDuration = -1 17 End Function 18 19 Calculate distance between two coordinates You can calculate the distance between two coordinates (2 pairs of latitudes and longitudes) using either Google’s API or a simple VBA Function.RegExp"): regex. ". Win 10 objHTTP. " ".International(xlLi 15 GetDistance = CDbl(tmpVal) 16 Exit Function 17 ErrorHandl: GetDistance = -1 18 End Function 19 20 Get Google Maps duration (in seconds) 1 2 Public Function GetDuration(start As String.ServerXMLHTTP") 7 URL = firstVal & Replace(start.Open "GET". MSIE 6. .

"41.609344 ElseIf unit = "N" Then 1 dist = dist * 0.Pi / 180#) 1 End Function 6 1 Function rad2deg(ByVal rad As Double) As Double 7 rad2deg = rad / WorksheetFunction.38992".1515 1 If unit = "K" Then 2 dist = dist * 1.-81.43206. ByVal lat2 A 9 Dim theta As Double: theta = lon1 . ByVal lon1 As Double.49992 Final call example: 1 Debug.-81.Sin(deg2rad(lat2)) + Math 1 dist = WorksheetFunction. 1 2 3 4 5 6 7 8 Public Function GetDistanceCoord(ByVal lat1 As Double.lon2 Dim dist As Double: dist = Math.-81.8684 3 End If 1 GetDistanceCoord= dist 4 End Function 1 5 Function deg2rad(ByVal deg As Double) As Double deg2rad = (deg * WorksheetFunction.Print GetDistance("41.Warning – no the world is not flat as opposed to what the Flat Earch Society is stating The function returns the distance and using the unit variable you can state if you want the function to return the distance in Kilometres ("K").43216.49992") .43216.Sin(deg2rad(lat1)) * Math. Miles ("M") or even nautical miles ("N").Pi * 180# 1 End Function 8 1 9 2 0 2 1 Calculate distance between coordinates using Google Maps in Excel To get Google Maps distance between two coordinates simply use the same GetDistance function as above and replace the start and dest parameters with the coordinates in this format: 1 41.Acos(dist) 0 dist = rad2deg(dist) 11 dist = dist * 60 * 1.

"41. Follow the steps: Add new VBA Module Go to the DEVELOPER ribbon and add select Visual Basic a and new Module to your VBA Project Insert the VBA code Insert the code from sections above (notice that the function is “Public” – therefore will be visible in your workbook as a so called UDF (User Defined Function) Input the function in Excel Go to the worksheet and input the function as shown below: 1 =GetDistance("Chicago".38992".-81.43216.49992") How to set it up in Excel? Important: Please remember that you need a direct Internet connection! Not via proxy etc. "New York") .43206.Print GetDuration("41.-81.Same goes for the duration function: 1 Debug.

with any coordinates/addresses in between our starting point and our destination. i As Long . For this I created 2 simple procedures MultiGetDistance and MultiGetDuration: Get distance between any number of locations By using our GetDistance function we can get the distance between any number of locations using the Visual Basic procedure below: 1 Public Function MultiGetDistance(ParamArray args() As Variant) As Double MultiGetDistance = 0 2 Dim startLoc As String.g. endLoc As String.Make sure to replace . with your default formula list separator (e. comma in the US)! Calculate distance using Google Maps between any number of coordinates/addresses in Excel Now that we know how to leverage our newly learned GetDistance and GetDuration functions we can use them to measure the distance/duration for any routes.

endLoc) 6 Next i 7 End Function 8 Below example usage: 1 =MultiGetDistance("Chicago". endLoc) 6 Next i 7 End Function 8 Below example usage: 1 =MultiGetDuration("Chicago"."San Jose") And here is the output: Get Google Maps distance between multiple addresses Get duration between any number of locations Similarly by using our GetDuration function we can get the duration between any number of locations using the Visual Basic procedure below: 1 Public Function MultiGetDuration(ParamArray args() As Variant) As Double 2 MultiGetDuration = 0 3 Dim startLoc As String. . i As Long 4 For i = LBound(args) To UBound(args) . This key identifies your application for purposes of quota key management.1 5 startLoc = args(i): endLoc = args(i + 1) MultiGetDuration = MultiGetDuration + GetDuration(startLoc. mode (defaults to driving) — Specifies the mode of transport to use when calculating distance Valid values and other request details are specified in the Travel Modes section of this document."New York".1 startLoc = args(i): endLoc = args(i + 1) 5 MultiGetDistance = MultiGetDistance + GetDistance(startLoc. Learn how to get a key from the Google Developers Console.3 4 For i = LBound(args) To UBound(args) ."San Jose") Parameters for calculating the Google Maps Distance The following parameters are available in the API query: PARAM DESCRIPTION Your application’s API key."New York". endLoc As String.  walking for pedestrian paths & sidewalks (where available). Other modes:  driving (default) for road network.

See my Web Scraping Kit for how I dealt with such . Common issues The functions above are not full proof and don’t take into account:  That Google won’t find the exact addresses and will approximate with a similar address (see component filtering for more precision)  That Google might return several matches.  transit for public transit routes (where available). langua ge The language in which to return results. While the function takes the first one from the returned list  HTTP or timeouts.  2 500 elements per 24 hour period. Is the function returning -1 or simply not working properly? Be sure you have a direct Internet connection! The XMLHttpRequest Object above is not configured to handle proxy servers common for Office environments. Available:  units=metric (fordistances in kilometers and meters) units  units=imperial For other parameters see the original Google Distance Matrix API page: The Google Distance Matrix API Limits and common issues Read more on the limitations of the Google Distance Matrix API here: The Google Distance Matrix API Google limits the amount of free queries to the following:  100 elements per query. There is a way around these limitation via the use of HTTP Proxies.  100 elements per 10 seconds. So beware of any mass recalculation of these functions as you may quickly find yourself exceeding these limits. Available:  avoid=tolls  avoid=highways avoid  avoid=ferries Unit system to use when expressing distance as text.  bicycling for bicycling via bicycle paths & preferred streets (where available). Read more here. See list here Restrictions to the route.

.  That distances/duration differ depending on which location is set as origin and which is set as destination (one way roads. Native VBA Multithreading? There is only 1 butR.... detours etc. Next steps Want to get the geolocation (coordinates) of any address? Excel: Get geolocation (coordinates) of any address Want to add maps and other cool Google Charts in Excel? Excel: Google Charts Tool Want to use Google translate in Excel? Excel: Google Translate functionality Related Posts Visual Basic Editor Tutorial for Excel – How.) Having trouble with matching a large dataset with distances and durations? Reach out for a free quote. Download an example You can download an example of the above here: DOWNLOAD EXAMPLE Help! Need help with calculating the distance between two addresses using the approach above? Feel free to comment below or ask a new Question via Questions page.. R. Excel Substring and VBA Substring – Left. GOOGLE MAPSMACROMAPUDFUSER DEFINED FUNCTIONVBA NEXT POSTGet Google Maps address coordinates (latitude & longitude) in Excel VBA TABLE OF CONTENTS 1 Using the Google Maps Distance Matrix API 2 Calculate distance between two addresses using Google Maps in Excel 3 Calculate distance between two coordinates 4 How to set it up in Excel? 5 Calculate distance using Google Maps between any number of addresses in Excel 6 Parameters for calculating the Google Maps Distance ..

Net  C  C++  PHP  Public Structure Edge Public Source As Integer Public Destination As Integer Public Weight As Integer End Structure Public Structure Graph .  C#  VB. It is a greedy algorithm in graph theory as it finds a minimum spanning tree for a connected weighted graph adding increasing cost arcs at each step. 7 Limits and common issues 8 Download an example 9 Help! 10 Next steps Simply the best place to learn VBA! RECENT POSTS Kruskal's Algorithm Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the least possible weight that connects any two trees in the forest. If the graph is not connected. then it finds a minimum spanning forest (a minimum spanning tree for each connected component). where the total weight of all the edges in the tree is minimized. This means it finds a subset of the edges that forms a tree that includes every vertex.

Sort(graph.Parent = yroot ElseIf subsets(xroot).Parent <> i Then subsets(i).Parent) End If Return subsets(i).Parent = xroot subsets(xroot).edge.Rank += 1 End If End Sub Private Shared Sub Print(result As Edge().VerticesCount Dim result As Edge() = New Edge(verticesCount . x) Dim yroot As Integer = Find(subsets. y As Integer) Dim xroot As Integer = Find(subsets. e As Integer) For i As Integer = 0 To e . result(i).VerticesCount = verticesCount graph.Destination. Function(a As Edge. result(i).Parent = Find(subsets. Public VerticesCount As Integer Public EdgesCount As Integer Public edge As Edge() End Structure Public Structure Subset Public Parent As Integer Public Rank As Integer End Structure Public Shared Function CreateGraph(verticesCount As Integer. x As Integer.EdgesCount = edgesCoun graph.Source. b As Edge) a. y) If subsets(xroot).WriteLine("{0} -.edge = New Edge(graph.1 Console.Parent End Function Private Shared Sub Union(subsets As Subset().Rank Then subsets(yroot).Weight) Next End Sub Public Shared Sub Kruskal(graph As Graph) Dim verticesCount As Integer = graph. i As Integer) As Integer If subsets(i). result(i).Weight)) Dim subsets As Subset() = New Subset(verticesCount .{1} == {2}".Rank > subsets(yroot).Rank Then subsets(xroot). edgesCoun As Integer) As Graph Dim graph As New Graph() graph.Parent = xroot Else subsets(yroot).CompareTo(b.1) {} .Rank < subsets(yroot).EdgesCount .Weight. subsets(i).1) {} Dim i As Integer = 0 Dim e As Integer = 0 Array.1) {} Return graph End Function Private Shared Function Find(subsets As Subset().

1 Dim nextEdge As Edge = graph.Weight = 15 ' Edge 2-3 graph.edge(0).edge(1).Destination = 1 graph.Source = 0 graph.Destination = 3 graph.edge(4).edge(1).edge(i) Dim x As Integer = Find(subsets.Weight = 6 ' Edge 0-3 graph. For v As Integer = 0 To verticesCount .Destination) i += 1 If x <> y Then result(e) = nextEdge e += 1 Union(subsets.Weight = 5 ' Edge 1-3 graph.Weight = 4 Kruskal(graph) .1 subsets(v). nextEdge.edge(1). y) End If End While Print(result. x.Weight = 10 ' Edge 0-2 graph.Rank = 0 Next While e < verticesCount .Source) Dim y As Integer = Find(subsets.edge(2).edge(0).edge(3).edge(2). edgesCount) ' Edge 0-1 graph.edge(4).Source = 0 graph.edge(4). nextEdge.edge(3).Source = 0 graph.Source = 1 graph.Source = 2 graph.Destination = 2 graph. e) End Sub Example Dim verticesCount As Integer = 4 Dim edgesCount As Integer = 5 Dim graph As Graph = CreateGraph(verticesCount.edge(2).edge(3).Destination = 3 graph.edge(0).Destination = 3 graph.Parent = v subsets(v).

3 == 4 0 -.1 == 10 Excel Gantt Chart TutorialExcel VBA Evaluate – Tips and Tricks to .3 == 5 0 -.Output 2 -.