Is it possible to update polygon fill in leaflet for shiny without recreating the map object Is it possible to update polygon fill in leaflet for shiny without recreating the map object r r

Is it possible to update polygon fill in leaflet for shiny without recreating the map object


To illustrate @Yihui Xie's comment, here is an example using leafletProxy to change the colors of the Polygon, based on a selectInput.

library(shiny)library(leaflet)library(sp)library(raster)## Spatial Polygon ##########Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)Srs1 = Polygons(list(Sr1), "s1")Srs2 = Polygons(list(Sr2), "s2")Srs3 = Polygons(list(Sr3, Sr4), "s3/4")SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)SpPDF <- SpatialPolygonsDataFrame(SpP, data = data.frame(x=1:length(SpP)), match.ID = F)Extent = extent(SpPDF)## UI ##########ui <- fluidPage(  selectInput("col", label = "Select a color", choices = c("Blues", "viridis", "magma")),  leafletOutput("map"))## SERVER ##########server <- function(input, output) {  output$map <- renderLeaflet({    leaflet()  %>%       addTiles() %>%       fitBounds(lng1 = Extent[1],lat1 = Extent[3], lng2 = Extent[2], lat2 = Extent[4])  })  observe({    req(input$col)    pal = colorFactor(input$col, domain = factor(SpPDF$x))    leafletProxy("map") %>%      addPolygons(data = SpPDF, color = ~pal(factor(SpPDF$x)))  })}shinyApp(ui, server)