[GIS] Spiderfy all Leaflet markerClusters with fewer than 5 markers

leafletmarkers

I am making a Leaflet map using markerCluster.js.
I would like to make all clusters with fewer than 5 markers automatically "spider", regardless of the zoom level. For example in the image below, I'd like the two clusters of 2 to be "spiderfied" regardless of the zoom, without having to get to the maxZoomLevel of my map.

enter image description here

I assume I need to do something along the lines of the pseudocode:

if (markerGroup.getChildCount() < 5) {
     markerGroup.Spiderfy()
}

However, I'm not sure exactly where to do this.

I tried adding a this after the map constructor. The first cluster is drawn open (spiderfied), but the rest are still closed. Also after I zoom, the one that was open closes.

  map.eachLayer(function(layer){     //iterate over map rather than clusters
     if (layer.getChildCount){         // if layer is markerCluster
           if (layer._childCount < 5){
              layer.spiderfy();
              console.log(layer._childCount);  // log count of points within each cluster
           }
      }

enter image description here

Best Answer

According to this comment "You can only have one cluster spiderfied at a time though". It is from 2015 but I assume it is still valid.

An alternative could perhaps be to try to customize the cluster icon instead to be like a spider web (for n < some limit). I tested modifying the Leaflet.markercluster example, to have the clusters show a list of the numbers associated with all its markers instead of the original sum of all the numbers, and I got it working:

map screenshot Of course that does not look good, but it should be a starting point.

The key part of it is the following

iconCreateFunction: function (cluster) {
  var markers = cluster.getAllChildMarkers();
  var n = [];
  for (var i = 0; i < markers.length; i++) {
    n.push(markers[i].number);
  }
  var divContent = n.join(', ');
  var size = calculateSize(divContent, { });
  var divWrapper = '<div style="background-color: red; width: ' + size.width
    + '; height: ' + size.height + '">' +  divContent + '</div>';
  return L.divIcon({ html: divWrapper, className: 'mycluster' });
},