Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get distance and value for origin-destination pairs from Google Maps API
require(jsonlite)
require(curl)
google_maps <- function(datafile, gapikey, save_file = FALSE){
# This function takes origin-destination pairs and returns the distance and
# trip duration between these pairs as a data frame
#
# _datafile_ is a string that is the name of a csv file in which each line
# contains an origin and a destination separated by a comma.
#
# _gapikey_ is the Google Maps API key, also a string.
#
# Note: distances are in meters, durations are in seconds.
gdist <- as.numeric()
gdur <- as.numeric()
data <- read.csv(file = paste0(datafile), header = FALSE)
names(data) <- c("from", "to")
for (i in 1:nrow(data)){
jsonData <- fromJSON(paste0("https://maps.googleapis.com/maps/api/directions/json?origin=", data[i,1] ,
"&destination=", data[i,2], "&key=",gapikey))
if(!is.null(unlist(jsonData$routes$legs[1])["distance.value"])){
gdist <- c(gdist, unlist(jsonData$routes$legs[1])["distance.value"])
gdur <- c(gdur, unlist(jsonData$routes$legs[1])["duration.value"])
} else {
gdist <- c(gdist, NA)
gdur <- c(gdur, NA)
}
}
data <- cbind(data, gdist, gdur)
if (save_file == TRUE){
write.csv(data, file = paste0("dist_matrix_", datafile))
message(paste0('Note: results saved as "dist_matrix_', datafile, '"'))
}
return(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment