Leaflet / Leaflet.markercluster

Marker Clustering plugin for Leaflet
MIT License
3.97k stars 1k forks source link

Cluster markers by tag? #641

Closed Cristy94 closed 8 years ago

Cristy94 commented 8 years ago

So I have some markers in an L.MarkerClusterGroup, markers are either green or red. When I zoom out, they all get clustered, is there any easy way to make it such that red markers get clustered together and green markers in other cluster?

I've seen that this is usually done by actually having different MarkerClusterGroups, but in my case I need to be able to iterate through all the markers (and I actually do that in a lot of parts in my code). So, I would either need to be able to simply add a tag to each marker (such as Red and Green) and only markers with same tag should be clustered together OR I need an way to create two different cluster groups but have a way of accessing the markers in both groups in a simple iteration (so I don't have to re-write a lot of code).

If none of those can work, is there other solution to have markers clustered in different clusters, while being in the same ClusterGroup? Can I have a cluster group inside another cluster group?

ghybs commented 8 years ago

Hi,

You could be interested in the following threads:

As for "accessing the markers in both groups in a simple iteration", what type of iteration are you using? If you just loop through all markers and order is not important, you could simply gather both MCG (or more) in a parent Layer Group (which does not need to be added to map) so that you can use the eachLayer method on it. Nesting MCG's in Layer Groups is not an issue. Nesting MCG inside MCG is a hell.

Hope this helps.

Cristy94 commented 8 years ago

This is how I solved my issue:

Instead of my old unitsLayer which was a MCG I have made it a simple LayerGroup and added two distinct cluster groups inside it (one for red units, one for green units).

    this.greenUnitsLayer.addTo(this.unitsLayer);
    this.redUnitsLayer.addTo(this.unitsLayer);
    this.map.addLayer(this.unitsLayer);

Now, in order to keep my previous code and not have duplicate (for each of the unit types), I have added this function to the unitsLayer, function which returns all the markers inside the unitsLayer, regarding their type:

    this.unitsLayer.customEachLayer = function(cb) {
        _this.greenUnitsLayer.eachLayer(function(marker) { cb(marker); });
        _this.redUnitsLayer.eachLayer(function(marker) { cb(marker); });
    };

Now, the only difference is the code is when an unit is created it is added to the MCG instead of the unitsLayer, and instead of using unitsLayer.eachLayer I now use unitsLayer.customEachLayer.