使用复选框添加标记

问题描述 投票:0回答:1

如果用户勾选了复选框,我会尝试在交互式传单地图上添加标记。但是,我无法让复选框外观在 renderLeaflet 函数中工作,但可以在 renderPlot 函数中工作。

我的代码有效,如下所示:

ui <- fluidPage(

  sidebarLayout(
    sidebarPanel(
    checkboxInput('check1','Show Counties', value = TRUE)),

  mainPanel(
    # I'm aware that this should be changed to leaftletOutput, when used 
    # with the in the second code snippet below
    plotOutput("mymap")

  ),

  position = 'right'

  )

)

server <- function(input, output) {

  output$mymap <- renderPlot({

    if (input$check1){
      hist(rnorm(10))
    } else {
      hist(rnorm(100))
    }

  })

 }

shinyApp(ui = ui, server = server)

相同的逻辑在 Leaflet 中不起作用,我非常感谢有关如何修改以下代码的输入。我知道您无权访问两个变量,USstatescoor,但我希望有人能够指出错误,可能是语法错误。输出函数如下所示;

output$mymap <- renderLeaflet({

  if (input$check1 == TRUE){
    leaflet(USstates) %>%
      addTiles() %>%
      addPolygons(color = 'navy',
                  opacity = 1.0,
                  weight = 1) %>%
      addMarkers(lng = coor[,1],lat = coor[,2])
  } else {
    leaflet(USstates) %>%
      addTiles() %>%
      addPolygons(color = 'navy',
                  opacity = 1.0,
                  weight = 1)
  }

})
r shiny r-leaflet
1个回答
0
投票

我在创建这篇文章后就想出了一个解决方案。解决方案是将传单代码包装在反应函数中,并在 renderLeaflet 函数中调用该函数。解决办法如下:

server <- function(input, output) {
  display <- reactive({
    if (input$check1){
      leaflet(USstates) %>%
        addTiles() %>%
        addPolygons(color = 'navy',
                    opacity = 1.0,
                    weight = 1) %>%
        addMarkers(lng = coor[,1],lat = coor[,2])
    } else {
      leaflet(USstates) %>%
        addTiles() %>%
        addPolygons(color = 'navy',
                    opacity = 1.0,
                    weight = 1)
    }
  })

  output$mymap <- renderLeaflet({
    display()
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.