h.l.m
h.l.m

Reputation: 13475

How to add an htmlwidget to a popup of a leaflet object?

I am using R to combine a leaflet object and an dygraph.

In particular I would like a dygraph (and ideally any htmlwidget) to appear as the popup to points on a map.

below is the code I am roughly trying to produce.

Ideally when the user clicks on the marker, the dygraph should appear in the popup.

  # example dygraph
  library(dygraphs)
  lungDeaths <- cbind(mdeaths, fdeaths)
  dygraph(lungDeaths)
  dd <- .Last.value

  # example leaflet map
  library(leaflet)
  leaflet() %>%
    addTiles() %>% 
    addMarkers(lng=174.768, lat=-36.852, 
               popup="The birthplace of R")
  ll <- .Last.value

  # I would like to be able to incorporate the dygraph as the popup,
  # however the below doesn't work.
  ll %>% addMarkers(lng=174.769, lat=-36.853,
                    popup=dd)


  # the end goal is to have this combined in a shiny output
  # below is a rough skeleton to add what I would expect to code
  # in order to be able to add the dygraph into the popup
  library(shiny)
  library(leaflet)
  library(dygraphs)

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

  server <- function(input, output, session) {

    output$mymap <- renderLeaflet({
      leaflet() %>%
        addTiles() %>% 
        addMarkers(lng=174.768, lat=-36.852, 
                   popup=dygraph(lungDeaths))

    })
  }

  shinyApp(ui, server)

Upvotes: 1

Views: 1090

Answers (1)

TimSalabim
TimSalabim

Reputation: 5844

This can be done using mapview::popupGraph which allows to include static as well as htmlwidgets based graphs in popups. The relevant line in your example to change is:

ll %>% addMarkers(lng=174.769, lat=-36.853,
                  popup=mapview::popupGraph(dd, type = "html"))

Note, theses html popups are embedded via an iframe, so there may be some unexpected behaviour especially when there is not enough space. With the github version of leaflet you can change the size of the popup to suit your needs. The CRAN version allows only 300px in width (if I am not mistaken).

Upvotes: 4

Related Questions