Search code examples
rpopupleafletlayerpolyline

Leaflet Map - second Polygon makes the first layer unclickable


I am working on a map of American Community Survey data. Currently I have a primary layer (seen below as plotMerge$incomePerCapita). It works well, has a fully fleshed out popup, image and all. When I add a second layer, to provide county and regional boundaries, the tract boundaries become un-clickable, seemingly masked by the new layer.

If I swap the layer order, the regional boundaries become invisible.

map1<-leaflet()%>%
  addTiles()%>%

addPolygons(data = plotMerge,
          fillColor = ~pal(plotMerge$incomePerCapita),
          color = "#000000", #this is an outline color
          fillOpacity = 0.8,
          weight = 0.2,
          popup=popup)%>%
addPolygons(data = countyPoly,
            fillColor = "transparent",
           color = "#000000",
           stroke = TRUE,
           weight = 1,
           smoothFactor = 0.5,
           group = "Counties")%>%
addLegend(pal = pal,
            values  = plotMerge$incomePerCapita,
            position = "bottomright",
            title = "State-wide Income Percentiles",
            labFormat = labelFormat(digits=1))

saveas(map1, "map1.html")
map1

Is there a way to show just the outline of a boundary in a second layer, yet leave the full functionality of the previous layer intact?

Should I be scripting the addPolygons in a different way to show the boundary without imposing a functionally obscure layer?

UPDATE:

I fixed an error and swapped the addPolygons code to get the layers in the right order.

map1<-leaflet()%>%
  addTiles()%>%
addPolygons(data = countyPoly,
            fillColor = "transparent",
           color = "#000000",
           stroke = TRUE,
           weight = 1,
           smoothFactor = 0.5,
           group = "Counties")%>%
addPolygons(data = plotMerge,
          fillColor = ~pal(plotMerge$incomePerCapita),
          color = "#000000", #this is an outline color
          fillOpacity = 0.8,
          weight = 0.2,
          popup=popup)%>%
addLegend(pal = pal,
            values  = plotMerge$incomePerCapita,
            position = "bottomright",
            title = "State-wide Income Percentiles",
            labFormat = labelFormat(digits=1))

Thanks for looking!


Solution

  • In case you are working with proper spatial objects using sp, you can coerce your countyPoly into a SpatialLines(DataFrame):

    countyLines <- as(countyPoly, "SpatialLinesDataFrame")
    

    Then you should be able to click the underlying polygon layer while showing the lines on top.

    EDIT: As a reproducible example you can try:

    library(mapview)
    library(sp)
    
    pol <- as(gadmCHE, "SpatialPolygons")
    ln <- as(gadmCHE, "SpatialLines")
    
    mapview(gadmCHE, color = "blue") + pol # not clickable
    mapview(gadmCHE, color = "blue") + ln # clickable