Advertisement
DavidVP2019

Geocoding vba excel 2010

Apr 6th, 2019
939
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Option Explicit
  2.  
  3. Function GetCoordinates(Address As String) As String
  4.  
  5.     'This function returns the latitude and longitude of a given address using the Google Geocoding API.
  6.    'The function uses the "simplest" form of Google Geocoding API (sending only the address parameter),
  7.    'so, optional parameters such as bounds, language, region and components are NOT used.
  8.    'In case of multiple results (for example two cities sharing the same name), the function
  9.    'returns the FIRST OCCURRENCE, so be careful in the input address (tip: use the city name and the
  10.    'postal code if they are available).
  11.    
  12.     'NOTE: As Google points out, the use of the Google Geocoding API is subject to a limit of 40,000
  13.    'requests per month, so be careful not to exceed this limit. For more info check:
  14.    'https://cloud.google.com/maps-platform/pricing/sheet
  15.        
  16.     'In order to use this function you must enable the XML, v3.0 library from VBA editor:
  17.    'Go to Tools -> References -> check the Microsoft XML, v3.0.
  18.    'If you don't have the v3.0 use any other version of it (e.g. v6.0).
  19.    
  20.     '2018 Update: In order to use this function you will now need a valid API key.
  21.    'Check the next link that guides you on how to acquire a free API key:
  22.    'https://www.myengineeringworld.net/2018/02/how-to-get-free-google-api-key.html
  23.    
  24.     '2018 Update 2 (July): The EncodeURL function was added to avoid problems with special characters.
  25.    'This is a common problem with addresses that are from Greece, Serbia, Germany and other countries.
  26.    
  27.     'Written By:    Christos Samaras
  28.    'Date:          12/06/2014
  29.    'Last Updated:  09/08/2018
  30.    'E-mail:        xristos.samaras@gmail.com
  31.    'Site:          https://www.myengineeringworld.net
  32.    '-----------------------------------------------------------------------------------------------------
  33.    
  34.     'Declaring the necessary variables.
  35.    'The first 2 variables using 30 at the end, corresponding to the "Microsoft XML, v3.0" library
  36.    'in VBA (msxml3.dll). If you use any other version of it (e.g. v6.0), then declare these variables
  37.    'as XMLHTTP60 and DOMDocument60 respectively.
  38.    Dim ApiKey          As String
  39.     Dim Request         As New XMLHTTP30
  40.     Dim Results         As New DOMDocument30
  41.     Dim StatusNode      As IXMLDOMNode, LatitudeNode As IXMLDOMNode, LongitudeNode As IXMLDOMNode
  42.  
  43.     'Set your API key in this variable. Check this link for more info:
  44.    'https://www.myengineeringworld.net/2018/02/how-to-get-free-google-api-key.html
  45.    '****************************************************************************************************************
  46.    ApiKey = "Your API Key goes here!"
  47.     'example: ApiKey = "lxI800lklv3sdf3v5F6........."
  48.    'Check that an API key has been provided.
  49.    If ApiKey = vbNullString Then
  50.         GetCoordinates = "Invalid API Key"
  51.         Exit Function
  52.     End If
  53.    
  54.     'Generic error handling.
  55.    On Error GoTo errorHandler
  56.    
  57.     'Create the request based on Google Geocoding API. Parameters (from Google page):
  58.    '- Address: The address that you want to geocode.
  59.    'Note: The EncodeURL function was added to allow users from Greece, Poland, Germany, France and other countries
  60.    'geocode address from their home countries without a problem. The particular function (EncodeURL),
  61.    'returns a URL-encoded string without the special characters.
  62.    Request.Open "GET", "https://maps.googleapis.com/maps/api/geocode/xml?" _
  63.     & "&address=" & URLEncode(Address) & "&key=" & ApiKey, False
  64.    
  65.     'Send the request to the Google server.
  66.    Request.send
  67.    
  68.     'Read the results from the request.
  69.    Results.LoadXML Request.responseText
  70.    
  71.     'Get the status node value.
  72.    Set StatusNode = Results.SelectSingleNode("//status")
  73.    
  74.     'Based on the status node result, proceed accordingly.
  75.    Select Case UCase(StatusNode.Text)
  76.    
  77.         Case "OK"   'The API request was successful. At least one geocode was returned.
  78.            
  79.             'Get the latitude and longitude node values of the first geocode.
  80.            Set LatitudeNode = Results.SelectSingleNode("//result/geometry/location/lat")
  81.             Set LongitudeNode = Results.SelectSingleNode("//result/geometry/location/lng")
  82.            
  83.             'Return the coordinates as a string (latitude, longitude).
  84.            GetCoordinates = LatitudeNode.Text & ", " & LongitudeNode.Text
  85.        
  86.         Case "ZERO_RESULTS"   'The geocode was successful but returned no results.
  87.            GetCoordinates = "The address probably not exists"
  88.            
  89.         Case "OVER_QUERY_LIMIT" 'The requestor has exceeded the limit of 2500 request/day.
  90.            GetCoordinates = "Requestor has exceeded the server limit"
  91.            
  92.         Case "REQUEST_DENIED"   'The API did not complete the request.
  93.            GetCoordinates = "Server denied the request"
  94.            
  95.         Case "INVALID_REQUEST"  'The API request is empty or is malformed.
  96.            GetCoordinates = "Request was empty or malformed"
  97.        
  98.         Case "UNKNOWN_ERROR"    'Indicates that the request could not be processed due to a server error.
  99.            GetCoordinates = "Unknown error"
  100.        
  101.         Case Else   'Just in case...
  102.            GetCoordinates = "Error"
  103.        
  104.     End Select
  105.        
  106.     'In case of error, release the objects.
  107. errorHandler:
  108.     Set StatusNode = Nothing
  109.     Set LatitudeNode = Nothing
  110.     Set LongitudeNode = Nothing
  111.     Set Results = Nothing
  112.     Set Request = Nothing
  113.    
  114. End Function
  115.  
  116. '-------------------------------------------------------------------------------------------------------------------
  117. 'The next two functions using the GetCoordinates function to get the latitude and the longitude of a given address.
  118. '-------------------------------------------------------------------------------------------------------------------
  119. Function GetLatitude(Address As String) As Double
  120.    
  121.     'Declaring the necessary variable.
  122.    Dim Coordinates As String
  123.    
  124.     'Get the coordinates for the given address.
  125.    Coordinates = GetCoordinates(Address)
  126.    
  127.     'Return the latitude as a number (double).
  128.    If Coordinates <> vbNullString Then
  129.         GetLatitude = CDbl(Left(Coordinates, WorksheetFunction.Find(",", Coordinates) - 1))
  130.     Else
  131.         GetLatitude = 0
  132.     End If
  133. End Function
  134.  
  135. Function GetLongitude(Address As String) As Double
  136.  
  137.     'Declaring the necessary variable.
  138.    Dim Coordinates As String
  139.    
  140.     'Get the coordinates for the given address.
  141.    Coordinates = GetCoordinates(Address)
  142.    
  143.     'Return the longitude as a number (double).
  144.    If Coordinates <> vbNullString Then
  145.         GetLongitude = CDbl(Right(Coordinates, Len(Coordinates) - WorksheetFunction.Find(",", Coordinates)))
  146.     Else
  147.         GetLongitude = 0
  148.     End If
  149.    
  150. End Function
  151.  
  152.  
  153. 'Written By:    wandy sae-tan
  154. Function URLEncode(ByVal Text As String) As String
  155.     Dim i As Integer
  156.     Dim acode As Integer
  157.     Dim char As String
  158.     URLEncode = Text
  159.     For i = Len(URLEncode) To 1 Step -1
  160.       acode = Asc(Mid$(URLEncode, i, 1))
  161.       Select Case acode
  162.         Case 48 To 57, 65 To 90, 97 To 122
  163.           ' don't touch alphanumeric chars
  164.        Case 32
  165.           ' replace space with "+"
  166.          Mid$(URLEncode, i, 1) = "+"
  167.         Case Else
  168.           ' replace punctuation chars with "%hex"
  169.          URLEncode = Left$(URLEncode, i - 1) & "%" & Hex$(acode) & Mid$(URLEncode, i + 1)
  170.       End Select
  171.     Next
  172. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement