更新 Leaflet GeoJson 图层并维护选定的功能弹出窗口

Update Leaflet GeoJson layer and maintain selected feature popup

我有一张 leaflet 地图,我正在用来自服务器的新数据刷新它。您可以单击地图功能,然后 popup 将显示该点。每次刷新时,我使用 map.removeLayer 删除 layer,使用 L.geoJson 添加新数据,但弹出窗口消失了。我希望弹出窗口随着新数据保持活动状态。我知道这可能不会像我通过删除 layer 那样工作。是否有另一种方法可以刷新图层数据并保持所选功能弹出窗口?

这是我从服务器获取新数据后调用的刷新函数。

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

这会为每个功能创建弹出窗口

function onEachFeature(feature, layer) {
    if (feature.properties && feature.properties.UserName) {
        layer.bindPopup(feature.properties.UserName);
    }
}

这有效,我跟踪了我在弹出内容中设置的 ID。添加图层后,我存储具有 clickedIdPopup 并对其执行 popupOpen

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
   }
}