你在找这个吗:
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
使用谷歌地图计算地图距离。
为了回答您的问题,我认为使用 json 版本的 google API 比使用 XML 版本更容易(甚至推荐)。
这是一个使用RJSONIO
. 甚至我建议你使用上面的功能。无需进行任何转换,因为结果已经在数小时内。
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)
}
现在你测试它:
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"