trafficonese / leaflet.extras

Extra functionality for leaflet R package.
https://trafficonese.github.io/leaflet.extras/
GNU General Public License v3.0
213 stars 74 forks source link

AddWMSLegend does not work with Observe or ObserveEvent #155

Closed richardtc closed 5 months ago

richardtc commented 6 years ago

I'm trying to insert a GeoServer WMS legend into Leaflet in Shiny as follows, but the legend does not render within an Observe or ObserveEvent function. Note that the legend does display in the map if not placed within an Observe or ObserveEvent. I'd be grateful to learn how to make this work. Thanks in advance, Richard

Example code: `observe({ if(input$srtm_sl != 0){ proxy <- leafletProxy("map") proxy %>% addWMSLegend( uri = "http://11.11.1111.11:8080/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.1.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=ta9191:srtm_sl&legend_options=fontName:Times%20New%20Roman;fontAntiAliasing:true;fontColor:0x000033;fontSize:12;bgColor:0xFFFFEE;dpi:91&SCALE=1001", position = "bottomleft", layerId = "legend" )

} }) `

Lavoiec commented 4 years ago

I ran into this problem again. I don't know if you found a way to fix the issue, but a workaround is to use addControl from base leaflet.

Looking at the source code, addWMSLegend() uses html::onRender(), which doesn't occur when using leafletProxy.

So something like what you're trying seems like it would not work with leafletProxy. When you were using it outside of ObserveEvent, did you still use leafletProxy ?

Instead, I'm using something like

proxy %>% addControl(paste0("<img src=",image_url, ">"),position = "topright")

where image_url is the link to the GetLegendGraphic

trafficonese commented 6 months ago

reprex:

library(shiny)  
library(leaflet)
library(leaflet.extras)

ui <- fluidPage(
  checkboxInput("showlegend", "Show Legend", FALSE),
  leafletOutput("map")
)

server <- function(input, output, session) {
  output$map <- renderLeaflet({
    leaflet() %>% 
      addTiles() %>%
      setView(11, 51, 6) %>% 
      addWMSTiles(
        baseUrl = "https://www.wms.nrw.de/wms/unfallatlas?request=GetMap",
        layers = c("Unfallorte","Personenschaden_5000","Personenschaden_250"),
        options = WMSTileOptions(format = "image/png", transparent = TRUE)
      )
  })
  observeEvent(input$showlegend, {
    leafletProxy("map") %>% 
      addWMSLegend(
        uri = paste0(
          "https://www.wms.nrw.de/wms/unfallatlas?request=GetLegendGraphic%26version=1.3.0%26format=image/png%26layer=Personenschaden_5000"
        )
      )
  })
}
shinyApp(ui, server)