leaflet.extras
leaflet.extras copied to clipboard
Duplicate legends when using addGeoJSONChoropleth in Shiny
When using addGeoJSONChoropleth in an R Shiny application, changing the colormap seems to result in a extra legend for each previously chosen colormap. Problem seems to occur both on the CRAN version and github master.
Live example: https://uoacer.shinyapps.io/GeoJSONChoropleth_test/
R version 3.6.3
Code to reproduce:
library(leaflet.extras)
library(shiny)
library(RColorBrewer)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(
top = 10,
right = 10,
selectInput("colors", "Color Scheme",
rownames(subset(
brewer.pal.info, category %in% c("seq", "div")
)))
)
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>% addProviderTiles(providers$CartoDB.Positron) %>% setView(-75.14, 40, zoom = 11)
})
observe({
print(paste("colorscale: ", input$colors))
leafletProxy("map", session) %>%
clearShapes() %>%
clearControls() %>%
addGeoJSONChoropleth(
"https://rawgit.com/TrantorM/leaflet-choropleth/gh-pages/examples/basic_topo/crimes_by_district.topojson",
valueProperty = "incidents",
scale = input$colors,
mode = "q",
steps = 5,
color = "#ffffff",
weight = 1,
fillOpacity = 0.5,
highlightOptions =
highlightOptions(
fillOpacity = 1,
weight = 2,
opacity = 1,
color = "#000000",
bringToFront = TRUE,
sendToBack = TRUE
),
legendOptions =
legendOptions(title = "Crimes", position = "bottomright"),
)
})
}
shinyApp(ui, server)
With this PR in place - https://github.com/bhaskarvk/leaflet-choropleth/pull/1/files#diff-1a04ef99957189d3dcef4a74278eddd33a16a2bbe9609aa53b65bf369831fd7f - there's a possible workaround, which is re-running renderLeaflet like so:
library(leaflet.extras)
library(shiny)
library(RColorBrewer)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(
top = 10,
right = 10,
selectInput("colors", "Color Scheme",
rownames(subset(
brewer.pal.info, category %in% c("seq", "div")
)))
)
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>% addProviderTiles(providers$CartoDB.Positron) %>% setView(-75.14, 40, zoom = 11) %>%
addGeoJSONChoropleth(
"https://rawgit.com/TrantorM/leaflet-choropleth/gh-pages/examples/basic_topo/crimes_by_district.topojson",
valueProperty = "incidents",
scale = input$colors,
mode = "q",
steps = 5,
color = "#ffffff",
weight = 1,
fillOpacity = 0.5,
highlightOptions =
highlightOptions(
fillOpacity = 1,
weight = 2,
opacity = 1,
color = "#000000",
bringToFront = TRUE,
sendToBack = TRUE
),
legendOptions =
legendOptions(title = "Crimes", position = "bottomright"),
)
})
}
shinyApp(ui, server)
Setting layerId = "main",
is another workaround that works with that PR
Here's my build of this package with the fix btw https://github.com/neon-ninja/leaflet.extras