Search code examples
rshinyr-leaflet

R shiny import leaflet html widget object


I have a leaflet plot that was exported as a .rds file. How can I now output this plot in a shiny app? Minimal example code below of what I have tried which currently gives "Warning: Error in FUN: argument is not a character vector [No stack trace available]"

library(shiny)
shinyUI<-fluidPage(mainPanel(
uiOutput("test")
)
)
shinyServer<-function(input,output){
output$test<-renderUI(readRDS("./Plots/LeafletPlot.rds"))
}
shinyApp(shinyUI,shinyServer)

Note that I have also tried to use renderLeaflet and leafletOutput but to no avail. running readRDS("./Plots/LeafletPlot.rds") from the console does load the leaflet map without issue.


Solution

  • # Create your object 
    library(leaflet)
    
    map <- leaflet::leaflet() %>%
      leaflet::addProviderTiles(providers$OpenStreetMap)
    
    saveRDS(object = map, file = "map.rds")
    
    # Read it at the beginning
    
    map2 <- readRDS("map.rds")
    
    library(shiny)
    shinyUI<-fluidPage(mainPanel(
      leafletOutput("test")
     )
    )
    
    shinyServer<-function(input,output){
      output$test<-renderLeaflet(map2)
    }
    
    shinyApp(shinyUI,shinyServer)