Fullhdpixel
Fullhdpixel

Reputation: 813

LeafletJS: prevent clicking on map when clicking on circlemarker

I have a leaflet map and there is both an event attached to the map (click) and an event attached to the circlemarker (click). Now I want to change the color of the circlemarker, but the trouble is that the event of the map fires as well and this is interfering with the logic of the circlemarker click.

How do I prevent the map event from firing when clicking on the circlemarker?

var circleMarker = L.circleMarker([point.lat, point.lng], {
  radius: 8,
  fillColor: "#ff0097",
  color: "#000",
  weight: 1,
  opacity: 1,
  fillOpacity: 0.8
}).addTo(drawmap);

circleMarker.on("click", function(e) {
  e.originalEvent.preventDefault(); //This does not work
  circleMarker.setStyle({ fillColor: '#1b1b1b' });
});


drawmap.on('click', function(e) {
//something unrelated
}

Upvotes: 4

Views: 1934

Answers (2)

Tim Headley
Tim Headley

Reputation: 113

Late entry:

In the Leaflet docs there is an option when creating a marker, bubblingMouseEvents, that allows for the prevention of event propagation. This works when creating a circleMarker too.

So in your case:

var circleMarker = L.circleMarker([point.lat, point.lng], {
  radius: 8,
  fillColor: "#ff0097",
  color: "#000",
  weight: 1,
  opacity: 1,
  fillOpacity: 0.8,
  bubblingMouseEvents: false
}).addTo(drawmap);

Upvotes: 3

Adam Paxton
Adam Paxton

Reputation: 1432

Not seeing a way to handle this internally within Leaflet's event object. Perhaps you can track with an external flag:

var isCircleEvent = false;
circleMarker.on("click", function (e) {
    circleMarker.setStyle({ fillColor: '#1b1b1b' });
    isCircleEvent = true;
});


drawmap.on('click', function (e) {
    if (isCircleEvent) {
        //reset the flag and return;
        isCircleEvent = false;
        return;
    }
    //something unrelated
}); 

Upvotes: 3

Related Questions