Leaflet popup doesnt open on the first click

Viewed 2207

I have a function which creates a marker and binds a popup to it. I want the popup to open and close with a single mouse click. What happens is that the popup doesn't open on the first click. Second click and all the subsequent clicks do the job. No errors in the browser console. What can be the problem?

Here's the code:

function addPlace() {
    var myIcon = L.icon({
        iconUrl: 'images/store.png',
        iconSize: [45, 47],
        iconAnchor: [22, 94],
        popupAnchor: [-3, -76],
    });

    var popup1 = L.popup()
        .setLatLng([32.07753, 34.76988])
        .setContent("Best shop<br>Food, drinks and more")

    var shop = L.marker([32.07714, 34.76988], {icon: myIcon})
        .on('click', function() { shop.bindPopup(popup1); })
        .addTo(mymap);
};
1 Answers

You aren't binding the pop up until you click the first time:

var shop = L.marker([32.07714, 34.76988], {icon: myIcon})
    .on('click', function() { shop.bindPopup(popup1); })

The first click binds the pop up, as the pop up isn't bound before the first click, it won't trigger.

The second click now can activate the popup, which is now bound to the marker. This is why it takes two clicks.

You can bind the popup to the layer when you add it, from the API docs:

All layers share a set of methods convenient for binding popups to it.

var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
layer.openPopup(); layer.closePopup();

Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened. (api docs)

Therefore you don't need to actually use an event listener explicitly.

As a result, you should be able to do:

var shop = L.marker([32.07714, 34.76988], {icon: myIcon})
    .bindPopup(popup1)
    .addTo(mymap);

You could keep the current implementation, if you open the popup when it is bound:.on('click', function() { shop.bindPopup(popup1).openPopup(); }), but it seems unnecessary to rebind it each click

Related