Search code examples
javascriptleaflet

Leaflet open a popup on marker click from GeoJSON layer


I have made a leaflet map. Data is loaded using GeoJSON on the onEachFeature event I have bound the popup with a dynamic content text taken from some property of the feature.

The problem is that with the code I've written the popup is shown only on the first click, then I click again on the same marker it doesn't show up.

here is the code:

function showMarkets() {
    $.ajax({
        url: '/API/GetMarketsWithStatus',
        dataType: 'json',
        async: true,
    }).done(function (geoData) {
        mapLayers.markets = L.geoJSON(geoData, {
            onEachFeature: onEachMarketFeature
        }).addTo(map);
    });
}
function onEachMarketFeature(feature, layer) {
    layer.on('click', function (e) {
        layer.bindPopup('<a href="http://some-url-to-call?mktid=' + feature.properties.code + '">' + feature.properties.name + '</a>');
        this.openPopup();
    });
}

Solution

  • Bind your popup when the feature is created, not when the user clicks on it, Leaflet will handle the click events for you:

    function onEachMarketFeature(feature, layer) {
        layer.bindPopup('<a href="http://some-url-to-call?mktid=' + feature.properties.code + '">' + feature.properties.name + '</a>');
    }