Marnick
Marnick

Reputation: 81

Using markerClusterOptions with SpatialPolygons in Leaflet

I am using the package Leaflet to plot around 25.000 polygons on a map. Because of this large number of polygons I want to make use of markerClusterOptions. This is what I would like to do:

leaflet() %>% 
 addTiles() %>% 
 addPolygons(data=sp_polygons,
            clusterOptions = markerClusterOptions())

But addPolygons doesn't know clusterOptions. What is possible, is to do the following

leaflet() %>% 
 addTiles() %>% 
 addMarkers(data=coordinates(sp_polygons),
            clusterOptions = markerClusterOptions())

But when I zoom in I only markers and not the polygons. Is there a way to use clusterOptions but still show the polygons when zooming in?

Upvotes: 4

Views: 1585

Answers (1)

fdetsch
fdetsch

Reputation: 5308

To cut a long story short, you could simply create a SpatialPointsDataFrame from the polygon data (as you did above using coordinates) and subsequently display points and polygons on the same map. Here is an example using the mapview package.

library(sp)
library(mapview)

## create spatial points from Switzerland administrative borders
gadmCHE_pts <- SpatialPointsDataFrame(coordinates(gadmCHE), 
                                      data = gadmCHE@data, 
                                      proj4string = CRS(proj4string(gadmCHE)))

## display data                     
mapview(gadmCHE_pts, clusterOptions = markerClusterOptions()) + 
  gadmCHE

combined_image

Upvotes: 2

Related Questions