Skip to content

Instantly share code, notes, and snippets.

@sh4n3d4v15
Last active February 9, 2018 02:11
Show Gist options
  • Save sh4n3d4v15/dc2a6c215efb89080def to your computer and use it in GitHub Desktop.
Save sh4n3d4v15/dc2a6c215efb89080def to your computer and use it in GitHub Desktop.
R functions to lookup distance and duration from two given points
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