在R中绘制行车路线

Drawing driving routes in R

我正在关注这个问题中提供的答案:

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

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

所以换句话说,我认为我的 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")

当我进入 "apply" 循环时,我收到错误 "Error in 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
)

效果很好。有任何想法吗?我想知道是不是因为我的位置只有城市名称(没有州或国家),所以我调整了示例数据只说 "Melbourne" 或 "Sydney",仍然有效。

不管它值多少钱,我只是 运行 你的代码没有任何问题。因此,@Dave2e 怀疑您的 API 调用可能有问题,超时或 google 由于某种原因未返回结果。所以你必须继续调试/打印结果以查看是否是这种情况。

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")