Translate

Friday, 8 December 2017

Connect to Google Map API from R

The below enables geocoding from R using Google Map API.

The relevant website is:

https://developers.google.com/maps/

There is a restriction on how many requests can be made per day for free usage etc, and the above website provides the necessary information and guidelines.

While it is not necessary, you can download your own key for additional benefits including tracking of the usage. Please see below link:

https://developers.google.com/maps/documentation/javascript/get-api-key


EXAMPLE:


library(RJSONIO)

#if you are using a key
KEY<-as.character(read.table("//[path to your Google Key]/[name of file containing the key (e.g. '.GoogleApiKey.txt']", header=FALSE, sep = ""))

search_url <- paste("https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=[insert address or location searched]&key=", KEY, sep = "")


#if you are NOT using a key
search_url <- "https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=[insert address or location searched]"
  
  
con <- url(search_url, open="r")
  
geo_info <- fromJSON(paste(readLines(con), collapse=""))

close(con)

#Flatten the received JSON
geo_info  <- unlist(geo_info )

latitude <- geo_info["results.geometry.location.lat"]
longitude <- geo_info["results.geometry.location.lng"]








No comments:

Post a Comment