Building CampaignHawk: Clustering with Leaflet Markercluster (Part 17)

As you recall, we now have a bunch of data that, as a practical matter, we can’t render because there are too many data points. To solve this, we need to implement markercluster. You’d be surprised at how easy this is.

Within our if (!this.props.loading) conditional in toggleDataLayer we need to add a cluster group. Everything we need to add is done functionally and Mapbox has some very intuitive functions. They get an A+. I will explain these various functions below the code block.

if (!this.props.loading) {
let clusterGroup = new L.MarkerClusterGroup();
let datalayer = L.mapbox.featureLayer()
.setGeoJSON(this.props.data)
clusterGroup.addLayer(datalayer)
map.addLayer(clusterGroup)

} ...

First, we create a new MarkerClusterGroup called clusterGroup. This clusterGroup object is what makes the magic happen.

Then we create a data layer that we will name datalayer, much like we did previously when we rendered every point independently. The only difference here is that we are creating the layer and adding the GeoJSON all in one step.

Now we take our clusterGroup and use the addLayer function to add our datalayer to the clusterGroup.

Then we add the clusterGroup layer to our map with the addLayer function.

Done. Now when you click on a radio button and toggle a layer, your clustered map appears.

Our newly clustered map.

Next Steps

Now that we have some data and we have it clustering properly, we need to make different data layers between which we can toggle. Some of these will require Turf.js and some will just require basic filtering.