Saturday, 16 February 2019

Geocoding function

This is a very simple function to perform geocoding using the Google Maps API:

getGeoCode <- function(gcStr, key)  {
  library("RJSONIO") #Load Library
  gcStr <- gsub(' ','%20',gcStr) #Encode URL Parameters
  #Open Connection
  connectStr <- paste0('',gcStr, "&key=",key) 
  con <- url(connectStr)
  data.json <- fromJSON(paste(readLines(con), collapse=""))
  #Flatten the received JSON
  data.json <- unlist(data.json)
  if(data.json["status"]=="OK")   {
    lat <- data.json[""]
    lng <- data.json["results.geometry.location.lng"]
    gcodes <- c(lat, lng)
    names(gcodes) <- c("Lat", "Lng")
    return (gcodes)

Essentially, users need to get an API key from google and then use as an input (string) for the function. The function itself is very simple, and it is an adaptation of some code I found on-line (unfortunately I did not write down where I found the original version so I do not have a way to reference the source, sorry!!).

geoCodes <- getGeoCode(gcStr="11 via del piano, empoli", key)

To use the function we simply need to include an address, and it will return its coordinates in WGS84.
It can be used in a mutate call within dplyr and it is reasonably fast.

The repository is here:


  1. Great!! I thought you might have seen my functions for geodata but they are structured differently. Same function was created from scratch in my lares library:
    Hope they become useful as well!

  2. Hi this is fantastic (the first geo code function that has actually worked for me) but I seem to be running into unknown issues with the API? I checked my API developer console and it seemed like the query stopped at around 280 calls (about 1 call per second) - have you tried this function with over 2,000 address to be parsed?

    1. I have tested it with 100s, not 1000s of addresses. Does it give you an API message?


Note: only a member of this blog may post a comment.