John Chrysostom
John Chrysostom

Reputation: 4063

Don't generate map click events when marker clicked in leaflet

So, I have a leaflet map...

var map = L.map('map').setView([35.772219, -78.675272], 17);
map.on('click', function(e) {alert('map click!')});

and I add a marker...

var marker = L.circleMarker([35.772219, -78.675272]);
marker.on('click', function(e) {alert('marker click!')});
marker.addTo(map);

If I click on the marker, both the marker and map click events fire, but I only want the click event for the marker... Is there any way to accomplish this? I can't seem to find one in the docs.

Upvotes: 3

Views: 2038

Answers (3)

nikoshr
nikoshr

Reputation: 33334

L.DomEvent.stopPropagation should do the trick:

Stop the given event from propagation to parent elements. Used inside the listener functions:

marker.on('click', function(e) {
    L.DomEvent.stopPropagation(e);
    console.log('marker click!')
});

And a demo (one circle cancels its event and not the other)

var map = L.map('map').setView([35.772219, -78.675272], 10);
map.on('click', function(e) {console.log('map click!')});


var marker = L.circleMarker([35.772219, -78.68]);
marker.on('click', function(e) {
    L.DomEvent.stopPropagation(e);
     console.log('marker click!')
});
marker.addTo(map);

marker = L.circleMarker([35.772219, -78.63], {fillColor: 'red'});
marker.on('click', function(e) {
     console.log('marker click with map click')
});
marker.addTo(map);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />

<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>

<div id="map" style="height: 100px"></div>

Upvotes: 9

random
random

Reputation: 7891

use event.stopPropagation(), to stop event bubbling to the parent. See stopPropagation.

document.querySelector('.parent').addEventListener('click', () => {
    console.log('Listening parent');
});

document.querySelector('.child').addEventListener('click', (e) => {
    e.stopPropagation();
    console.log('Listening child');
});
<div class="parent">
  parent
  <div class="child">
    child
  </div>
</div>

Upvotes: 0

Palencar
Palencar

Reputation: 159

Have you try to add a e.preventDefault(); and e.stopPropagation() in the function of your marker click? Like so:

marker.on('click', function(e) { e.preventDefault(); e.stopPropagation(); alert('marker click!');});

Upvotes: 0

Related Questions