19

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.

Thanks of any suggestions.

Bangyou
  • 9,462
  • 16
  • 62
  • 94
  • 1
    There is an underlying [JavaScript function called `getZoom`](http://leafletjs.com/reference.html#map-getzoom) that does exactly that, but I'm not quite sure how to access it. – alistaire Jan 25 '16 at 06:24
  • Thanks. I find it before, but not sure how to add js into shiny and access the value in R code. – Bangyou Jan 25 '16 at 06:27
  • There's `htnlwidgets::JS` or `v8::`, but I don't know what the leaflet object gets called in the JavaScript or how to get a function evaluated in that same environment. – alistaire Jan 25 '16 at 06:38

1 Answers1

19

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)
                })
        })
NicE
  • 21,165
  • 3
  • 51
  • 68