1

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();
    });
}

2 Answers 2

2

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>');
}
0

Just use "layer.unbindPopup()" in front of "layer.bindPopup(...)".
Thank You on extremely helpful question which shows the way for implementation of dynamic popups.

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.unbindPopup();
        layer.bindPopup('<a href="http://some-url-to-call?mktid=' + feature.properties.code + '">' + feature.properties.name + '</a>', {
                                    autoClose:true,
                                    closeOnClick:true
                                  });
        this.openPopup();
    });
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.