[GIS] leaflet onClick add/remove circles

javascriptleaflet

I am using leaflet.
I have a number of circles, and I want to imply a global event listener link for those circles which will add some other circles in one click to any circle, and remove those added circles by the second click.
How is that possible?
grapical description

//the circles which will have an event listener
var circle1 = L.circle([44.6663888888889, 6.775],{radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#ff9900',fillOpacity:1});
var circle2 = L.circle([44.6502777777778, 6.79333333333333], {radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#008000',fillOpacity:1});
...




//create an onClick event targeting circle 1 and 2 to add/remove circle3 and circle4
map.on('click', function(e){...?...});



var circle3 = L.circle([44.6191666666667, 6.81222222222222], {radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#008000',fillOpacity:1});
var circle4 = L.circle([44.6761111111111, 6.795], {radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#008000',fillOpacity:1});
...

Best Answer

If you use map.on() it handles events of map container.

You need to group your circles with L.featureGroup():

// group circles like the ones to be clicked and ones to be shown
var group1 = L.featureGroup();
var group2 = L.featureGroup();
// circles to be clicked
var circle1 = L.circle([44.6663888888889, 6.775],{radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#ff9900',fillOpacity:1}).addTo(group1);
var circle2 = L.circle([44.6502777777778, 6.79333333333333], {radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#008000',fillOpacity:1}).addTo(group1);
// circles to be shown with event
var circle3 = L.circle([44.6191666666667, 6.81222222222222], {radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#008000',fillOpacity:1}).addTo(group2);
var circle4 = L.circle([44.6761111111111, 6.795], {radius: 150, color:'white',weight:.5, opacity:1,fillColor: '#008000',fillOpacity:1}).addTo(group2);
map.addLayer(group1);
// handle event of the group you choosed to be clicked
group1.on('click', function(){
      // check if second group is on the map
      if(map.hasLayer(group2)){
        map.removeLayer(group2);
      }
      else {
        map.addLayer(group2);
      }
    })

Example on JSFiddle