Tuesday, March 20, 2012

Geocode and reverse geocode your data using, R, JSON and Google Maps' Geocoding API


Geocode and reverse geocode your data using, R, JSON and Google Maps' Geocoding API

To geocode and reverse geocode my data, I use Google's Geocoding service which returns the geocoded data in a JSON. I will recommend that you register with Google Maps API and get a key if you have large amount of data and would do repeated geo coding.

Geocode:

getGeoCode <- function(gcStr)  {
  library("RJSONIO") #Load Library
  gcStr <- gsub(' ','%20',gcStr) #Encode URL Parameters
 #Open Connection
 connectStr <- paste('http://maps.google.com/maps/api/geocode/json?sensor=false&address=',gcStr, sep="") 
  con <- url(connectStr)
  data.json <- fromJSON(paste(readLines(con), collapse=""))
  close(con)
  #Flatten the received JSON
  data.json <- unlist(data.json)
  if(data.json["status"]=="OK")   {
    lat <- data.json["results.geometry.location.lat"]
    lng <- data.json["results.geometry.location.lng"]
    gcodes <- c(lat, lng)
    names(gcodes) <- c("Lat", "Lng")
    return (gcodes)
  }
}
geoCodes <- getGeoCode("Palo Alto,California")
> geoCodes
           Lat            Lng 
  "37.4418834" "-122.1430195" 

Reverse Geocode:
reverseGeoCode <- function(latlng) {
latlngStr <-  gsub(' ','%20', paste(latlng, collapse=","))#Collapse and Encode URL Parameters
  library("RJSONIO") #Load Library
  #Open Connection
  connectStr <- paste('http://maps.google.com/maps/api/geocode/json?sensor=false&latlng=',latlngStr, sep="")
  con <- url(connectStr)
  data.json <- fromJSON(paste(readLines(con), collapse=""))
  close(con)
  #Flatten the received JSON
  data.json <- unlist(data.json)
  if(data.json["status"]=="OK")
    address <- data.json["results.formatted_address"]
  return (address)
}
address <- reverseGeoCode(c(37.4418834, -122.1430195))
> address
                    results.formatted_address 
"668 Coleridge Ave, Palo Alto, CA 94301, USA" 

 Happy Coding!



5 comments:

  1. Thanks a lot!!
    Do you know if it's possible to get more then only the x & y. I was thinking about the code error from Google, from 1 to 9. Can I get i maybe from the JSON file? Thanks again

    ReplyDelete
  2. I have looked up longitude and lat and the address it gives me is 668 coleridge ave Palo alto,Ca, theres no listing there???? Help

    ReplyDelete
  3. Excellent post and very informative as well. Your knowledge appears very well on this topic and the way you have explained it, any new person can understand it easily. I would like you to keep writing like this and share your information with us. bridal bed sheet design ideas , vicky razai price in pakistan 2021 ,

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete