start a function when click on circle - leaflet

2019-05-06 17:12发布

问题:

I make some circles in JS as follow:

L.circle(
  [46.765735535841024, 23.58344078063965], 5, {
    color: "blue"
  }).addTo(map).bindPopup("Description: This is my description");

I want to replace that bindPopup with a function. When I click the circle, instead of my description display, I want to run a function, for example I made this function:

function circleClick() {
     // my implementations;
}

Would someone tell me how could I do this possible?

回答1:

Simply assign your circleClick function as listener on each of your circles:

L.circle(
  [46.765735535841024, 23.58344078063965], 5, {
    color: "blue"
  }
).addTo(map).on("click", circleClick);
// more L.circle's...

function circleClick(e) {
    var clickedCircle = e.target;

  // do something, like:
  clickedCircle.bindPopup("some content").openPopup();
}

Alternatively, you can gather all your circles within a Feature Group, and attach the event listener to that group only:

var group = L.featureGroup().addTo(map);

L.circle(
  [46.765735535841024, 23.58344078063965], 5, {
    color: "blue"
  }
).addTo(group);
// more L.circle's...

group.on("click", function (e) {
    var clickedCircle = e.layer; // e.target is the group itself.

  // do something, like:
  clickedCircle.bindPopup("some content").openPopup();
});


回答2:

You just need to assign the circle to a variable and then listen to click event.

var circle = L.circle(...).addTo(map);

circle.on('click', function (e) {
    alert("Hello, circle!");
});