Search code examples
rshinyr-leaflet

Zoom leaflet map to default


Is there anyway to add a layer control or button to reset map and go back the initial position. For example, when in the you are exploring a map and zooming in, and then you want to zoom out to get back to the initial stage.

library(shiny)
library(leaflet)

ui <- fluidPage(
  leafletOutput("mymap")

)

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

outline <- quakes[chull(quakes$long, quakes$lat),]

output$mymap <- renderLeaflet({ leaflet(quakes) %>%
  # Base groups
  addTiles(group = "OSM (default)") %>%
  addProviderTiles("Stamen.Toner", group = "Toner") %>%
  addProviderTiles("Stamen.TonerLite", group = "Toner Lite") %>%
  # Overlay groups
  addCircles(~long, ~lat, ~10^mag/5, stroke = F, group = "Quakes") %>%
  addPolygons(data = outline, lng = ~long, lat = ~lat,
              fill = F, weight = 2, color = "#FFFFCC", group = "Outline") %>%
  # Layers control
  addLayersControl(
    baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
    overlayGroups = c("Quakes", "Outline"),
    options = layersControlOptions(collapsed = FALSE)
    )

  })
}

shinyApp(ui, server)

Solution

  • You can do this without any javascript code by using the leafletProxy and the setView functions to change the map when the a button is clicked.

    Here's an example:

    library(shiny)
    library(leaflet)
    
    ui <- fluidPage(
      leafletOutput("mymap"),
      actionButton("reset_button", "Reset view")
    
    )
    
    server <- function(input, output, session) {
      initial_lat = -23.079
      initial_lng = 178.15
      initial_zoom = 4
    
      output$mymap <- renderLeaflet({ leaflet(quakes) %>% 
                                        setView(lat = initial_lat, lng = initial_lng, zoom = initial_zoom) %>%
                                        addTiles(group = "OSM (default)") %>%
                                        addProviderTiles("Stamen.Toner", group = "Toner") %>%
                                        addProviderTiles("Stamen.TonerLite", group = "Toner Lite")})                                 
    
    
      observe({
        input$reset_button
        leafletProxy("mymap") %>% setView(lat = initial_lat, lng = initial_lng, zoom = initial_zoom)
      })
    }
    
    shinyApp(ui, server)