Reputation: 35
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...
Upvotes: 0
Views: 1617
Reputation: 1246
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)
Upvotes: 2