0

I'm building a Shiny app using leafpm polygon editor. Basically I apply some changes to an existing polygon, then I save the edited polygons and edit the leaflet map by removing polygons and adding the new polygons.

My problem is that I don't manage to make the function removeShape() work for "Cut layers" leafpm option. You can see in the reprex below that if you edit the polygon shape with the "Edit layers" tool, when you click on save the polygon is removed and replaced well (I changed the colour so that it's easy to see that the polygon was replaced). If you edit the polygon shape with the "Cut layers" tool and click on save, removeShape() does not work and you end up with two duplicate polygons overlapping (one with the original colour and one with the new colour; you can use the "Drag layers" tool to visualise it).

I tried playing with the field layerId in removeShape() but couldn't get one that removes a cut polygon. Any idea what I'm doing wrong?

library(shiny)
library(leaflet)
library(mapedit)
library(sf)
library(leafpm)
library(ggplot2)
library(dplyr)

# Create a polygon
poly <- data.frame(lon = c(-60), lat = c(1)) %>% st_as_sf(coords = c("lon", "lat"), crs = 4326) %>% st_buffer(., 1000)
poly$ID="ID1"


### UI
ui <- fluidPage(
  editModUI("map", height=600, width = "100%"),
  actionButton('save', 'Save changes', style="color: #fff; background-color: #009138ff; border-color: #009138ff")
)


### Server
server <- function(input, output, session) {
  
  ### Create base map
  edits <- callModule(
    editMod,
    leafmap = leaflet() %>% addTiles() %>% addPolygons(data=poly, color="darkred", fillOpacity=0.5, group="editable", layerId=poly$ID) %>% leafpm::addPmToolbar(targetGroup="editable"),
    id = "map",
    record = FALSE,
    sf = TRUE,
    targetLayerId = "editable"
  )
  
  ### Save edits
  observeEvent(input$save, {
    # Isolate the last edit of the polygon
    dist <- edits()$edited %>% group_by(layerId) %>% summarise_all(last) ; print(dist)
    
    # Update leaflet map
    leafletProxy("map-map") %>% 
      removeShape(layerId = dist$layerId) %>%
      addPolygons(data=dist, color=sample(c("gold", "green", "blue", "black"), size=1), fillOpacity=0.5, group="editable", layerId=dist$layerId)
  })
}


### Run the application 
shinyApp(ui = ui, server = server)

0

Browse other questions tagged or ask your own question.