6

I can't get a leaflet map to render in my shiny app, although the code works by itself outside of shiny. I do not get any errors so I am stuck, any help is appreciated.

Sample Data:

cleanbuffalo <- data.frame(name = c("queen","toni","pepper"), 
                           longitude = c(31.8,32,33), 
                           latitude = c(-24,-25,-26))

Shiny UI:

vars <- c(
  "Pepper" = "pepper",
  "Queen" = "queen",
  "Toni" = "toni"
)

shinyUI(navbarPage("Buffalo Migration", id ="nav",

  tabPanel("Interactive Map",

div(class="outer",

    leafletOutput("map", width = "100%", height = "100%"),
    #Panel Selection
    absolutePanel(id = "controls", class = "panel panel-default", fixed = TRUE,
      draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto",
      width = 330, height = "auto",

      h2("Buffalo Migration"),
      #Buffalo Group selection
      checkboxGroupInput(
        "checkGroup", label = h3("Select Buffalo to Follow"),
        choices = vars,
        selected = 1)
          )
        )
      )
  )
)

Shiny Server:

library(shiny)
library(dplyr)
library(leaflet)
library(scales)
library(lattice)

shinyServer(function(input, output, session) {
  output$map <- renderLeaflet({
    leaflet() %>% addTiles() %>% setView(lng = 31.88, lat = -25.02, zoom=1)
  })
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
josh453
  • 308
  • 2
  • 12

1 Answers1

13

It doesn't work because of the height parameter in leafletOutput. Strangely, if you specify it in % the map doesn't show up, but if you use "px" (or a number which will be coerced to a string and have "px" appended) it does work fine.

leafletOutput("map", width = "75%", height = "500px") yields:

enter image description here

I don't know why this happens but if you wanted to specify the height of the leafletOutput in % you could wrap it into a div and give it the appropriate height.


By default the width is set to 100% and the height to 400px. So, you don't have to specify these parameters - I would do it only if I wanted to change the size of the output.

leafletOutput(outputId, width = "100%", height = 400)
Michal Majka
  • 5,332
  • 2
  • 29
  • 40
  • 1
    This solved my problem, thank you. I would have never guessed this to be the issue. – josh453 Aug 22 '16 at 18:33
  • 2
    The documentation in `?shiny::plotOutput` gives the reason: " Note that, for height, using "auto" or "100%" generally will not work as expected, because of how height is computed with HTML/CSS." – SymbolixAU Aug 22 '16 at 22:59
  • 1
    plus a couple of github issues [here](https://github.com/rstudio/shiny/issues/705) [and here](https://github.com/rstudio/shiny/issues/650), for example for further explanation – SymbolixAU Aug 22 '16 at 23:01
  • Could you give example how to wrap height in div paramiter to set it to 100%? – AAAA May 18 '22 at 11:49