Ozi Baldone
Ozi Baldone

Reputation: 1

Leaflet JS: On click a MarkerClusterGroup, check/uncheck a control.layer checkbox

How to check a checkbox of the control.layer when I click on a cluster?

Example: When I click on my cluster "Bosquet Creux" on my map, I want it to check "Bosquet Creux" in my layer control.

My Leaflet Map

Plugin used: MarkersCluster

var Region1 = new L.MarkerClusterGroup({ showCoverageOnHover: false, disableClusteringAtZoom: 4, maxClusterRadius: 300,
iconCreateFunction: function(cluster){
    var Region1 = cluster.getAllChildMarkers();
        var n = null;
        for (var i = 0; i < Region1.length; i++)
            return L.divIcon({ html: n, className: 'Region1', iconSize: L.point(268, 34)});

        Region1.on('click', function(){if (map.hasLayer(Region2)) {map.removeLayer(Region2);}});
}
});

Sorry for my bad English.

Upvotes: 0

Views: 1248

Answers (1)

chrki
chrki

Reputation: 6323

To check for a click on a cluster you can listen to the clusterclick event as explained in the docs. You can then find the checkbox with document.querySelector('#id of checkbox') (or document.getElementById()) and turn it on by setting its value .checked="checked", or turn it off with .checked=false.

Place this code outside of the new L.MarkerClusterGroup() somewhere in your Javascript:

Region1.on('clusterclick', function (a) {
    if (!map.hasLayer(Region2)) {
      map.addLayer(Region2);
      map.removeLayer(Region1);
      document.querySelector('#region1checkbox').checked="checked";
    }
});

Another note: Your Region1.on() in the code you posted is not executed because there's a return statement before it, this will cause the function to return the icon and it will end right there.

Here's a demo: http://plnkr.co/edit/83oEg9tbeAeGwq8ZPPmi?p=preview

Upvotes: 1

Related Questions