rshinyshinydashboardr-leafletbs4dash

Leaflet map in bs4Dash's box


Recently, when working on a shiny dashboard, I encountered an issue of Leaflet map not working (seemingly) correctly with bs4Dash box. Seems that after the box is maximized, leaflet map is not updating to reflect the new container width.

Map after maximizing the box

I think this is a similar issue to this one: rstudio/leaflet#248. Tried a solution provided by Joe Cheng, but couldn't make it work (I'm not good at Javascript unfortunately). Is there any workaround to get the map to render full screen after maximizing the box?

Reproducible example:

library(shiny)
library(bs4Dash)
library(leaflet)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    box(
      title = "Map",
      collapsible = TRUE,
      height = "80vh",
      width = 6,
      maximizable = TRUE,
      leafletOutput("map1", height = "100%")
    )
  )
)

server <- function(input, output, session) {
  output$map1 <- renderLeaflet({
    leaflet() %>% 
      setView(19.08, 60.25, zoom = 4) %>% 
      addTiles()
  })
  
}

shinyApp(ui, server)

Solution

  • You can define a id for the box and then updateBox on the server side to change the width. Try this

    library(shiny)
    library(bs4Dash)
    library(leaflet)
    
    ui <- dashboardPage(
      dashboardHeader(),
      dashboardSidebar(),
      dashboardBody(
        bs4Dash::box(
          id = "mybox", 
          title = "Map",
          collapsible = TRUE,
          height = "80vh",
          width = 6,
          maximizable = TRUE,
          leafletOutput("map1", height = "100%")
        )
      )
    )
    
    server <- function(input, output, session) {
      output$map1 <- renderLeaflet({
        leaflet() %>% 
          setView(19.08, 60.25, zoom = 4) %>% 
          addTiles()
      })
      
      observeEvent(input$mybox$maximized, {
        if (input$mybox$maximized){
          mywidth = 12
        } else mywidth = 6
        updateBox(
          "mybox",
          action = "update",
          options = list(
            width = mywidth
          )
        )
      })
      
    }
    
    shinyApp(ui, server)