'How to fix Heatmap being masked by other layers in Leaflet

I am trying to use Leaflet in R and I want my map to have two layers: one for a heatmap and one for polygons. The problem is that polygons always stay on top of the heatmap whereas I want the heatmap to appear on top of the polygons. Below is an example code:

library(leaflet)
library(leaflet.extras)

leaflet() %>%
  addPolygons(lng = c(10, 20, 20, 10), lat = c(10, 10, 20, 20), fillOpacity = 0.75, group = "L1") %>%
  addHeatmap(lng = c(14, 15, 15, 16), lat = c(10, 10, 12, 10), group = "L2") %>%
  addLayersControl(
    overlayGroups = c( "L1", "L2"),
    options = layersControlOptions(collapsed = T),
    position = "bottomleft"
  )

Someone gave a partial solution to this here: Controlling the Z index of a Leaflet heatmap in R

However I couldn't figure it out how to solve the issue using that answer. Any helps would be appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source