Scraping duration and distance from Google Maps – R

Here is a simple R code to scrape distance and duration for a set of postcodes from source (origin).

Prerequisite :

You will need a KEY to access Google Maps API. If intending to use it to create a data set (like me), a Standard API user plan which is free with an allowance of 25000 calls per day will do. Else, you will have to go for the premium version.

The following link will explain how to get a key .

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

R Code: 


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

postcode<-c('SW19','SW3','SM2')

url <- function(address, return.call = "json", sensor = "false") {

## Replace the dots with the key you generated in the above step.

key <- '...'

origins <- 'SE1'

root <- paste0('https://maps.googleapis.com/maps/api/distancematrix/json?key=',key,
'&units=imperial&origins=',origins,',london&destinations=')

u <- paste(root, address,',london,UK', sep = "")

return(URLencode(u))
}
rm(output)

output<-data.frame(postcode=character(),dis=character(),dur=character(),stringsAsFactors=FALSE)

for (i in 1:length(postcode)) {

address<-postcode[i]

u <- url(address)
doc <- getURL(u)
x <- fromJSON(doc,simplify = FALSE)

dis<-x$rows[[1]]$elements[[1]]$distance$text
dur<-x$rows[[1]]$elements[[1]]$duration$text

tmp<-data.frame(postcode=address,dis=dis,dur=dur)
output<-rbind(output,tmp)

}

View(output)

 The output of the above code will be :

R_GMaps_Output

 

Leave a Reply

Your email address will not be published. Required fields are marked *