Search code examples
rshinyr-leaflet

shiny leaflet display labels based on zoom level


I want to display my marker labels based on zoom level. Based on (https://rstudio.github.io/leaflet/shiny.html) I tried to use "input$MAPID_zoom". In my example, labels stored in location_name should be displayed when zoom level (mapscale) is lower to 6.

What I tried :

library(shiny)
library(leaflet)

 # my data
df <- data.frame(
  location_name = c('S1', 'S2'),
  lng = c(-1.554136,  -2.10401),
  lat = c(47.218637, 47.218637), 
  stringsAsFactors = FALSE)


# UI
 ui <- shinyUI(fluidPage(
  leafletOutput('map')

  ))

# server 

server <- shinyServer(function(input, output, session) {

  mapscale <-  observe({
    input$map_zoom   # get zoom level
  })


  output$map <- renderLeaflet({
    leaflet() %>%
    addTiles() %>% 
    addMarkers(data=df, lng = ~lng, lat = ~lat,
               label =~if(mapscale<6, location_name))
})

})

shinyApp(ui = ui, server = server)

Solution

  • A few remarks on your code if you like. If you wrap the zoom in a reactive function, reference it like mapscale(). Use the normal if statement in R and the ~ in front of the variable. Then you should be fine.

    Reproducible example:

    library(shiny)
    library(leaflet)
    
    df <- data.frame(
      location_name = c('S1', 'S2'),
      lng = c(-1.554136,  -2.10401),
      lat = c(47.218637, 47.218637), 
      stringsAsFactors = FALSE
    )
    
    
    ui <- shinyUI(
      fluidPage(
        leafletOutput(outputId = 'map')
      )
    )
    
    server <- shinyServer(function(input, output, session) {
    
      output$map <- renderLeaflet({
        leaflet() %>%
          addTiles()
      })
    
      observeEvent(
        eventExpr = input$map_zoom, {
          print(input$map_zoom)           # Display zoom level in the console
          leafletProxy(
            mapId = "map", 
            session = session
          ) %>% 
            clearMarkers() %>%
            addMarkers(
              data = df, 
              lng = ~lng,
              lat = ~lat,
              label = if(input$map_zoom < 6) ~location_name
          )
        }
      )
    
    
    })
    
    shinyApp(
      ui = ui, 
      server = server
    )