1

I am trying to cut a leaflet map in R, so I only show a specific municipality. I have manage to hide the remaining municipalities in the country, but that leaves the water and the rest of the world visible.

dk <- getData("GADM",country="Denmark",level=2)

frb <- dk[dk$ID_2!=10,]

leaflet() %>%
  setView(lat=55.680544, lng=12.519379,zoom=13)%>%
  addTiles(group="Kort") %>% 
  addPolygons(data = frb,
          fillColor= "white",
          fillOpacity = 1, 
          weight = 2, 
          color = "white") 

I think I need to make a polygon of the remaining world and make it white, but I can't figure out how.

Tobias D
  • 163
  • 2
  • 8

1 Answers1

1

I would possibly proceed as follows:

  • first, create a worldwide raster using the default spatial extent of the 'missing' method (see ?raster: xmn=-180, xmx=180, ymn=-90, ymx=90);
  • then, transform this template into a 'Spatial*' object using rasterToPolygons;
  • and finally, cut a hole into it using gDifference from rgeos (inspired by Remove intersect of one polygon from another in R).

Here is the resulting code. Interactive data display is realized through mapview. Make sure to have a look at mapviewGetOption("basemaps") which lists the single map types compatible with mapview()'s 'map.type' argument.

library(raster)
library(rgeos)
library(mapview)

## select municipality
dk <- getData("GADM", country = "Denmark", level = 2)
mc <- dk[10, ]

## create mask using worldwide raster as template
wld <- rasterToPolygons(raster(ncol = 1, nrow = 1, crs = proj4string(mc)))
msk <- gDifference(wld, mc)

## setup map and zoom to municipality
m <- mapview(msk, color = "white", alpha = 1, alpha.regions = 1) + mc
m

map

fdetsch
  • 5,183
  • 2
  • 29
  • 41