Created
January 27, 2016 21:22
-
-
Save andrashann/64c3a00b2f0e22aec75f to your computer and use it in GitHub Desktop.
Get distance and value for origin-destination pairs from Google Maps API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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