2
votes

I have a leaflet map which I am refreshing with new data from the server. You can click on the map feature and a popup will show for the point. Every time the refresh happens, I remove the layer using map.removeLayer, add the new data using L.geoJson, but the popup goes away. I want the popup to stay active with the new data. I know this probably won't work the way I'm doing it by removing the layer. Is there another way to do this that will refresh the layer data and maintain the selected feature popup?

This is the refresh function that I call after I get the new data from the server.

function refreshMapLocations() {
    map.removeLayer(locationLayer);    
    locationLayer = L.geoJson(locations, {
        onEachFeature: onEachFeature
    }).addTo(map);  
}

This creates the popup for each feature

function onEachFeature(feature, layer) {
    if (feature.properties && feature.properties.UserName) {
        layer.bindPopup(feature.properties.UserName);
    }
}
1
Save the ID of the selected feature before refreshing your layer, then open the popup programmatically after refreshing you layer. Would it solve your problem. As keeping the popup open while removing the feature doesn't make sense.muzaffar
That was my thought on it if there wasn't a way for the leaflet API to do it.Heinrich

1 Answers

0
votes

This worked, I keep track of an id that I set in the popup content. After the layer is added I store the Popup that has the clickedId and do popupOpen on that.

var popupToOpen;
var clickedId;

function onEachFeature(feature, layer) {
    if (feature.properties && feature.properties.UserName) {
        if (feature.properties.MarkerId == clickedId) {            
            layer.bindPopup("div id='markerid'>"+feature.properties.MarkerId+"</div>feature.properties.UserName);
        } else {
            layer.bindPopup("div id='markerid'>"+feature.properties.MarkerId+"</div>feature.properties.UserName);
        }
    }
}

function refreshMapLocations() {
    map.removeLayer(locationLayer);    
    locationLayer = L.geoJson(locations, {
        onEachFeature: onEachFeature
    }).addTo(map);  

    if (popupToOpen != null) {
        popupToOpen.openPopup();
    }
}

function initMap() {
    ...
   map.on('popupopen', function (e) {
      ...
      //clickedId = id from event popup
   }
}