3

Is it possible to retrieve a leaflet map in Shiny after it's already been rendered?

Here is an example in code that shows how a map generated by leaflet() is different from one that is returned from leafletProxy() even though they would appear the exact same when rendered. Is there a function maybe different from leafletProxy() to get the actual htmlwidget object?

library(shiny)
library(leaflet)

m1 <- leaflet() %>% addTiles()

shinyApp(
  ui = fluidPage(
    textOutput("test"),
    br(),
    leafletOutput("mymap")
  ),
  server = function(input, output, session) {
    output$mymap <- renderLeaflet({
      leaflet() %>% addTiles()
    })
    output$test <- renderText({
      sprintf("Are the two maps the same?: %s", 
              identical(m1, leafletProxy("mymap")))
    })
  }
)

Reasoning: The reason that I would like the actual rendered object is that I have a Shiny application where the map is updated multiple times using leafletProxy() and then it needs to be downloaded to an HTML file. The problem is saveWidget, webshot, mapshot and other functions need the actual map object, not the proxy version in order to save. This question has been posted multiple times in a few different ways, but the only viable solution is to create two maps side-by-side: one that's updated via leafletProxy() and another that's built directly on top of the call to leaflet(). I would rather not maintain two different maps.

Potential Duplicate Questions

Disclaimer I have cross-posted this question as an issue to the manipulateWidget package since it seems like the most promising area where already rendered objects in Shiny can be retrieved. https://github.com/rte-antares-rpackage/manipulateWidget/issues/59

Steven M. Mortimer
  • 1,618
  • 14
  • 36
  • thanks for this question, this is exactly my problem. I have considered maintaining a second map, but I cannot figure out how to copy the first maps settings with the leafletProxy modifications to the 2nd one – user670186 Mar 15 '19 at 23:05
  • @user670186 If you want to maintain two maps follow the example above. Anytime you update the rendered map by using leafletProxy you must run the same exact code against the initially declared map that is not being rendered. That will ensure the two objects are the same thing. – Steven M. Mortimer Mar 22 '19 at 23:39
  • thanks, yes i was considering this, but maintaining 2 maps doesnt feel like the most elegant solution. Instead what it did was creating R list objects and store all infos about my additional layers and draws in there before applying the leafletProxy. Then I found out that I can just output a leaflet() object in Rmarkdown. So I was able to call leaflet() and add all the layers and drawings from the R list object. This felt a bit more elegant, more performant and better UX. – user670186 Mar 24 '19 at 15:36

0 Answers0