1

I came across a problem when I was trying to visualize polygons using Simple Features and Mapview.

I've created two rectangles, a and b and put them on Mapview on two layers. My problem is that if I select b before a, the b rectangle will be covered by a and will not be properly shown.

Is there any way I could always keep a in the background, so that b is always shown when selected?

library(mapview)
library(sf)

a<-rbind(c(0,0), c(15, 0), c(15, 5), c(0, 5), c(0, 0))
a_polygon<-st_polygon(list(a))

b<-rbind(c(5,1), c(10, 1), c(10, 4), c(5, 4), c(5, 1))
b_polygon<-st_polygon(list(b))


mapview(list(st_sfc(a_polygon), st_sfc(b_polygon)), col.regions = list('blue', 'yellow'), layer.name =c('a', 'b'))

enter image description here

Waldi
  • 39,242
  • 6
  • 30
  • 78
Moein
  • 101
  • 5

2 Answers2

1

Instead of using mapview which is an API for leaflet, you could use leaflet directly.
leaflet allows to add Panes to control layers order:

leaflet() %>% addMapPane("background", zIndex = 400) %>%  
              addMapPane("foreground", zIndex = 500) %>% 
              addPolygons(data = a_polygon, 
                          group="a", 
                          color ='blue',
                          fillOpacity= 1,
                          options = pathOptions(pane = "background")) %>%
              addPolygons(data = b_polygon,
                          group="b",
                          color='yellow',
                          fillOpacity = 1,
                          options = pathOptions(pane = "foreground")) %>%
              addLayersControl(overlayGroups = c("a", "b"),
                               options = layersControlOptions(collapsed = FALSE))

enter image description here

Waldi
  • 39,242
  • 6
  • 30
  • 78
0

You can use the alpha.regions argument to allow layers to be somewhat see-through.

mapview(a_polygon, col.regions = 'blue', alpha.regions = .6) +
  mapview(b_polygon, col.regions = 'yellow', alpha.regions = .6)

The alpha.regions can be set from 0(not visible) to 1(opaque).This is what it looks like with 'b' selected first, and then 'a' with alpha for both at .6:

enter image description here

mrhellmann
  • 5,069
  • 11
  • 38