Is there a way to enable mouse wheel zoom only after first click on map.
I have the following code in which I want to zoom the map only after click on the map. Is there a way to do that in shiny?
library(shiny)
library(leaflet)
library(maps)
ui <- fluidPage(
leafletOutput("CountryMap", width = 1000, height = 500)
)
server <- function(input, output){
Country = map("world", fill = TRUE, plot = FALSE, regions="USA", exact=TRUE)
output$CountryMap <- renderLeaflet({
leaflet(Country) %>% addTiles() %>%
fitBounds(Country$range[1], Country$range[3], Country$range[2], Country$range[4])%>%
addPolygons(fillOpacity = 0.6, smoothFactor = 0.5, stroke = TRUE, weight = 1)
})
}
shinyApp(ui =ui, server = server)
R Leaflet package does not have the option to disable zoomControl
or mouseWheelControl
yet according to this https://github.com/rstudio/leaflet/issues/179, but inspired by Yihui's suggestion from the link, here is a workaround that dynamically changes the maxZoom
level depending on mouse click event.
library(shiny)
library(leaflet)
library(maps)
ui <- fluidPage(
leafletOutput("CountryMap", width = 1000, height = 500)
)
server <- function(input, output){
Country = map("world", fill = TRUE, plot = FALSE, regions="USA", exact=TRUE)
# Add a default minZoom and maxZoom of the same value so that the map does not zoom
output$CountryMap <- renderLeaflet({
leaflet(Country) %>% addTiles(options=tileOptions(minZoom=4, maxZoom=4)) %>%
fitBounds(Country$range[1], Country$range[3], Country$range[2], Country$range[4]) %>%
addPolygons(fillOpacity = 0.6, smoothFactor = 0.5, stroke = TRUE, weight = 1)
})
# Change a reactive value depending on mouse click
zoom <- reactiveValues(level=4)
# This records mouse clicks outside polygons
observeEvent(input$CountryMap_click, {
zoom$level = 20
})
# This records mouse clicks inside polygons
observeEvent(input$CountryMap_shape_click, {
zoom$level = 20
})
# Change zoom level of the map
observe({
if (zoom$level == 20) {
leafletProxy("CountryMap") %>% clearTiles() %>%
addTiles(options=tileOptions(minZoom=4, maxZoom=20))
}
})
}
shinyApp(ui =ui, server = server)