Search code examples
rshinyr-leaflet

Select and Deselect Polylines in Shiny/Leaflet


I solved my problem as Lauren. Changing styles when selecting and deselecting multiple polygons with Leaflet/Shiny The only difference is that I use polylines instead of polygons. I want to select multiple polylines und deselect them at click again. But it doesn't work..it deletes the reselected from the table but not from the map and after a line was deleted from my selected lines I can't select it anymore.

Can someone help me please!

Data

Here is my code:

library(shiny)
library(leaflet)
library(geojsonio)

url <- "pathTogeojson"

geojson <- geojsonio::geojson_read(url, what = "sp") 

shinyApp(
  ui <- fluidRow(
        leafletOutput("map")),

  server <- function(input, output, session) {

    click_list <- reactiveValues(ids = vector())  

    output$map <- renderLeaflet({
      leaflet() %>% 
        addTiles() %>% 
        setView(lng=16.357795000076294, lat=48.194883921677935, zoom = 15) %>%
        addPolylines(data=geojson, layerId = geojson@data$name_1, group = "selected", color="red", weight=3,opacity=1)
    })

    observeEvent(input$map_shape_click, {

      click <- input$map_shape_click
      proxy <- leafletProxy("map")
      click_list$ids <- c(click_list$ids, click$id)

      sel_lines <- geojson[geojson@data$name_1 %in% click_list$ids, ]

      if(click$id %in% sel_lines@data$id)
      {
        nameMatch <- sel_lines@data$name_1[sel_lines@data$id == click$id]
        click_list$ids <- click_list$ids[!click_list$ids %in% click$id] 
        click_list$ids <- click_list$ids[!click_list$ids %in% nameMatch]

        proxy %>% removeShape(layerId = click$id)
      }
      else
      {
        proxy %>% addPolylines(data = sel_lines, layerId = sel_lines@data$id, color="#6cb5bc", weight=5,opacity=1)
      }
    })
  })

Solution

  • I found the solution by my own..my data and my incomprehension were the problem. It only works, when all used columns are type character...so i had to do a type conversion with as.character()