Search code examples
rshinyr-leaflet

How to get the zoom level from the leaflet map?


I create a map using leaflet package in Shiny which have a selectInput to allow user to select from a site list. The site list also adds into leaflet as markers.

When user selects a new site, I want to recenter map into the selected site without change the zoom level. The setView function can be called to set center points, but has to specify the zoom level.

Is it possible to get the zoom level of leaflet map which can be used in the setView function?

This is a minimum example to play with my question with reset zoom level.

library(shiny)
library(leaflet)

df <- data.frame(
    site = c('S1', 'S2'),
    lng = c(140, 120),
    lat = c(-20, -30), 
    stringsAsFactors = FALSE)

# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
    selectInput('site', 'Site', df$site),
    leafletOutput('map')
  
))

server <- shinyServer(function(input, output, session) {
    
    output$map <- renderLeaflet({
        leaflet() %>%
            addTiles() %>% 
            setView(lng = 133, lat = -25,  zoom = 4) %>% 
            addMarkers(lng = df$lng, lat = df$lat)
    })
    
    observe({
        req(input$site)
        sel_site <- df[df$site == input$site,]
        isolate({
            leafletProxy('map') %>%
                setView(lng = sel_site$lng, lat = sel_site$lat, zoom = 4)
        })
    })
})

shinyApp(ui = ui, server = server)

PS: when you play with these codes, please adjust zoom level before selecting a new site.


Solution

  • You can access the zoom level using input$mapid_zoom (see here).

    In your observe, you could do:

     observe({
                    sel_site <- df[df$site == input$site,]
                    isolate({
                            new_zoom <- 4
                            if(!is.null(input$map_zoom)) new_zoom <- input$map_zoom
                            leafletProxy('map') %>%
                                    setView(lng = sel_site$lng, lat = sel_site$lat, zoom = new_zoom)
                    })
            })