Search code examples
rshinyr-leaflet

Prevent user from moving beyond boundaries


I have a map which shows Australia.

A map of Australia

What I want to do is to prevent the user going outside of this view. I know that I can pass providerTileOptions a minZoom and a bounds function, but this still enables the user to drag outside of this view (they'll just get blank grey).

How can I accomplish this?

Reproducible code:

library(shiny)
library(leaflet)



ui <- fluidPage(

    leafletOutput(
     "map",
     width = "100%",
     height = 500
    )
)


server <- function(input, output) {

    output$map <- renderLeaflet({
      leaflet() %>%
        addProviderTiles(providers$Esri.WorldGrayCanvas,
                         options = providerTileOptions(
                           minZoom = 4,
                           bounds = list(
                            c(-7.275292, 57.04102),
                            c(-43.45292, 221.1328)
                           )
                         )
                         ) %>%
        setView(134.4727, -25.87899, zoom = 4)
    })
}

shinyApp(ui = ui, server = server)

Solution

  • You can achieve this with setMaxBounds()

    leaflet() %>%
      addProviderTiles(providers$Esri.WorldGrayCanvas,
                       options = providerTileOptions(
                         minZoom = 4,
                         bounds = list(
                           c(-7.275292, 57.04102),
                           c(-43.45292, 221.1328)
                         )
                       )
      ) %>%
      setView(134.4727, -25.87899, zoom = 4) %>%
      setMaxBounds(57.04102, -7.275292, 221.1328, -43.45292)