Search code examples
rshinyr-leaflet

How to to make leaflet render when switching menuItems?


A basic R Shiny 'dashboard' app with 2 sidebar menu items, one containing a Leaflet widget output.

The error to reproduce is -

  1. Run this code from R Studio (make sure your R Studio IDE is maximized to the screen).
  2. Maximize the runtime window.
  3. Switch to the blank menu item tab.
  4. Make the window smaller, maximize the window.
  5. Switch back to the original menu item tab with the Leaflet widget.

If the error has been reproduced, the map will not be fully rendered, leaving a bunch of blank space. This can only be fixed by minimizing and maximizing the window again.

library(leaflet)
library(magrittr)
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Dashboard", tabName = "dashboard"),
      menuItem("blankMenuItem", tabName = "blank")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "dashboard",
              leafletOutput("map")),
  
      tabItem(tabName = "blank")
    )
  )
)

server <- function(input, output) { 

  output$map <- renderLeaflet({

    leaflet() %>%
      addTiles() %>%  # Add default OpenStreetMap map tiles
      addMarkers(lng = 174.768, lat = -36.852, popup="The birthplace of R") 

  })
  }

shinyApp(ui, server)

enter image description here enter image description here enter image description here enter image description here enter image description here

Do you have any idea why this behavior occurs?


Solution

  • Was able to make it resize after viewing a semi-related issue here. This work around affects all sidebar menu items, fixes the non-rendering leaflet. A resize event is used that does not require the user to physically resize the window.

    Inside dashboardBody():

    shiny::includeScript("mapresize.js")
    

    mapresize.js contents:

    $(document).on('click', '.sidebar-menu li', function() {
        window.dispatchEvent(new Event("resize"));
    });