Skip to content

Instantly share code, notes, and snippets.

@MonkmanMH
Forked from josecarlosgonz/GoogleMapsAndR.md
Last active December 22, 2015 14:29
Show Gist options
  • Save MonkmanMH/6486001 to your computer and use it in GitHub Desktop.
Save MonkmanMH/6486001 to your computer and use it in GitHub Desktop.

Using Google Maps API and R

[source: http://www.r-bloggers.com/using-google-maps-api-and-r/] [address modifications added by MonkmanMH]

This script uses RCurl and RJSONIO to download data from Google's API to get the latitude, longitude, location type, and formatted address

library(RCurl)
library(RJSONIO)
library(plyr)

Build a URL to access the API:

url <- function(address, return.call = "json", sensor = "false") {
  root <- "http://maps.google.com/maps/api/geocode/"
  u <- paste(root, return.call, "?address=", address, "&sensor=", sensor, sep = "")
  return(URLencode(u))
}

Function to parse the results>

geoCode <- function(address,verbose=FALSE) {
  if(verbose) cat(address,"\n")
  u <- url(address)
  doc <- getURL(u)
  x <- fromJSON(doc,simplify = FALSE)
  if(x$status=="OK") {
    lat <- x$results[[1]]$geometry$location$lat
    lng <- x$results[[1]]$geometry$location$lng
    location_type  <- x$results[[1]]$geometry$location_type
    formatted_address  <- x$results[[1]]$formatted_address
    return(c(lat, lng, location_type, formatted_address))
    Sys.sleep(0.5)
  } else {
    return(c(NA,NA,NA, NA))
  }
}

Test with one address

address <- geoCode("553 Superior Street, Victoria, BC")

First two items are the latitude and longitude coordinates, then the location type and formatted address

address

We can use Plyr to geocode a vector with addresses

address <- c("553 Superior Street, Victoria, BC","Serious Coffee James Bay, Victoria, BC")
locations  <- ldply(address, function(x) geoCode(x))
names(locations)  <- c("lat","lon","location_type", "formatted")
head(locations)

The following are the different location types:

  • "ROOFTOP" indicates that the returned result is a precise geocode for which we have location information accurate down to street address precision.
  • RANGE_INTERPOLATED" indicates that the returned result reflects an approximation (usually on a road) interpolated between two precise points (such as intersections). Interpolated results are generally returned when rooftop geocodes are unavailable for a street address.
  • GEOMETRIC_CENTER" indicates that the returned result is the geometric center of a result such as a polyline (for example, a street) or polygon (region).
  • APPROXIMATE" indicates that the returned result is approximate.

For more info on Google Maps API check here

Another example of pulling info from Google Maps

Source http://ekonometrics.blogspot.ca/2011/04/google-maps-and-travel-times.html

# ############################################
# all the necessary packages
if (!require(rjson)) install.packages("rjson")
library(rjson)
#
if (!require(RJSONIO)) install.packages("RJSONIO")
library(RJSONIO)
#
if (!require(gooJSON)) install.packages("gooJSON")
library(gooJSON)
#
if (!require(RCurl)) install.packages("RCurl")
library(RCurl)
#
#An example of coordinates
xlat<-57.372801
xlong<-2.016214
ylat<-57.459688
ylong<-2.790558
#
#Writing the corresponding url
z<-paste("http://maps.google.com/maps/api/directions/json?origin=", +
         xlat,",",xlong,"&destination=",ylat,",",ylong," +
         &sensor=false",sep="")
#
#To get and read the json file
x<-fromJSON(getURL(url=z))
#
#To catch the Google limitation on requests (it often happens)
if(x$status=="OVER_QUERY_LIMIT"){
while(x$status=="OVER_QUERY_LIMIT"){Sys.sleep(10*60) ;print("wait for 10 mins")}
}
#
x<-fromJSON(getURL(url=z))
#
#
#To get the total travel time
TRAVEL_TIME<-x[[2]][[1]][[2]][[1]][[2]]$text
print(TRAVEL_TIME)
#

JSON and associated R Packages

RJSON http://cran.r-project.org/web/packages/rjson/index.html http://crantastic.org/packages/rjson http://stackoverflow.com/questions/2617600/importing-data-from-a-json-file-into-r http://laclefyoshi.blogspot.ca/2011/02/processing-json-with-r-rjson.html

RJSONIO http://cran.r-project.org/web/packages/RJSONIO/index.html http://www.inside-r.org/packages/cran/RJSONIO/docs/fromJSON http://www.omegahat.org/RJSONIO/

gooJSON http://cran.r-project.org/web/packages/gooJSON/index.html

Stack Overflow http://stackoverflow.com/questions/3845639/how-can-i-use-google-maps-api-to-return-a-journey-time-with-and-without-traffic http://stackoverflow.com/questions/1042885/using-google-maps-api-to-get-travel-time-data

Google Maps API reference pages

https://developers.google.com/maps/documentation/javascript/distancematrix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment