首页 > 解决方案 > 使用复选框 Leaflet/R 添加标记

问题描述

如果用户勾选复选框,我正在尝试在我的交互式传单地图上添加标记。但是,我无法让复选框外观在 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)
  }

})

标签: rshinyleaflet

解决方案


I came up with a solution, of cause right after I created this post. The solution was to wrap the leaflet code in a reactive function and call that one in the renderLeaflet function. The solution is as follows:

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

推荐阅读