问题
We have a Leaflet Map which we are trying to build using GeoJSON. Our data comes in from a live stream, so we start out by initializing the GeoJSON with empty data:
var myLayer = L.geoJson([], {
style: function(feature) {
var color = getDataband(LATENCY_BANDS, feature.properties.latency).color;
return {
fillColor: color
};
},
pointToLayer: function(feature, latlng) {
return L.circleMarker(latlng, geojsonMarkerOptions);
},
filter: function(feature, layer) {
var latency = feature.properties.latency;
for (var i = 0; i < ENABLED_LATENCY_BANDS.length; i++) {
if (ENABLED_LATENCY_BANDS[i].contains(latency)) {
return true;
}
}
return false;
}
});
Then we add the data points one by one as messages come in from the live stream by calling:
var geojsonFeature = {
"type": "Feature",
"properties": {
"latency": sample.latency
},
"geometry": {
"type": "Point",
"coordinates": [location.longitude, location.latitude]
}
};
myLayer.addData(geojsonFeature);
However, our filter dynamically changes based on user input. Therefore, we need to remove all existing data and re-add all data to the map whenever the user input changes in order for the new filter to apply to all existing and new data. We tried calling the following whenever the user input changes:
map.removeLayer(myLayer);
myLayer.addTo(map);
However, when myLayer
is re-added to the map, the old data are wiped out and only new data appear.
It seems like we should be re-initializing the myLayer
object before we call myLayer.addTo(map)
, but we don't know how to re-initialize myLayer
with the existing feature data. Documentation does not explain how to reference the data of the GeoJSON leaflet object.
How do we reference the data of a GeoJSON leaflet object?
Thanks.
回答1:
The filter option has effect only at instantiation and when using .addData()
method. Furthermore, when a feature is filtered out, it is not just "hidden", it is not recorded in memory (i.e. not within that group).
It is strange that your old data is wiped out by removing the group and adding it back to the map, should you have changed the filter conditions or not.
Anyway, there is probably no documentation about how to "reference the data of the GeoJSON Leaflet object" in the sense that you are trying to achieve, because it is implementation dependent.
In your case, you would need to accumulate your features in a hidden group / array, so that whenever your filter conditions change, you can re-evaluate these features through the new filter.
For example, you could do something like:
var accumulatedFeatures = [];
// When data arrives
accumulatedFeatures.push(geojsonFeature);
myLayer.addData(geojsonFeature);
// When filter conditions change
myLayer.clearLayers(); // http://leafletjs.com/reference-1.0.0.html#layergroup-clearlayers
myLayer.addData(accumulatedFeatures); // Re-evaluate all data through new filter
来源:https://stackoverflow.com/questions/39776919/how-to-reference-the-data-of-an-existing-geojson-leaflet-object