假设平均速度为65 km / h,我使用以下函数估算行驶一定距离的时间(以小时为单位): distHoras - function(origin, destination){ xml.url - paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=', orig
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) }
我如何调整此函数以使其直接产生时间,因此我不需要进行65 km / h的假设,从而得到更好的估计?阅读the documentation之后,我尝试将“距离”切换为“持续时间”,但它无法正常工作.我可能错过了一些简单的东西,但我对使用API很新,并且被所有文本所淹没.感谢任何帮助!
你在找这个: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使用Google地图计算地图距离.
为了回答你的问题,我认为使用json版本的谷歌API比使用谷歌API更容易(甚至推荐).
这是使用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"