Vector Layers Order in Leaflet-R – How to Manage Layers

leaflet-rr

Here is a leaflet map in R

https://lawsblog.netlify.com/post/leaflet-map/

The white lines are neighbourhood boundaries.
The green polygons are parks.
The parks are drawn over the boundaries obscuring the borders.
I want the white neighbourhood boundaries to be drawn on top of the parks so that the entire border is seen.

This sounds like an issue of layer ordering.

I thought I could use zIndex with leaflet to solve the problem. I've tried hoods = 200, parks = 300 and hoods = 200, parks = 100. I can't get it to work.

The relevant code:

# Add neighbourhoods
  addPolygons(data = hood_shp, 
              fillColor = ~pal(be_per_cap),
              weight = 2,
              opacity = 1,
              color = "white",
              dashArray = "0",
              fillOpacity = 1.0,
              options = list(zIndex = 200) %>% 
# Add parks
  addPolygons(data = parks,
              color = "green",
              weight = 1.0,
              opacity = 1.0,
              options = list(zIndex = 300),
              fillOpacity = 1.0)

Best Answer

This is possible with the latest leaflet version from github. They've introduced a function called addMapPane which gives full control over individual layer ordering. Here's an example:

# devtools::install_github("rstudio/leaflet")

library(mapview) # for the data
library(leaflet)
library(sf)      # for data wrangling
library(dplyr)   # for data wrangling

# create some borders
borders = franconia %>%
  group_by(district) %>%
  summarise() %>%
  st_cast("MULTILINESTRING")

# create a map with individual layer ordering using addMapPane
leaflet() %>%
  addTiles() %>%
  addMapPane("polygons", zIndex = 410) %>%
  addMapPane("borders", zIndex = 420) %>%
  addPolygons(data = franconia, group = "franconia", weight = 2,
              options = pathOptions(pane = "polygons")) %>%
  addPolylines(data = borders, group = "district", color = "black",
               opacity = 1, options = pathOptions(pane = "borders")) %>%
  addLayersControl(overlayGroups = c("franconia", "district"))

Of course, in your example map you're overlaying two polygon layers so you will need to decide which one of those should be on top. You cannot have just the borders of a polygon layer overlay the other but not the fill... I suggest you create a 3rd layer with only the borders added via addPolylines and have that in the pane with the highest zIndex similar to the example above.