I'm using Leaflet together with Marker Cluster plugin on AngularJS app.
When selecting on a map's item I need to highlight it. Because I'm using divIcons, I'm adding or removing class, also setting colour if item is not a marker.
For that I'm saving last clicked item in the memory so that when the next item is selected, I can de-highlight the previous item and highlight current one.
// De-highlight previous item
if (lastClickedLayer) {
if (lastClickedLayer instanceof L.Marker) {
lastClickedLayer._icon.classList.remove('marker-highlighted');
}
else {
lastClickedLayer.setStyle({
color: (lastClickedLayer.feature.status === 'active') ? '#43A7E0' : '#EB7938'
});
}
}
// Highlight item on the map
lastClickedLayer = e.layer;
if (e.layer instanceof L.Marker) {
e.layer._icon.classList.add('marker-highlighted');
}
else {
e.layer.setStyle({
color: '#32C9AC'
});
}
Everything would be fine if not Marker Clustering! When I zoom out and get a cluster of current markers (let's say I select one marker first) and then zoom in back to that cluster, my selected marker does not have assigned 'marker-highlighted' class.
Also, If I'm at the vey end of zoom-in and clusters are showing spider-webs of markers (or how they're called), when cluster in which is selected marker is closed, I can't seem to unset class of that layer - it's just gets undefined.
How could I possible solve my issues?
Oh and my map items are kept as a new L.MarkerClusterGroup().
You can try removing the marker from the cluster when it's selected ...
markerCluster.removeLayer(selectedMarker);
map.addLayer(selectedMarker);
and put it back to the cluster when it deselected ...
map.removeLayer(selectedMarker);
markerCluster.addLayer(selectedMarker);
You can see an example here that shows single selection
Each time you create a marker, you add this click handler ...
m.on('click', function(e) {
if(selectedMarker != false) {
map.removeLayer(selectedMarker);
markerCluster.addLayer(selectedMarker);
selectedMarker.setIcon(unselectedIcon);
if(selectedMarker == e.target) {
console.log('clear selection');
selectedMarker = false;
}
else {
console.log('change selection');
selectedMarker = e.target;
selectedMarker.setIcon(selectedIcon);
markerCluster.removeLayer(selectedMarker);
map.addLayer(selectedMarker);
}
}
else {
console.log('new selection');
selectedMarker = e.target;
selectedMarker.setIcon(selectedIcon);
markerCluster.removeLayer(selectedMarker);
map.addLayer(selectedMarker);
}
});
However, I can see 2 downsides:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With