使用R中的leaflet绘制路径旅程

5

我正在使用leaflet包R中绘制起始经纬度和结束经纬度坐标的dataframe,并创建了一个Shiny仪表板:

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

我想知道是否有一种方式可以通过公共交通路线(例如 Google Maps API 或库函数)连接起始和结束坐标,如果不行,是否可以通过直线连接这些坐标?

3个回答

11
你可以使用我的googleway包来获取方向/路线并在Google地图上绘制它。
要使用Google的API,您需要为要使用的每个API获得有效的密钥。在这种情况下,您将需要一个方向键,以及绘制地图您将需要一个maps 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")

输入图像描述


同样地,在一个 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)

图片描述


3
你可以向地图中添加addPolylines()。它需要两个矢量作为参数,一个是纬度,一个是经度,每行表示一个“路标”。 不了解你的数据结构就很难帮助你。 MRE:
library(leaflet)
cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))

leaflet() %>% 
    addTiles() %>% 
    addPolylines(lat = cities$Lat, lng = cities$Long)

我尝试了折线,但所有的线都连接在一起。数据基本上是5列,地点名称和起始/结束经纬度。 - mystery man
这真的取决于你的数据结构。请提供一个可重现的例子。 - GGamba
希望这可以帮到您: 开始地点 结束地点 日期 开始纬度 开始经度 结束纬度 结束经度 Harwood Bury 17/05/16 53.5984 -2.38731 53.59125 -2.29713 Harwood Wigan 17/05 /16 53.5984 -2.38731 53.54582 -2.63202 等等 - mystery man
抱歉,似乎无法将数据放入表格中。开始 结束 日期 开始纬度 开始经度 结束纬度 结束经度 哈伍德 伯里 17/05/16 53.5984 -2.38731 53.59125 -2.29713 哈伍德 威根 17/05 /16 53.5984 -2.38731 53.54582 -2.63202 等等等等 - mystery man
@mysteryman - 请编辑您的问题并将数据放在那里。使用 dput(head(yourData)),因为这会为他人使用提供正确的数据结构。 - SymbolixAU

0

我使用“for循环”来解决这个问题,只需逐个绘制折线。 (对不起我的中文表达 ^_^) 例如:

for(i in 1:nrow(sz)){
     if(i<=nrow(sz) ){
      a <- as.numeric(c(sz[i,c(8,10)])); 
      b <- as.numeric(c(sz[i,c(9,11)]));
      A <- A %>% addPolylines(a,b,group=NULL,weight = 1,color = "brown",
                              stroke = TRUE,fill = NULL,opacity = 0.8)}

或者像更复杂的一个

for(j in 0:23){if(j<=23)
  #j--切每小时数据
  j1 <- as.character(paste(j,"点",sep='')) 
sz <- sz121[sz121$h==j,]
sz_4 <- sz121[sz121$bi_state==4 &sz121$h==j ,]
sz_8 <- sz121[sz121$bi_state==8&sz121$h==j,]
#还原A
A <- leaflet(sz121) %>% amap() %>% addLabelOnlyMarkers(~s_lon,~s_lat) %>% 
  addLegend(title=j1,colors=NULL,labels =NULL,position="topleft")
A <- A %>%addCircleMarkers(data=sz_8,~s_lon,~s_lat,color="orange",fill=TRUE,fillColor = "red", opacity = 1,fillOpacity=0.8,
                           weight =1,radius = 10) %>%addCircleMarkers(data=sz_4,~s_lon,~s_lat,color="black",fill=TRUE,fillColor = "red", 
                                                                      opacity = 1,fillOpacity=0.8,weight =5,radius = 10 ) %>% 
  addCircleMarkers(data=sz_8,~e_lon,~e_lat,color="orange",fill=TRUE,fillColor = "blue", opacity = 1,fillOpacity=0.8,weight=1,radius = 10) %>%
  addCircleMarkers(data=sz_4,~e_lon,~e_lat,color="black",fill=TRUE,fillColor = "blue", opacity = 1,fillOpacity=0.8,weight =5,radius = 10 ) 
for(i in 1:nrow(sz)){
  #i--画路径
  if(i<=nrow(sz) ){
    a <- as.numeric(c(sz[i,c(8,10)]));
    b <- as.numeric(c(sz[i,c(9,11)]));
    A <- A %>% addPolylines(a,b,group=NULL,weight = 1,color = "brown",stroke = TRUE,fill = NULL,opacity = 0.8)
  }
  if(i==nrow(sz)){print(A)}
}
Sys.sleep(3)
}

我不知道如何在没有警告的情况下正确地分享我的代码。 - 罗梅菲

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接