简体   繁体   中英

Shiny+leaflet: How to let addMarkers depend on user input

I want to let the user choose if certain markers are plotted on a Leaflet map. This depends on input$competitorchoice, which can be TRUE or FALSE. I want certain markers to be plotted only when this value is TRUE. I would use an if clause and addMarkers within this if, but this does not work...

Example code can be seen below:

output$mymap<-renderLeaflet({
  leaflet(data=get(paste(input$type,".locations",sep = ""))[[input$stations]])  %>%
  addMarkers(~lon, ~lat,data=terminals,icon=termi,popup = ~name_terminal))

Hereafter, I want to add a conditional addMarkers.It is only called when input$competitorchoice is TRUE...

Since you didn't provide a reproducible example, I based this off the Leaflet tutorial dataset. One approach is to have a checkbox input that is reactive. Here is my attempt, where markers can be enabled/disabled by clicking the box.

library(shiny)
library(leaflet)

ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  # Add checkboxInput() to turn markers on and off:
  checkboxInput("markers", "Turn On Markers", FALSE)
)

server <- function(input, output, session) {
  # Some random data:
  dat <- data.frame(long = rnorm(40) * 2 + 13, lat = rnorm(40) + 48)

  # observe() looks for changes in input$markers and adds/removes
  # markers as necessary:
  observe({
    proxy <- leafletProxy("mymap", data = dat)
    proxy %>% clearMarkers()
    if (input$markers) {
      proxy %>% addMarkers()
    }
  })

  # Render basic map with any element that will not change.
  # Note: you can change the starting zoom/positioning/et cetera
  # as appropriate:
  output$mymap <- renderLeaflet({
    leaflet(dat) %>% addProviderTiles("Stamen.TonerLite", options = providerTileOptions(noWrap = TRUE))
  })
}

shinyApp(ui, server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM