Search code examples
rshinyr-leaflet

How to dynamically change the size of leaflet map?


I want to know, how can we change the size of leaflet map in shiny R. For example consider the following code:

library(leaflet)
library(shiny)

app = shinyApp(
  ui = fluidPage(
    sidebarLayout(
      sidebarPanel( sliderInput("obs",
                    "Number of observations:",
                    min = 0,
                    max = 1000,
                    value = 500)
        ),
      mainPanel(
        leafletOutput('myMap', width = "200%", height = 1400)
        )
    )
  ),
  server = function(input, output) {
    map = leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 17)
    output$myMap = renderLeaflet(map)
  }
)

if (interactive()) print(app)

For changing the size of map, I can change the width and height argument in ui. When I tried to change the same in server, it did not work out.

I do not know, any way in which one can change the parameters in ui through server. I tried this approach, but it did not work.

library(leaflet)
library(shiny)

Height = 1000 
app = shinyApp(
  ui = fluidPage(
    sidebarLayout(
      sidebarPanel( sliderInput("Height",
                    "Height in Pixels:",
                    min = 100,
                    max = 2000,
                    value = 500)
        ),
      mainPanel(
        leafletOutput('myMap', width = "200%", height = Height)
        )
    )
  ),
  server = function(input, output) {
    Height <- reactive(input$Height)
    map = leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 17)
    output$myMap = renderLeaflet(map)
  }
)

if (interactive()) print(app)

I just want to know, how to make the size of map dynamic so that I can control it.


Solution

  • You need to render leafletOutput on server side like

    app = shinyApp(
      ui = fluidPage(
        sidebarLayout(
          sidebarPanel( sliderInput("Height",
                                    "Height in Pixels:",
                                    min = 100,
                                    max = 2000,
                                    value = 500)
          ),
    
          mainPanel(
            uiOutput("leaf")
    
          )
        )
      ),
      server = function(input, output) {
        output$leaf=renderUI({
          leafletOutput('myMap', width = "200%", height = input$Height)
        })
    
        output$myMap = renderLeaflet(leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 17))
      }
    )