0

I'm working on a Leaflet map that will be part of a Shiny application. This map involves being able to click on a point to allow a plot to generate based on the input click. The map has an overlay group that can be toggled on and off. In this example, a simple popup displaying the name of the city will show up when the point is clicked.

Problem
When the map is initialized, the points are clickable. When the overlayGroup is turned off with the layersControl, the points are clickable. Once the overlayGroup is turned back on, the points are no longer clickable. This only affects the points that are covered by the overlayGroup (see the Myrtle Beach point).

What I've Tried
When there are multiple baseLayers that can be toggled by addLayersControl(), the circle markers are always clickable as the baseLayers are changed using this solution. This does not work with overlayGroups. I would like to find a similar solution with using overlayGroups that always keeps the circleMarkers on top so they are able to be clicked.

Code

# sample test of overlay groups in Leaflet

# load libraries
library(sf)
library(leaflet)

# get sample spatial data
demo(nc, ask = FALSE, echo = FALSE)
plot(nc)

# data frame for points
points <- data.frame(location = c("Greensboro","Charlotte","Raleigh","Myrtle Beach"),
                     lat = c(36.056,35.208,35.767,33.688),
                     long = c(-79.791,-80.847,-78.636,-78.908))

# Leaflet
leaflet(data = nc) %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  
  # Polygon layer
  addPolygons(data=nc, stroke = T, fillOpacity = 0, weight = 3, 
              color = "black", label = ~NAME,
              labelOptions = labelOptions(noHide = F, textsize = "12px", 
                                          style = list("font-weight" = "bold")), 
              group = "State") %>%

  # Point layer
  addCircleMarkers(data = points, lng = ~long, lat = ~lat, fillColor = "green",
                   weight = 3, fillOpacity = 0.5, radius = 10, stroke = TRUE,
                   popup = ~as.character(paste("<strong>City Name: </strong>", points$location,"<br/>")),
                   group = "Points") %>%
  
  
  # Layers control - polygon as an overlayGroup
  addLayersControl(overlayGroups = "State")
1
  • A temporary workaround would be to add highlightOptions = highlightOptions(sendToBack = TRUE) inside your addPolygons() function. This pushes the polygon layer back after mouse-over--so if the layer is toggled off and then on again, the circle markers won't immediately be clickable, but if the user moves their cursor over the polygon layer that sits on top of the circle marker, moves elsewhere on the map, and then moves back to the circle marker, the polygon layer will no longer be on top and the circle marker should be clickable. Commented May 10 at 21:48

0

Browse other questions tagged or ask your own question.