如何修改或删除GeoJSON Leaflet对象中的一些现有数据?

时间:2016-10-05 20:29:25

标签: javascript dictionary leaflet geojson

最近我询问了referencing the data of an existing GeoJSON Leaflet object。我的Leaflet地图包含流入我的GeoJSON Leaflet对象的数据。用户输入可以更改GeoJSON数据的过滤器,因此要使过滤器同时应用于现有数据和新数据,我会在名为myFeatures的数组中跟踪我的数据。每当过滤器更改或myFeatures中的项目发生更改时,我都会执行以下操作:

myGeoJson.clearLayers();
myGeoJson.addData(myFeatures);

这样可以根据最新更新的要素数据或过滤器中的更改来更新地图。

我在初始化GeoJSON对象时将弹出窗口应用于GeoJSON对象:

var myGeoJson = L.geoJson(myFeatures, {
  style: function(feature) {
    ...
  },

  pointToLayer: function(feature, latlng) {
    return L.circleMarker(latlng, geojsonMarkerOptions);
  },

  filter: function(feature, layer) {
    ...
  },

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

当我点击单个功能时,会出现弹出窗口。但是,由于clearLayersaddData被调用,弹出窗口很快就会消失。 :(

在这种情况下,是否有某种方法可以阻止弹出式解雇?

或者 - 更好的问题 - 有没有办法修改GeoJSON对象中的现有数据或从GeoJSON对象中删除一些(不是全部)数据?

为了提供一些上下文,我的GeoJSON显示了每个要素的圆圈标记。圆形标记基于特征的属性着色。该属性实际上可以随时间变化,因此标记的样式需要更新。标记也会在一段时间后超时,需要从地图中删除,但其他标记需要保留在地图上。

1 个答案:

答案 0 :(得分:1)

确实有更好的方法可以做到这一点,但是如果你不想过多地修改你的代码架构,你可以在特定的层中创建弹出窗口,当你添加新的时,你不会清楚数据

为了给你一个想法(标记在你的例子中扮演myGeoJson的角色):

var popup_id = {};
var popup_layer = new L.layerGroup();
var markers = new L.layerGroup();

$.each(testData, function(index, p) {
   var marker = L.marker(L.latLng(p.lat, p.lon));
   markers.addLayer(marker);
   popup = new L.popup({offset:  new L.Point(0, -30)});
   popup.setLatLng(L.latLng(p.lat, p.lon));
   popup.setContent(p.text);
   popup_id[p.id] = popup;
   marker.on('click', function() {
      popup_id[p.id].openPopup();
      popup_layer.addLayer(popup_id[p.id]);
      markers.clearLayers();
   })
});

popup_layer.addTo(map);
markers.addTo(map);

您还可以在字典popup_id中跟踪所有弹出窗口。 既然你还没有为我们提供JSfiddle,那么找到你的案例的完美答案有点困难,但我希望弹出层(也是here in my fiddle)给你一个很好的指导。