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.

2
  • Would it be easier to use setMaxBounds to stop people scrolling outside your area of interest?
    – Spacedman
    Commented Mar 8, 2017 at 15:56
  • @Spacedman : Yes, that would indeed be a good idea. Thanks.
    – Tobias D
    Commented Mar 10, 2017 at 10:04

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.