Search code examples
rshinyr-leaflet

htmlwidget onRender function does not work in R Shiny


I'm trying to put a pulsing marker from a leaflet plugin on a Shiny App Map. It works very well on a basic R Studio Console, see here: Add a popup when clicked through to a 'plugin' pulsing marker in R Leaflet

But the following does not:

library(shiny)
library(leaflet)
library(htmltools)
library(htmlwidgets)

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%")
)

server <- function(input, output, session) {
  
  #js and css plugin files are stored locally, but you can access to them here :
# https://raw.githubusercontent.com/mapshakers/leaflet-icon-pulse/master/src/L.Icon.Pulse.js
# https://raw.githubusercontent.com/mapshakers/leaflet-icon-pulse/master/src/L.Icon.Pulse.css
  esriPlugin <- htmlDependency("leaflet-icon-pulse",version = "1.0",
                               src = "C:/HOME/",
                               script = "L.Icon.Pulse.js",stylesheet ="L.Icon.Pulse.css")
  
  registerPlugin <- function(map, plugin) {
    map$dependencies <- c(map$dependencies, list(plugin))
    map
  }

  output$map <- renderLeaflet({
    leaflet() %>% 
      addProviderTiles("CartoDB.DarkMatter") %>% setView(-122.4105513,37.78250256, zoom = 12) %>%
      registerPlugin(esriPlugin) %>%
      onRender("function(el,x) {
               var pulsingIcon = L.icon.pulse({iconSize:[5,5],color:'red',heartbeat:0.5});
               var pulsingIcon2 = L.icon.pulse({iconSize:[10,10],color:'orange',heartbeat:2});
               var marker = L.marker([37.78,-122.41],{icon: pulsingIcon}).bindPopup('<b>Hello world!</b><br>I am a popup.').openPopup().addTo(this);
               var marker = L.marker([37.75,-122.39],{icon: pulsingIcon2}).addTo(this);}")
  })
  
}

shinyApp(ui, server)

Does anyone see why it does not work?


Solution

  • This looks like indeed a bug in Shiny (or htmlwidgets), I created a reproducible example and filed an issue https://github.com/rstudio/shiny/issues/1389