Search code examples
javascriptrshinyr-leaflet

Problems scaling map


I can't have "full screen" map in my shiny app, because when I used "100%" parameter, the map disappears...

ui <- fluidPage(
  leafletOutput("mymap", height = "100%", width = "100%"),

But when I do this

ui <- fluidPage(
  leafletOutput("mymap"),

there is no problems, but there is a half with map and a half in blank. And I need it to be full screen

I tried

leafletOutput("mymap", height = 800, width = 1300)

But it is not what I need, because it didn't scale to the window, that's why I prefer the "100%" parameter.


Solution

  • Well I guess with 100% height you mean "fit to screen/window"?

    jscode <- '
    $(document).on("shiny:connected", function(e) {
    var jsHeight = window.innerHeight;
    Shiny.onInputChange("GetScreenHeight",jsHeight);
    });
    '
    
    
    library(shiny)
    library(leaflet)
    
    r_colors <- rgb(t(col2rgb(colors()) / 255))
    names(r_colors) <- colors()
    
    ui <- fluidPage(
      p(),
      tags$script(jscode),
      uiOutput("leafl"),
      actionButton("recalc", "New points")
    )
    
    server <- function(input, output, session) {
    
      points <- eventReactive(input$recalc, {
        cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
      }, ignoreNULL = FALSE)
    
      output$mymap <- renderLeaflet({
        leaflet() %>%
          addProviderTiles("Stamen.TonerLite",
                           options = providerTileOptions(noWrap = TRUE)
          ) %>%
          addMarkers(data = points())
      })
    
      output$leafl <- renderUI({
        if(!is.null(input$GetScreenHeight)){
          width  <- session$clientData$output_image1_width
          print(session$clientData)
          height <- session$clientData$output_image1_height
          leafletOutput("mymap", width = "100%", height = input$GetScreenHeight)
        }
      })
    }
    
    shinyApp(ui, server)