Last active
February 9, 2018 02:11
-
-
Save sh4n3d4v15/dc2a6c215efb89080def to your computer and use it in GitHub Desktop.
R functions to lookup distance and duration from two given points
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
library(RCurl) | |
library(RJSONIO) | |
library(plyr) | |
url <- function(origin, destination) { | |
root <- "https://maps.googleapis.com/maps/api/directions/json" | |
u <- paste(root, "?origin=", origin, "&destination=", destination, "&key=AIzaSyAuj0ix2b8t54hrhIEHRsQNk0r6y9eBK2U", sep = "") | |
return (URLencode(u)) | |
} | |
lookupDistanceAndDuration <- function(orgin,destination,verbose = FALSE) { | |
if (verbose) cat(address, "\n") | |
u <- url(orgin,destination) | |
print(u) | |
doc <- getURL(u) | |
x <- fromJSON(doc, simplify = FALSE) | |
if (x$status == "OK") { | |
distance <- x$routes[[1]]$legs[[1]]$distance$value | |
duration <- x$routes[[1]]$legs[[1]]$duration$value | |
return (c(distance,duration)) | |
}else{ | |
return (c(NA,NA)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment