9

I would like to be able to update properties of drawn polygons in leaflet without it drawing the polygons again. This makes it rather slow, and since I want to use it for a time-series, they need to update quickly. I have added some example code where the button update the colors (of polygons), however it is slow because of the redrawing. Any suggestions would be more than welcome! I have reused some elements to of previous questions to get a working example that downloads its own shapefile. Looking forward to your solutions!

# bits of code from: https://stackoverflow.com/questions/29118059/display-spatialpolygonsdataframe-on-leaflet-map-with-r

library(rgdal)
library(leaflet)
library(shiny)

download.file(file.path('http://www.naturalearthdata.com/http/',
                        'www.naturalearthdata.com/download/50m/cultural',
                        'ne_50m_admin_0_countries.zip'), 
              f <- tempfile())
unzip(f, exdir=tempdir())

world <- readOGR(tempdir(), 'ne_50m_admin_0_countries', encoding='UTF-8')

#lets grab 20 countries:
commonwealth <- c("Antigua and Barb.", "Australia", "Bahamas", "Bangladesh", 
                  "Barbados", "Belize", "Botswana", "Brunei", "Cameroon", "Canada", "Cyprus",
                  "Dominica", "Fiji", "Ghana", "Grenada", "Guyana", "India", "Jamaica", "Kenya",
                  "Kiribati")
col<-c("red","green", "yellow","blue")


ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  actionButton("recolor", "New colors")
)

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

  points <- eventReactive(input$recolor, {
    sample(col, 20, replace=TRUE)
  }, ignoreNULL = FALSE)

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles(providers$Stamen.TonerLite,
                       options = providerTileOptions(noWrap = TRUE)
      ) %>%
      addPolygons(data=subset(world, NAME %in% commonwealth), weight=2, color=~sample(col, 20, replace=TRUE))
  })

  observe({
    leafletProxy("mymap", data = points()) %>%
    clearShapes() %>%
      addPolygons(data=subset(world, NAME %in% commonwealth), weight=2, color=~points())
  })
}

shinyApp(ui, server)
MJC
  • 103
  • 6
  • 1
    I'd love to get the reputation points by reproducing another answer here... but this appears to have been asked and answered here: https://stackoverflow.com/questions/37433569/changing-leaflet-map-according-to-input-without-redrawing – D. Woods Aug 02 '19 at 18:48

0 Answers0