加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – 如何从Google Maps API获取驾驶时间?

发布时间:2020-12-16 22:58:09 所属栏目:百科 来源:网络整理
导读:假设平均速度为65 km / h,我使用以下函数估算行驶一定距离的时间(以小时为单位): distHoras - function(origin,destination){ xml.url - paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=',origin,'destinations=',destination,'m
假设平均速度为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)
}

我如何调整此函数以使其直接产生时间,因此我不需要进行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=",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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读