1

我正在关注这个问题中提供的答案:使用 R 中的传单绘制旅程路径

并希望复制相同的想法:绘制显示城市之间行驶路线的地图。

作为参考,当我简单地复制并粘贴 SymbolixAu 答案中的代码时......效果很好!(简单的地图,即 googe_map,而不是“闪亮”的代码)。

所以换句话说,我认为我的 api 密钥设置得很好。但是由于某种原因,当我尝试在我的位置数据上使用相同的代码时,它不起作用。这是我的代码:

df_locations<-structure(list(origin = c("WARWICK", "EAST PROVIDENCE", "WARREN", 
                      "CENTERDALE", "CENTRAL FALLS", "DAVISVILLE", "NORTH PROVIDENCE", 
                      "EAST PROVIDENCE", "PROVIDENCE", "CHEPACHET"), destination = c("CENTERDALE", "EAST PROVIDENCE", "BRISTOL", "JOHNSTON", "CRANSTON", "WARWICK","NORTH PROVIDENCE", "EAST PROVIDENCE", "WARREN", "CHEPACHET")), class = "data.frame", row.names = c(NA, -10L))


## loop over each pair of locations, and extract the polyline from the result
lst_directions <- apply(df_locations, 1, function(x){
res <- google_directions(
key = api_key
, origin = x[['origin']]
, destination = x[['destination']]
)

df_result <- data.frame(
origin = x[['origin']]
, destination = x[['destination']]
, route = res$routes$overview_polyline$points
)
return(df_result)
})

## convert the results to a data.frame
df_directions <- do.call(rbind, lst_directions)

## plot the map
google_map(key = map_key ) %>%
add_polylines(data = df_directions, polyline = "route")

当我进入“应用”循环时,我收到错误“data.frame 中的错误(origin = x[[“origin”]],destination = x[[“destination”]],:参数意味着不同的数量行:1、0"

当我重新运行完全相同的代码时,只需使用示例数据框:

df_locations <- data.frame(
origin = c("Melbourne, Australia", "Sydney, Australia")
, destination = c("Sydney, Australia", "Brisbane, Australia")
, stringsAsFactors = F
)

它完美地工作。有任何想法吗?我想知道是不是因为我的位置只有城市名称(没有州或国家),所以我调整了示例数据,只说“墨尔本”或“悉尼”,仍然有效。

4

1 回答 1

2

对于它的价值,我只是运行你的代码没有任何问题。因此,@Dave2e 怀疑您的 API 调用可能有问题,无论是超时还是谷歌由于某种原因没有返回结果。因此,您必须继续调试/打印结果以查看是否是这种情况。

df_locations<-structure(list(origin = c("WARWICK", "EAST PROVIDENCE", "WARREN", 
                                        "CENTERDALE", "CENTRAL FALLS", "DAVISVILLE", "NORTH PROVIDENCE", 
                                        "EAST PROVIDENCE", "PROVIDENCE", "CHEPACHET"), destination = c("CENTERDALE", "EAST PROVIDENCE", "BRISTOL", "JOHNSTON", "CRANSTON", "WARWICK","NORTH PROVIDENCE", "EAST PROVIDENCE", "WARREN", "CHEPACHET")), class = "data.frame", row.names = c(NA, -10L))

library(googleway)

set_key("MYKEY")


## loop over each pair of locations, and extract the polyline from the result
lst_directions <- apply(df_locations, 1, function(x){
  res <- google_directions(
    origin = x[['origin']]
    , destination = x[['destination']]
  )

  df_result <- data.frame(
    origin = x[['origin']]
    , destination = x[['destination']]
    , route = res$routes$overview_polyline$points
  )
  return(df_result)
})

df_directions <- do.call(rbind, lst_directions)

## plot the map
google_map() %>%
  add_polylines(data = df_directions, polyline = "route")

在此处输入图像描述

于 2020-01-16T23:00:57.120 回答