leaflet.extras
leaflet.extras copied to clipboard
R Leaflet marker click event not working after using addSearchMarker
I have a app with a leaflet map and an observeEvent function for circleshapes clicks. When a circle is clicked, a plot is displayed
This all works, but the problem is that I also have a leaflet.extras addSearchMarker tool for searching the markers (called somewhere1, 2 , 3). When I search for a circle the marker click event no longer works.
Here is a reproductible example. Thanks for helping.
library(shiny)
library(leaflet)
library(dplyr)
library(leaflet)
library(leaflet.extras)
# Dummy data
df <- data.frame(lng = c(-5, -5, -5, -5, -15, -15, -10),
lat = c(8, 8, 8, 8, 33, 33, 20),
year = c(2018, 2018, 2018, 2017, 2017, 2017, 2016),
type = c('A', 'A', 'A', 'A', 'B', 'B', 'A'),
id =c(1, 1, 1, 1, 2, 2, 3),
place =c("somewhere1", "somewhere1", "somewhere1", "somewhere1", "somewhere3", "somewhere2", "somewhere3"),
stringsAsFactors = FALSE)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(top = 10, right = 10,
style="z-index:500;", # legend over my map (map z = 400)
tags$h3("map"),
sliderInput("periode", "Chronology",
min(df$year),
max(df$year),
value = range(df$year),
step = 1,
sep = ""
),
checkboxGroupInput("choice",
"type",
choices = list("type A" = "A",
"type B" = "B"),
selected = 1),
plotOutput(outputId = "plot"))
)
server <- function(input, output, session) {
# reactive filtering data from UI
reactive_data_chrono <- reactive({
df %>%
filter(year >= input$periode[1] & year <= input$periode[2]) %>%
filter(type %in% input$choice) %>%
count(place,lng, lat, type, id) %>%
arrange(desc(n))
})
# colors
pal <- colorFactor(
palette = c('red', 'blue'),
domain = df$type
)
# static backround map
output$map <- renderLeaflet({
leaflet(df) %>%
addTiles() %>%
fitBounds(~min(lng), ~min(lat), ~max(lng), ~max(lat))
})
# reactive circles map
observe({
leafletProxy("map", data = reactive_data_chrono()) %>%
clearShapes() %>%
addCircles(lng=~lng,
lat=~lat,
weight = 5,
radius = ~(n*50000),
color = ~pal(type),
group ="cities", layerId = ~id, label =~df$place) %>%
addSearchFeatures(
targetGroups = "cities", options = searchFeaturesOptions(collapsed = TRUE,
zoom = 7, openPopup = TRUE, autoCollapse = TRUE, hideMarkerOnCollapse = TRUE, position = "topleft" ))
})
# Observe circles from leafletProxy "map"
observe({
leafletProxy("map") %>% clearPopups()
event <- input$map_shape_click
if (is.null(event))
return()
print(event) # Show values on console fort testing
# Filtering and plotting
x <- df[df$id == event$id, ]
x2 <- x %>%
count(id, year)
output$plot <- renderPlot({plot(x2$n, x2$year)
})
})
}
shinyApp(ui, server)
See https://github.com/bhaskarvk/leaflet.extras/issues/143. Once it is fixed in the upstream dependency, it will be updated here. Note, this is only for broken CircleMarkers, all other shapes should work.
Thank you.