Search code examples
rshinyr-leaflet

Remove zoom controls from rendered leaflet map in Shiny


Leaflet provides an option, when setting up your map, to hide the zoom controls

leaflet(options = leafletOptions(zoomControl = FALSE)

However, I would like to call this option after having already created a map so that a user can download the map without the zoom controls and without me having to re-create a different version of the map from scratch.

Here's a simple version of my app at the moment:

library(shiny)
library(tidyverse)
library(leaflet)
library(mapview)

ui <- fluidPage(
  fluidPage(
    leafletOutput(outputId = "map"),
    downloadButton(outputId = "save")
  )
)

server <- function(input, output, session) {

  map <- reactive({
    leaflet() %>%
      addTiles()
  })

  output$map <- renderLeaflet({
    map()
  })

  output$save <- downloadHandler(
    filename = "map.jpeg",
    content = function(file){
      latRng <- range(input$map_bounds$north,
                      input$map_bounds$south)
      lngRng <- range(input$map_bounds$east,
                      input$map_bounds$west)
      map() %>%
        setView(lng = (lngRng[1] + lngRng[2])/2,
                lat = (latRng[1] + latRng[1])/2,
                zoom = input$map_zoom) %>%
        ### HERE ###
        mapshot(file = file)
    }
  )

}

shinyApp(ui, server)

I'd like to be able to add a line of code where I've commented ### HERE ### that would turn off zoom controls. In my actual code the displayed map is really complex with lots of options and I wouldn't want to have all that code twice just for the sake of removing zoom controls in the initial call to leaflet().


Solution

  • You can do it like so:

    library(shiny)
    library(tidyverse)
    library(leaflet)
    library(mapview)
    
    ui <- fluidPage(
      fluidPage(
        leafletOutput(outputId = "map"),
        downloadButton(outputId = "save")
      )
    )
    
    server <- function(input, output, session) {
    
      map <- reactive({
        leaflet() %>%
          addTiles()
      })
    
      output$map <- renderLeaflet({
        map()
      })
    
      output$save <- downloadHandler(
        filename = "map.jpeg",
        content = function(file){
          latRng <- range(input$map_bounds$north,
                          input$map_bounds$south)
          lngRng <- range(input$map_bounds$east,
                          input$map_bounds$west)
          m = map() %>%
            setView(lng = (lngRng[1] + lngRng[2])/2,
                    lat = (latRng[1] + latRng[1])/2,
                    zoom = input$map_zoom)
          m$x$options = append(m$x$options, list("zoomControl" = FALSE))
          mapshot(m, file = file)
        }
      )
    
    }
    
    shinyApp(ui, server)
    

    which is updating the leaflet options after map creation. I will incorporate this in the mapshot function to optionally remove the zoomControl.