Here is a leaflet map in R


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)

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(sf)      # for data wrangling
library(dplyr)   # for data wrangling

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

# 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.

  • Thank you for your post. It was most helpful. However, I'm not sure how to highlight the neighbourhood when I mouseover it. Before, when the border and fill, were part of the same object it was straightforward. Now that they are separate it's unclear. I'll clarify in a separate question.
    – ixodid
    May 26 '18 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.