r-spatial / leafem

leaflet extensions for mapview
https://r-spatial.github.io/leafem/
Other
108 stars 29 forks source link

How to remove GeoRaster when using shiny/leafletproxy? #56

Open jzadra opened 2 years ago

jzadra commented 2 years ago

As stated in the title, I need to be able to remove a GeoRaster and replace it with a different one in a shiny app. Is there a way to do this?

trafficonese commented 5 months ago

The leaflet methods hideGroup/showGroup/clearGroup should work. Here is an example:

library(shiny)  
library(leaflet)
library(leafem)

tif = system.file("tif/L7_ETMs.tif", package = "stars")
x1 = read_stars(tif)
x1_b3 = x1[, , , 3] # band 3

ui <- fluidPage(
  actionButton("hide", "Hide Group"),
  actionButton("show", "Show Group"),
  actionButton("clea", "Remove Group"),
  actionButton("add1", "Add new Group"),
  leafletOutput("map")
)

server <- function(input, output, session) {
  output$map <- renderLeaflet({
      leaflet() %>%
        addTiles() %>%
        leafem:::addGeoRaster(
          x1_b3
          , opacity = 1
          , group = "initial"
          , colorOptions = colorOptions(
            palette = grey.colors(256)
          )
        )
  })
  observeEvent(input$hide, {
    leafletProxy("map") %>% 
      hideGroup("initial")
  })
  observeEvent(input$show, {
    leafletProxy("map") %>% 
      showGroup("initial")
  })
  observeEvent(input$clea, {
    leafletProxy("map") %>% 
      leaflet::clearGroup("initial")
  })
  observeEvent(input$add1, {
    x1_b2 = x1[1, , , 1] # band 2
    leafletProxy("map") %>% 
      leaflet::clearGroup("initial") %>% 
      leafem:::addGeoRaster(
        x1_b2
        , opacity = 1
        , group = "added"
        , colorOptions = colorOptions(
          palette = grey.colors(256)
        )
      )
  })
}
shinyApp(ui, server)