gpt4 book ai didi

r - 使用纬度和经度向量查找 R 中的步行距离

转载 作者:行者123 更新时间:2023-12-02 03:31:43 25 4
gpt4 key购买 nike

您好,我有一系列住宅和一系列火车站。我想计算从每个家庭(n=1718)到每个车站(n=11)的步行距离。我知道谷歌限制你每天 2000 次观察,所以我会把所有的家庭观察都做成 1 个站。我的数据如下所示:

Home data:                      

longitude latitude
1 -76.27769 36.86308
2 -76.29188 36.87556
3 -76.26982 36.86628
4 -76.27455 36.86894

Station Data
Longitude Latitude
1 -76.30377 36.85945
2 -76.29490 36.85395
3 -76.28896 36.85156
4 -76.28989 36.84719
5 -76.28579 36.84568

我找到了这样的代码,但它总结了每个家庭的距离,而不是每个家庭的距离。我是 R 的新手...帮助!

  `distHoras <- function(origin, destination){

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

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


mode4url <- paste("mode=", 'walking', sep = "")
lang4url <- paste("language=", 'en-EN', sep = "")
sensor4url <- paste("sensor=", tolower(as.character(FALSE)),
sep = "")
posturl <- paste(origin, destination, 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('origin', 'destination')
elements.distance.text elements.distance.value
"1,253 km" "1252635"
elements.duration.text elements.duration.value
"9 days 8 hours" "804659"
elements.status
"OK"

最佳答案

像这样的东西??

google.dist <- function(from,to,mode="walking") {
require(httr)
require(XML)
url <- "https://maps.googleapis.com/maps/api/distancematrix/xml"
origin <- paste(with(from,paste(latitude,longitude,sep=",")),collapse="|")
dest <- paste(with(to,paste(latitude,longitude,sep=",")),collapse="|")
response <- GET(url,query=list(origins=origin,destinations=dest,mode=mode))
doc <- content(response,type="text/xml")
status <- sapply(doc["//row/element/status"],xmlValue)
if(any(status!="OK")) warning("Error Status on some routes")
distance <- sapply(doc["//row/element/distance/value"],xmlValue)
data.frame(expand.grid(to=1:nrow(to),from=1:nrow(from)),distance=as.numeric(distance))
}
google.dist(Home,Station)
# to from distance
# 1 1 1 3275
# 2 2 1 2494
# 3 3 1 2163
# 4 4 1 2548
# 5 5 1 2212
# 6 1 2 2539
# 7 2 2 2950
# 8 3 2 3288
# 9 4 2 3815
# 10 5 2 4034
# ...

这使用带有 XML 输出的 Google 距离矩阵 API。返回的数据框包含 tofrom 数据框的行号以及它们之间的距离。 API 已记录 here .请注意terms of use .

关于r - 使用纬度和经度向量查找 R 中的步行距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26303308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com