shiny leaflet display labels based on zoom level

前端 未结 1 659
猫巷女王i
猫巷女王i 2021-01-23 07:10

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

相关标签:
1条回答
  • 2021-01-23 07:44

    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
    )
    
    0 讨论(0)
提交回复
热议问题