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.
getZoom
that does exactly that, but I'm not quite sure how to access it. – alistairehtnlwidgets::JS
orv8::
, 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