Search code examples
rr-leaflet

Leaflet polygons add black borders


I would like to add a black border around my polygons. See the image below what I have got so far.

enter image description here

I used this code. I dont know how I could include a zip file so its reproducible.

library("rgdal")
library("leaflet")
 
 amsterdam.districts <- shapefile("~/R/Shiny/Shapefiles/sd2010zw_region.shp")
 amsterdam.districts <- spTransform(amsterdam.districts, CRS("+init=epsg:4326"))
 amsterdam.districts$STADSDEELN<- c("Centrum","Westpoort","West","Nieuw West","Zuid","Oost","Noord","Zuidoost")
 
 amsterdam.districts$SDNUMMER=as.factor(amsterdam.districts$SDNUMMER) 
 factpal=colorFactor(brewer.pal(n = 11, name ="Spectral") , amsterdam.districts$SDNUMMER) 
 
   leaflet() %>%
     addPolygons(
       data =amsterdam.districts, 
       stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5,
       color = "grey",
       fillColor = ~factpal(SDNUMMER),
       layerId = amsterdam.districts@data$STADSDEELN)%>%
     addProviderTiles("CartoDB.Positron", options= providerTileOptions(opacity = 1))

Solution

  • Here's a reproducible example:

    library(mapview)
    library(RColorBrewer)
    
    factpal <- colorFactor(brewer.pal(n = 11, name ="Spectral") , gadmCHE$NAME_1) 
    
    leaflet() %>%
      addPolygons(
        data = gadmCHE, 
        stroke = TRUE, fillOpacity = 0.5, smoothFactor = 0.5,
        color = "black", opacity = 1,
        fillColor = ~factpal(gadmCHE$NAME_1)) %>%
      addProviderTiles("CartoDB.Positron", options = providerTileOptions(opacity = 1))
    

    You simply need to set stroke = TRUE and color = "black" to get the borders. Note that I also set opacity = 1 to prevent semitransparent borders.