Search code examples
rshinyr-leafletleaflet.draw

Allow only editing and deleting but not adding new markers


I want to have a map, where markers can be dragged and deleted, but no new markers added. This should be simple to do, but I couldn't figure out, how to do this using the leaflet DrawToolbar. There doesn't seem to be an option which disables the drawing.

library(shiny)
library(leaflet)
library(leaflet.extras)

data <- data.frame(lat = c(48, 47.5), lng = c(11, 11), marker_id = c(1, 2))

ui <- fluidPage(
  leafletOutput("map")
)

server <- function(input, output) {
  values <- reactiveValues(data = data)

  output$map <- renderLeaflet({
    leaflet() %>% addTiles() %>% setView(11, 48, 8) %>% 
      addDrawToolbar(
        targetGroup = "markers",
        polylineOptions = FALSE,
        polygonOptions = FALSE,
        rectangleOptions = FALSE,
        circleOptions = FALSE,
        editOptions = editToolbarOptions())
  }) 

  observe({
    leafletProxy("map") %>% clearMarkers() %>%
      addMarkers(data = values$data,
        options = list(draggable = TRUE), group = "markers")
  })
}

shinyApp(ui, server)

Solution

  • You can add css styling to hide the button. Changing your fluidPage as follows should do the trick:

    ui <- fluidPage(
      tags$head(
        tags$style(HTML("
          a.leaflet-draw-draw-marker {
          display: inline;
          visibility: hidden;
          }
         div.leaflet-draw-toolbar{
           box-shadow: 0 0px 0px rgba(0,0,0,0) !important; 
          -moz-box-shadow:0 0px 0px rgba(0,0,0,0) !important;
          -webkit-box-shadow: 0 0px 0px rgba(0,0,0,0) !important;
          border-color: rgba(0,0,0,0) !important;
          }
    
        "))
      ),
      leafletOutput("map")
    )
    

    Please let me know if you have any issues.