0
votes

I'm trying to add markers on my interactive Leaflet map if the user ticks off a checkbox. However, I can't get the checkbox-appearance to work within the renderLeaflet function, but I can within a renderPlot function.

My code, that works, looks as below:

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)

The same logic doesn't work within Leaflet, and I would highly appreciate input on how to modify the below code. I know you don't have access to the two variables, USstates or coor, but I was hoping one could point the error, potentially in terms a syntax error. The output function looks as follows;

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

})
1

1 Answers

0
votes

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