如何在R闪亮中添加两个不同的输入标记?

时间:2015-11-13 02:49:56

标签: r shiny leaflet

我正在尝试为两个不同的输入添加两个不同的标记。我得到了第一个工作但不是第二个工作。这是我的代码

ui.R

library(shiny)
library(leaflet)


shinyUI(fluidPage(


  # Application title
  titlePanel("Aspen GBS Population Structure results on map"),

  # Side bar layout
  sidebarLayout(
    sidebarPanel(
      selectInput("structure", label = "Select K for display", choices = c("2", "3", "4", "5", "6"), selected = "2"),
      checkboxInput("origin", label = "Flood path")),

      mainPanel(
    leafletOutput("map")
      )
    )
  )
)

server.R

leafIcons <- icons(
  iconUrl = ifelse(data_K2$FP_Icon == "greenleafIcon",
                   "http://leafletjs.com/docs/images/leaf-green.png",
                   "http://leafletjs.com/docs/images/leaf-red.png"
  ),
  iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/docs/images/leaf-shadow.png",
  shadowWidth = 50, shadowHeight = 64,
  shadowAnchorX = 4, shadowAnchorY = 62
)




library(shiny)


shinyServer(function(input, output, session) {
    dt <- reactive(
        switch(input$structure,
              "2" = data_K2$Structure.2,
              "3" = data_K2$Structure.3))

    output$map <- renderLeaflet(
      leaflet(data = data_K2) %>% addTiles() %>% setView(lng = -106.1039361,lat = 50.543981, zoom = 4) %>% 
      addCircleMarkers(lat = ~Lat, lng = ~Long, popup = ~Location_discription, radius=2, color = ~dt(), fill = TRUE) %>%
      addMarkers(lat = ~Lat, lng = ~Long, popup = ~Location_discription, icon = leafIcons)
    )
})

我希望仅在使用addMarkers按钮时激活checkboxInput。但是现在它默认被选中了。

1 个答案:

答案 0 :(得分:1)

我发现最简单的方法是使用组标记标记,然后在输入时显示/隐藏它们。这样你就节省了一些计算,并且传单设计用于使用leafletProxy(它在Rstudio指南中有详细记录)。您还需要添加一个更新地图的观察者,如本例所示,

library(shiny)
library(leaflet)

ui <- shinyUI(fluidPage(
    sidebarLayout(
        sidebarPanel(
            checkboxInput("show", "Show/Hide")
        ),
        mainPanel(
            leafletOutput("map")
        )
    )
))

dat <- data.frame(lng = rnorm(3, -106.1039361, 0.5) ,
                  lat = rnorm(3, 50.543981, 0.5))

server <- shinyServer(function(input, output, session) {

    ## Your map, give the markers groups
    output$map <- renderLeaflet(
        leaflet(data = dat) %>% 
        addTiles() %>% setView(lng = -106.1039361,lat = 50.543981, zoom = 4) %>% 
        addCircleMarkers(group="circles",
                         popup = ~paste(lat), radius=2, fill = TRUE) %>%
        addMarkers(group="markers")
    )

    ## Observer to update map on input
    observeEvent(input$show, {
        proxy <- leafletProxy('map')
        if (input$show) proxy %>% showGroup('markers')
        else proxy %>% hideGroup('markers')
    })
})

shinyApp(ui, server)