R leaflet is drawing base layers on top of overlay

2020-05-03 12:11发布

I'm running into a problem with leaflet for R: When I change the base layer (polygons), the overlay layer gets pushed behind the base layer. From my reading of the leafletR help files, the overlay layers should always have a higher z-index than the base layers, and should stay on top.

Example is here: http://rpubs.com/bvila/overdraw

require(acs)
require(tigris)
require(leaflet)
require(tidyverse)

leaflet(data = counties(state = "UT")) %>% 
  addPolygons(color = "red", fillColor = "orange", group = "base1", fillOpacity = 1) %>% 
  addPolygons(color = "pink", fillColor = "purple", group = "base2", fillOpacity = 1) %>% 
  addPolygons(color = "yellow", fillColor = "green", group = "overlay", fillOpacity = 1) %>% 
  addLayersControl(baseGroups = c("base1", "base2"), options = layersControlOptions(collapsed = F), overlayGroups = "overlay")

1条回答
我命由我不由天
2楼-- · 2020-05-03 12:38

The polygon layers should always have a higher z-index than tile layers. The layers control uses this terminology because the base groups are intended to be base (tile) layers, and the overlay groups are intended to be overlay (polygon) layers.

You can work around this with a bit of JavaScript, see the onRender stage added to the pipe (you only have to do this once for a given map object):

leaflet(data = counties(state = "UT")) %>% 
  addPolygons(color = "red", fillColor = "orange", group = "base1", fillOpacity = 1) %>% 
  addPolygons(color = "pink", fillColor = "purple", group = "base2", fillOpacity = 1) %>% 
  addPolygons(color = "yellow", fillColor = "green", group = "overlay", fillOpacity = 0.5) %>% 
  addLayersControl(baseGroups = c("base1", "base2"), options = layersControlOptions(collapsed = F), overlayGroups = "overlay") %>%
  htmlwidgets::onRender("
    function(el, x) {
      this.on('baselayerchange', function(e) {
        e.layer.bringToBack();
      })
    }
  ")
查看更多
登录 后发表回答