基于动态selectInput的传单地图缩放

时间:2018-10-31 19:16:52

标签: r shiny shinydashboard reactive r-leaflet

这是一个虚拟数据帧DF

Location <- c("A","B","C","D","E")
OwnBicycle <- c("Yes","Yes","Yes","No","No")
Latitude <- c(-0.091702,-3.218834,-2.856487,-1.300799,0.498922)
Longitude <- c(34.767958,40.116147,38.945562,36.785946,35.308054)
DF <- data.frame(Location,OwnBicycle,Latitude,Longitude)

loc <- unique(DF$Location)
ownbike <- unique(DF$OwnBicycle)

UI上主要代码的一部分。

selectInput("loc", label = "Location", choices=loc, selected = "A")
leafletOutput("mymap", height = 500)

服务器

# reactive for selectIpout
filtered <- reactive({
  DF[DF$Location == input$loc,]
})

#leafletProxy 
observe(leafletProxy("mymap", data = filtered()) %>%
          clearMarkers()%>%
          addMarkers(radius =3)
)

在“发光”仪表板上的leafletObserver中,当用户从selectInput中选择选项B时,我希望地图放大到位置B。我尝试了以下突出显示的步骤here,但是为此,它具有一个已初始化纬度/经度的按钮?

1 个答案:

答案 0 :(得分:0)

您需要将flyToleafletProxy一起使用。您可以根据需要调整zoom参数。我对您的代码做了一些改进,因此它与您的代码略有不同。 -

library(shiny)
library(leaflet)

shinyApp(
  ui = fluidPage(
    selectInput("loc", label = "Location", choices=loc, selected = "A"),
    leafletOutput("mymap", height = 500)
  ),
  server = function(input, output) {
    filtered <- reactive({
      DF[DF$Location == input$loc,]
    })

    output$mymap <- renderLeaflet({
      leaflet() %>% addTiles()
    })

    mymap_proxy <- leafletProxy("mymap")

    observe({
      fdata <- filtered()
      mymap_proxy %>%
        clearMarkers() %>%
        addMarkers(lng = fdata$Longitude, lat = fdata$Latitude) %>%
        flyTo(lng = fdata$Longitude, lat = fdata$Latitude, zoom = 10)
    })
  }
)