gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:39:34 25 4
gpt4 key购买 nike

我正在创建一个 Shiny 仪表板,其中包含我在 R 中绘制的起始经度/纬度和结束经度/纬度的 dataframe使用传单包:

`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())`

我想知道是否有办法连接公共(public)交通路线协调的起点和终点(也许通过谷歌地图 API 或库内功能,或者如果失败,则通过直线连接坐标?

最佳答案

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

要使用 Google 的 API,您需要为要使用的每个 API 提供有效 key 。在这种情况下,您需要 directions key ,为了绘制 map ,您需要 maps javascript key

(如果您愿意,您可以生成一个 key 并为两个 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")

enter image description here

<小时/>

在 Shiny 的应用程序中也是如此

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)

enter image description here

关于r - 在 R 中使用传单绘制旅程路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42026578/

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