You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny中使用addDrawToolbar后Leaflet地图变灰无显示问题求助

Fixing Gray Leaflet Map When Using addDrawToolbar in Shiny

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:

  1. Add a dedicated layer group for drawn shapes
    You need to explicitly create the 'Selected' layer group using addLayersGroup() before calling addDrawToolbar. This gives the toolbar a valid space to store the polygons/rectangles you draw.

  2. 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 editOptions to include targetGroup = '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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:48:37