Shiny中使用addDrawToolbar后Leaflet地图变灰无显示问题求助
I’ve run into this exact snag before! The root issue here is tied to the targetGroup parameter you set in addDrawToolbar—you specified 'Selected' but didn’t create a corresponding layer group for the drawn shapes to live in. Shiny’s Leaflet integration expects that target group to exist before the draw toolbar tries to use it, which is why removing the toolbar code makes the map render normally again.
Here’s how to fix it step by step:
Add a dedicated layer group for drawn shapes
You need to explicitly create the'Selected'layer group usingaddLayersGroup()before callingaddDrawToolbar. This gives the toolbar a valid space to store the polygons/rectangles you draw.Align edit toolbar settings with the target group
Make sure the edit options explicitly target the same layer group to avoid conflicts when modifying drawn shapes.
Here’s your modified, working code:
library(shiny) library(leaflet) library(leaflet.extras) ui <- fluidPage( leafletOutput("mymap") ) server <- function(input, output) { output$mymap <- renderLeaflet({ leaflet() %>% addProviderTiles("Esri.WorldStreetMap") %>% # Create the target layer group first addLayersGroup("Selected") %>% addDrawToolbar( targetGroup = 'Selected', polylineOptions = FALSE, markerOptions = FALSE, polygonOptions = drawPolygonOptions( shapeOptions = drawShapeOptions(fillOpacity = 0, color = 'red', weight = 3) ), rectangleOptions = drawRectangleOptions( shapeOptions = drawShapeOptions(fillOpacity = 0, color = 'red', weight = 3, clickable = TRUE) ), editOptions = editToolbarOptions( edit = TRUE, selectedPathOptions = selectedPathOptions(), # Ensure edit toolbar targets the correct group targetGroup = 'Selected' ) ) }) } shinyApp(ui, server)
Key changes explained:
- Added
addLayersGroup("Selected")right after the base tiles: This creates the layer group that the draw toolbar uses to store your drawn shapes. - Updated
editOptionsto includetargetGroup = 'Selected': This tells the edit toolbar exactly which layer group to modify when you edit drawn elements.
When you run this code, the map should load normally, and you’ll be able to draw red polygons/rectangles, plus edit them as expected.
内容的提问来源于stack exchange,提问作者Shubham

