Search code examples
rshinyr-leaflet

Map doesn't load in shiny on start


I have the following little piece of code (more less as described HERE) - I want to control the number of points to be shown by a slider in shiny. You can see that the initial map is loaded after a little while (watch console output), but it will only show up after you used the slider once.

But I'd like the map to show up after it is created during launch of the shiny app - do you have any hints how to do that?

## app.R ##
library(shiny)
library(shinydashboard)
library(httr)
library(leafletR)

data(quakes)

# dest_dir=tempdir()
dest_dir="foo_map"

dest_file = paste(dest_dir,"quakes","quakes.html",sep="\\")


dat = quakes

createMapHTML <- function(inputFreq=1) {

  q.dat <- toGeoJSON(data=dat[seq(from = 1, to = nrow(dat), by=inputFreq), ], 
                     dest=dest_dir, name="quakes")
  
  sty <- styleSingle(col="darkblue", fill="darkblue", rad=6)
  
  # create map
  q.map <- leaflet(data=q.dat, dest=dest_dir,  size = c(1200, 600), incl.data=TRUE,
                   base.map=list("osm"), style=sty, popup="*", controls="all")
}

# createMapHTML()

runApp(list(
ui = dashboardPage(
  dashboardHeader(title = "quakes"),
  dashboardSidebar(
    sliderInput("slider", "#observations frequency:", 1, 100, 1)
  ),
  dashboardBody(
    htmlOutput("inc")
  )
),
server = function(input, output, session) {
  
  createMap <- reactive({
    createMapHTML(input$slider) 
    return(includeHTML(dest_file))
  })
 
  output$inc<-renderUI({ createMap() })
}
))

Solution

  • so the bottleneck with the leafletR package is the conversion to GeoJson. Additionally the "includeHTML & htmlOutput" workaround for embedding the html out is flaky..

    To avoid both I just switched to the leaflet packackage:

    ## app.R ##
    library(shiny)
    library(shinydashboard)
    library(leaflet)
    
    data(quakes)
    dat = quakes
    
    
    runApp(list(
      ui = dashboardPage(
        dashboardHeader(title = "quakes"),
        dashboardSidebar(
          sliderInput("slider", "#observations frequency:", 1, 100, 1)
        ),
        dashboardBody(
            leafletOutput("map", height = 600)
        )
      ),
      server = function(input, output) {
    
        output$map <- renderLeaflet({
    
          map <- leaflet() %>% addTiles()
    
          map %>% addCircles(data=dat[seq(from = 1, to = nrow(dat), by=input$slider), ],   #input$slider
                             lat = ~lat, lng = ~long, fillOpacity = 1.0)
        })
      }
    ))