Borealis
Borealis

Reputation: 8490

How to apply polygon tint bands in Leaflet?

The image shows a tint band (aka shapeburst fill) applied to a polygon shapefile in QGIS. I've been paging through leaflet documentation trying to find something similar without success.

Is there a method to apply a tint band similar to the screenshot to polygon boundaries in a Leaflet web map?

enter image description here

Upvotes: 2

Views: 385

Answers (1)

Sébastien Rochette
Sébastien Rochette

Reputation: 6671

I imagine your question is about a direct leaflet solution, but as I work with R, I found it interesting to try to answer it with tools I know.
The idea is simple, I cannot reproduce the transparency gradient, but I thought I could create a doughnut polygon and apply a color with transparency on it:

  • Create a buffer with a negative distance to get a smaller polygon with the shape of the original
  • Use the buffer to remove the inside of the original polygon
  • Map the doughnut realized on leaflet with transparency

You can produce your doughnut polygons with any GIS software, but the interest of R is that you can directly create the leaflet widget. So here is the code with example data:

# Load libraries
library(raster)
library(sf)
library(raster)
library(dplyr)
library(ggplot2)
library(leaflet)

# Get some data
fra.sp <- getData('GADM', country = 'FRA', level = 1)
fra.sf <- st_as_sf(fra.sp)

# Create buffer
fra.sf.buf <- st_cast(st_buffer(fra.sf, dist = -0.1))

# Create holes in original polygons
fra.sf.buf.comb <- fra.sf.buf %>% st_combine() %>% st_sf()
fra.sf.doug <- st_difference(fra.sf, fra.sf.buf.comb) %>% st_cast()

# Create leaflet widget and save on disk
## Color palette
factpal <- colorFactor(rep(unique(yarrr::piratepal("basel")),
                                 length.out = nrow(fra.sf.doug)),
                       fra.sf.doug$NAME_1)
m <- leaflet() %>%
  addProviderTiles(providers$Stamen.Toner) %>%  
  addPolygons(data = fra.sf.doug.simple, weight = 1, smoothFactor = 0.75,
    opacity = 0, fillOpacity = 0.6,
    color = "#000000",
    fillColor = ~factpal(fra.sf.doug.simple$NAME_1),
    highlightOptions = highlightOptions(color = "white", weight = 2,
      bringToFront = TRUE)) %>%
  addPolygons(data = fra.sf.simple, weight = 1, smoothFactor = 0.75,
    opacity = 1.0, fillOpacity = 0,
    color = "#000000")
## Save widget
htmlwidgets::saveWidget(m, file = "m.html")

Tinted bands with R and leaflet

As I found the output nice, I created an article on my blog with the different steps detailed.

Upvotes: 1

Related Questions