0

I am using the Leaflet markercluster plug in, and now want to add a button to turn the clustering on/off. For that I wanted to use the leaflet button plug in, because I am already using it in my code.

I tried around with this piece of code and customized the lines with "sidebar" in it.

var button = new L.Control.Button('Toggle me', {
toggleButton: 'active'
});
button.addTo(map);
button.on('click', function () {
if (button.isToggled()) {
    sidebar.hide();
} else {
    sidebar.show();
}
});

I also have an overlay where I want to implement those layers then.

How I cluster my markers:

var extern2 = L.markerClusterGroup();
extern2.addLayer(extern);
1

1 Answer 1

2

You have two layers, where extern layer contains original markers and extern2 contains clustered markers. What you have to do in toggle control is just to add one layer to the map and remove the other.

Assuming that initially plain markers (non clustered) are shown, code could look something like this:

var extern2 = L.markerClusterGroup();
extern2.addLayer(extern);

map.addLayer(extern);

var button = new L.Control.Button('Show clusters', {
  toggleButton: 'active'
});
button.addTo(map);

button.on('click', function () {
  var txt;
  var controlElement = button.getContainer();
  if (button.isToggled()) {
    txt = 'Show clusters';
    map.removeLayer(extern2);
    map.addLayer(extern);
    }
  else {
    txt = 'Show markers';
    map.removeLayer(extern);
    map.addLayer(extern2);
  }
  controlElement.innerHTML = txt;
});    
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.