Sta*_*t-R 15 xml r google-maps-api-3 driving-distance
我试图通过给出lat/lon来获得两点之间的行驶距离.我可以手动将它们放入谷歌地图并获得驾驶距离,但我想以编程方式完成所有这些操作.
我想JavaScript是最常用的语言.但是,我不知道JavaScript,我相当熟悉使用R.我更喜欢在R中这样做,因为我在R中进行所有数据分析.
我正在寻找沿着道路的距离而不是飞行距离.经过几个小时的尝试,我在R中编写了以下函数(这个和这一个帮助).你有没有更好的方法来获得这个功能或任何非常简单的距离?
library(XML)
latlon2ft <- function(origin,destination)
{
xml.url <- paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=',origin,'&destinations=',destination,'&mode=driving&sensor=false')
xmlfile <- xmlTreeParse(xml.url)
xmltop = xmlRoot(xmlfile)
distance <- xmltop[['row']][[1]][5][1][['distance']][['value']][[1]]
distance <- as.numeric(unclass(distance)[['value']])
ft <- distance*3.28084 # FROM METER TO FEET
return(ft)
}
latlon2ft(origin='37.193489,-121.07395',destination='37.151616,-121.046586')
Run Code Online (Sandbox Code Playgroud)
结果= 17224.41
你需要RCurl或等同于此.
library(XML)
library(bitops)
library(RCurl)
latlon2ft <- 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))
ft <- distance*3.28084 # FROM METER TO FEET
return(ft)
}
latlon2ft(origin='37.193489,-121.07395',destination='37.151616,-121.046586')
Run Code Online (Sandbox Code Playgroud)
结果:
[1] 17224.41
Run Code Online (Sandbox Code Playgroud)
小智 7
我编写该gmapsdistance程序包就是为了做到这一点。它在CRAN上可用。您可以通过以下方式使用该功能:
results = gmapsdistance(origin = "38.1621328+24.0029257",
destination = "37.9908372+23.7383394",
mode = "walking") results
# $Time
# [1] 30025
#
# $Distance
# [1] 39507
#
# $Status
# [1] "OK"
Run Code Online (Sandbox Code Playgroud)
您还可以包括起点和终点的向量,并获得结果距离矩阵。它也支持路线,并且有很多选项:
results = gmapsdistance(origin = c("Washington+DC", "New+York+NY", "Seattle+WA", "Miami+FL"),
destination = c("Los+Angeles+CA", "Austin+TX", "Chicago+IL", "Philadelphia+PA"),
mode = "bicycling",
departure = 1514742000)
results
# $Time
# or Time.Los+Angeles+CA Time.Austin+TX Time.Chicago+IL Time.Philadelphia+PA
# 1 Washington+DC 856621 535146 247765 54430
# 2 New+York+NY 917486 596011 308630 32215
# 3 Seattle+WA 374692 678959 674989 956702
# 4 Miami+FL 829039 416667 452035 411283
#
# $Distance
# or Distance.Los+Angeles+CA Distance.Austin+TX Distance.Chicago+IL Distance.Philadelphia+PA
# 1 Washington+DC 4567470 2838519 1303067 266508
# 2 New+York+NY 4855086 3126136 1590684 160917
# 3 Seattle+WA 1982354 3562970 3588297 5051951
# 4 Miami+FL 4559205 2279966 2381610 2169382
#
# $Status
# or status.Los+Angeles+CA status.Austin+TX status.Chicago+IL status.Philadelphia+PA
# 1 Washington+DC OK OK OK OK
# 2 New+York+NY OK OK OK OK
# 3 Seattle+WA OK OK OK OK
# 4 Miami+FL OK OK OK OK
Run Code Online (Sandbox Code Playgroud)