1

我一直在尝试 2 个邮政编码之间的地图距离。我有大约 3 万条记录。我知道谷歌每天只允许 2500 个查询,因此我现在有一个来自他们的 API。出于某种原因 - 我一直在努力将 API 密钥插入代码中。我还遇到了另一个名为 googleway 的包——它做同样的事情,但我喜欢 mapdist 的格式。有没有办法:

a) 在此代码中使用 API 或
b) 使用 google way 包填充与 mapdist 类似的结果

提前感谢您的支持。

library(ggmap)
library(plyr)
library(googleway)
key <- "XXX"

file_loc <- "C:/Users/Owner/Desktop/distance.csv"

x <- read.csv(file_loc, header = TRUE)

from <- x[1]
to <- x[2]

DF <- cbind(from, to); DF <- as.data.frame(DF) # create data frame
DF$from <- as.character(DF$from) # mapdist demands input to be character type
DF$to <- as.character(DF$to)     # mapdist demands input to be character type
remove (from, to) #remove input to avoid confusion

DF$row.number <- 1:nrow(DF)      #create an index number for each row


for (i in DF$row.number){
  orig <- DF[i,c('from')]
  dest <- DF[i,c('to')]
  a <- mapdist(from = orig, to = dest, mode = "driving",output = c("simple", "all"), override_limit = FALSE)
  a$row.number <- i
  DF$minutes[match(a$row.number, DF$row.number)] <- a$minutes
  DF$hours[match(a$row.number, DF$row.number)] <- a$hours
  DF$km[match(a$row.number, DF$row.number)] <- a$km
  DF$miles[match(a$row.number, DF$row.number)] <- a$miles
}


write.csv(DF, "newdata.csv") #Save dataset
4

1 回答 1

4

据我所知,您无法指定 API 密钥ggmap::mapdist

至于googleway(我写了包),使用方法是

key <- "your_api_key"
google_distance(origins = list("MCG, Melbourne, Australia"),
                destinations = list("Sydney Opera House, Australia"),
                key = key)

# $destination_addresses
# [1] "Sydney NSW, Australia"
# 
# $origin_addresses
# [1] "Jolimont Station, Wellington Cres, East Melbourne VIC 3002, Australia"
# 
# $rows
# elements
# 1 869 km, 869270, 8 hours 51 mins, 31847, 8 hours 45 mins, 31485, OK
# 
# $status
# [1] "OK"

或者,如果您有一个来自/到地址的 data.frame:

df <- data.frame(from = c("MCG, Melbourne, Australia", "Sydney Opera House, Australia"),
                 to = c("Sydney Opera House, Australia", "Canberra, Australia"))


res <- apply(df, 1, function(x){

    google_distance(origins = list(x["from"]),
                    destinations = list(x["to"]),
                    key = key)

})
res
# [[1]]
# [[1]]$destination_addresses
# [1] "Sydney NSW, Australia"
# 
# [[1]]$origin_addresses
# [1] "Jolimont Station, Wellington Cres, East Melbourne VIC 3002, Australia"
# 
# [[1]]$rows
# elements
# 1 869 km, 869270, 8 hours 51 mins, 31847, 8 hours 44 mins, 31451, OK
# 
# [[1]]$status
# [1] "OK"
# 
# 
# [[2]]
# [[2]]$destination_addresses
# [1] "Canberra ACT 2601, Australia"
# 
# [[2]]$origin_addresses
# [1] "Sydney NSW, Australia"
# 
# [[2]]$rows
# elements
# 1 286 km, 286143, 3 hours 1 min, 10859, 3 hours 6 mins, 11152, OK
# 
# [[2]]$status
# [1] "OK"
于 2016-07-27T00:50:49.747 回答