使用传单在R中绘制旅程路径

mys*_*man 4 r leaflet shinydashboard

我正在创建一个Shiny仪表板,其中dataframe包含开始经度/纬度和经度/纬度结束,我R使用以下方法绘制了leaflet package:

`m=leaflet()%>%
      addTiles() %>%
      addMarkers(lng=(data$Start_long[i:j]), lat=(data$Start_lat[i:j]),popup="Start") %>%
      addCircleMarkers(lng=(data$End_long[i:j]), lat=(data$End_lat[i:j]),popup="End",clusterOptions=markerClusterOptions())`
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法加入由公共交通路线协调的开始和结束(可能通过谷歌地图API或库内功能或失败,加入坐标直线?

Sym*_*xAU 9

您可以使用我的googleway包来获取路线/路线,并将其绘制在Google地图上

要使用Google的API,您需要为要使用的每个API提供有效密钥.在这种情况下,您需要一个方向键,并且为了绘制地图,您需要一个地图javascript键

(如果您愿意,可以生成一个密钥并为两个API启用它)

要调用Directions API并将其绘制在R中,您就可以执行此操作

library(googleway)

api_key <- "your_directions_api_key"
map_key <- "your_maps_api_key"

## set up a data.frame of locations
## can also use 'lat/lon' coordinates as the origin/destination
df_locations <- data.frame(
  origin = c("Melbourne, Australia", "Sydney, Australia")
  , destination = c("Sydney, Australia", "Brisbane, Australia")
  , stringsAsFactors = F
)

## 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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


同样在一个闪亮的应用程序中

library(shiny)
library(shinydashboard)
library(googleway)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    textInput(inputId = "origin", label = "Origin"),
    textInput(inputId = "destination", label = "Destination"),
    actionButton(inputId = "getRoute", label = "Get Rotue"),
    google_mapOutput("myMap")
  )
)

server <- function(input, output){

  api_key <- "your_directions_api_key"
  map_key <- "your_maps_api_key"

  df_route <- eventReactive(input$getRoute,{

    print("getting route")

    o <- input$origin
    d <- input$destination

    return(data.frame(origin = o, destination = d, stringsAsFactors = F))
  })


  output$myMap <- renderGoogle_map({

    df <- df_route()
    print(df)
    if(df$origin == "" | df$destination == "")
      return()

    res <- google_directions(
      key = api_key
      , origin = df$origin
      , destination = df$destination
    )

    df_route <- data.frame(route = res$routes$overview_polyline$points)

    google_map(key = map_key ) %>%
      add_polylines(data = df_route, polyline = "route")
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述