I use the following function to estimate the time (in hours) to drive a certain distance, assuming an average speed of 65 km/h:
distHoras <- function(origin, destination){
xml.url <- paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=',
origin, '&destinations=', destination, '&mode=driving&sensor=false')
xmlfile <- xmlParse(getURL(xml.url))
dist <- xmlValue(xmlChildren(xpathApply(xmlfile,"//distance")[[1]])$value)
distance <- as.numeric(sub(" km", "", dist))
time <- (distance / 1000) / 65
return(time)
}
How can I tweak this function in order to have it yield time directly, so I don't need to make this 65 km/h assumption and thus get a better estimate? After reading the documentation, I tried switching 'distance' with 'duration', but it didn't work. I'm probably missing something simple, but I'm quite new to working with APIs and am overwhelmed by all that text. Appreciate any help!
Are you looking for this :
mapdist
Compute map distances using Google Maps.To answer your question, I think it is easier (even recommended) to use json version of google API than XML one.
Here a fast version using
RJSONIO
. Even I recommend you to use the function above. No need to do any conversion since the result is already in hours.Now you test it :