Daniele Navarra
Daniele Navarra

Reputation: 159

Leaflet: Add event to marker?

I tried to add a click event to a leaflet marker like this:

L.marker([41.866056100409044, 12.5349304759025576]).on('click', red).bindLabel('kebabbari (Ali Baba)', {noHide: true}).addTo(map).showLabel();

But the result is just a marker without any click event (the "red()" function exists)
Marker in leaflet, click event doesn't work

Upvotes: 0

Views: 7130

Answers (1)

Andy Donegan
Andy Donegan

Reputation: 915

Just ran multiple tests with different scenarios and they all worked with an onclick or mouseover. I'm using Leaflet 1.03 I think your using the previous version.

var Marker = L.marker([41.866056100409044, 12.5349304759025576]).on('click', onClick).addTo(map)

Add a new function like below :-

function onClick(e) {
    alert(this.getLatLng());
}

Try this and it will prove your onclick function can work. I think the leaflet Plugin Label might be interfering with it as it has an Onclick option and you may need to look further into that.

But sometimes you need to prove you can make it work first and then add things back in bit by bit.

Also Leaflet.Label does have a conflict with onclick.

https://github.com/Leaflet/Leaflet.label/issues/132 This issue from the forum will help you out they have answer detailed on here.

You need to specifically bind an event to marker.label , e.g.:

L.DomEvent.addListener(marker.label, 'click', function(e) { this.togglePopup() }, marker);

I had to dig in to the code a bit to figure this out, worth a mention in the README on how to access the label and bind events to it.

Upvotes: 2

Related Questions