1

I added a click event to a LayerGroup. But it did not work. I am pasting code below:

const map1 = L.map("map1", {
    center: [11.274, 50.765].reverse(),
    zoom: 10
    });

const mlyr2 = L.layerGroup([
    L.marker([11.274, 50.765].reverse()),
    L.marker([13.537, 49.877].reverse()),
  ]).addTo(map1);


mlyr2.on('click', function(e){
  alert("clicked the layergroup!");
});

The alert is not displayed. Is it that mouse events don't work on layergroups and that we should use featuregroup instead. Further I am using the latest leaflet version

1 Answer 1

0

According to documentation your code should work, but it doesn't. I have no idea why it doesn't work, but there is a simple workaround. Just iterate all the layers of layer group:

mlyr2.eachLayer(function(layer) {
  layer.on('click', function(e){
    alert("clicked the layergroup!");
  });
)};

If you don't like this solution, you'll have to use L.featureGroup, where it's clearly stated in the docs:

Events are propagated to the FeatureGroup, so if the group has an event handler, it will handle events from any of the layers. This includes mouse events and custom events.

1
  • Thanks, I wanted event handler to work on the group as a whole and FeatureGroup worked great.
    – Arun
    Commented Jun 6 at 6:43

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.