Search code examples
rshinyr-leaflet

Gap when conditional map not displayed


I am producing a Shiny interactive document. I wish to give the user the option of displaying a map conditional on checkbox status, and that map has some reactive content. I am able to achieve this, but not without the space that the map occupies remaining when it is not displayed. I believe this is also true of a plot instead of a map.

Is it possible to have the map's absence leave no gap?

---
title: "Conditional Map"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE, results='hide'}
knitr::opts_chunk$set(echo = FALSE)
library(leaflet)
library(shiny)
```

The map should be present based upon the condition of the checkbox:

```{r}
# coordinates for markers:
Coords = list("London"=c(0,51), "New York" = c(-74,40))

selectInput(inputId = "Loc",label = "Select location", choices = names(Coords))

checkboxInput(inputId = "ShowMap", label="Show map?", value=TRUE)

leafletOutput("Map")

output$Map = renderLeaflet({if(input$ShowMap) leaflet() %>% addTiles %>% 
setView(-45,45,zoom=2) %>%
addMarkers(lng=Coords[[input$Loc]][1],lat=Coords[[input$Loc]][2])})

```

## The Next Bit

Some additional content here which should appear directly below the previous content, whether that is the map or the checkbox.

Solution

  • Use conditional panel like so:

    conditionalPanel(condition = "input.ShowMap == true", 
    leafletOutput("Map"))