How do I get driving time from Google Maps API?

杀马特。学长 韩版系。学妹 提交于 2019-12-01 07:35:26

Are you looking for this :

library(ggmap)
from <- 'Paris'
to <- 'London'
mapdist(from,to,mode='driving')
 from     to      m      km    miles seconds  minutes    hours
1 Paris London 454416 454.416 282.3741   18283 304.7167 5.078611

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.

library(RJSONIO)
distHoras <- function(origin, destinations){

origin <- gsub(",", "", origin)
origin <- gsub(" ", "+", origin)
origin <- paste("origins=", origin, sep = "")

destinations <- gsub(",", "", destinations)
destinations <- gsub(" ", "+", destinations)
destinations <- paste("destinations=", paste(destinations, 
                                             collapse = "|"), sep = "")


mode4url <- paste("mode=", 'driving', sep = "")
lang4url <- paste("language=", 'en-EN', sep = "")
sensor4url <- paste("sensor=", tolower(as.character(FALSE)), 
                   sep = "")
posturl <- paste(origin, destinations, mode4url, sensor4url, 
                 sep = "&")
url_string <- paste("http://maps.googleapis.com/maps/api/distancematrix/json?", 
                    posturl, sep = "")
url_string <- URLencode(url_string)
connect <- url(url_string)
tree <- fromJSON(paste(readLines(connect), collapse = ""))
close(connect)
rapply(tree$rows,I)
}

Now you test it :

distHoras('Paris','London')
 elements.distance.text elements.distance.value  elements.duration.text 
               "454 km"                "454416"        "5 hours 5 mins" 
elements.duration.value         elements.status 
                "18283"                    "OK" 

I'm going to throw my own pacakge into the mix that also queries Google's API for you

(You need a valid Google API key to use it)

library(googleway)

api_key <- "your_api_key_here"

google_distance(origins = "Paris", 
                                destinations = "London",
                                key = api_key)

# $destination_addresses
# [1] "London, UK"
# 
# $origin_addresses
# [1] "Paris, France"
# 
# $rows
# elements
# 1 456 km, 456230, 5 hours 31 mins, 19858, 6 hours 12 mins, 22311, OK
# 
# $status
# [1] "OK"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!