'How to check if a marker is in a cluster?

With Leaflet.Markercluster, how is it possible to check if a marker is in a cluster?



Solution 1:[1]

Use Leaflet's hasLayer() function

Leaflet has a function hasLayer() that returns true/false whether a layer currently exists in the map. When clustered, a marker is technically no longer a layer on the map, so hasLayer() would return false.

I use this to deselect a selected marker if it gets clustered after zoom events occur.

Below is roughly what I do; this is not complete code...

Relevant abbreviated code:

I hold my clustering like this...

this.markersClustered = L.markerClusterGroup({ // Lots of stuff here... } })

In my click event for individual markers, I store the marker in a "selectedItem" object (which I use for all kinds of other logic in my app)...

onEachFeature(feature, marker) {
    marker.on("click", e => {

        // ... (lots of code) ...

        // Save instance of the marker; I call it "layer" only
        // because I only use this for the hasLayer() check
        this.selectedItem.layer = marker

        // Here do other stuff too, whatever you need...
        //this.selectedItem.target = e.target
        //this.selectedItem.latlng = e.latlng
        //this.selectedItem.id = e.target.feature.id
        //this.selectedItem.icon = layer._icon

        // ... (lots of code) ...

    })
}

When cluster animations end, using hasLayer(), check whether the selected marker is in a cluster...

this.markersClustered.on('animationend', (e) => {

  // Check visibility of selected marker
  // True: Not in a cluster (ie marker is visible on map)
  // False: In a cluster (ie marker is not visible on map)

  console.log("Selected marker visible?:" +  this.map.hasLayer(this.selectedItem.layer))

})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MarsAndBack