我正在使用 OpenLayers 4 和 Gesoerver 2.12 WFS。我想每 1 秒向矢量源添加新功能并显示在 map 上。
现在,我的问题是如果没有 vectorSource.clear(),我无法添加新功能。
如何在不清除“旧”功能的情况下添加新功能?
我的代码:
var url = "http://localhost:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typename=wfs_geom&propertyName=geometry,id2&sortBy=id2+D&maxFeatures=1&srsname=EPSG:3857&outputFormat=application/json"
var vectorSource = new ol.source.Vector({
projection: 'EPSG:3857',
format: new ol.format.GeoJSON(),
url: url
});
var fetchData = function() {
jQuery.ajax(url, {
dataType: 'json',
success: function(data, textStatus, jqXHR) {
//vectorSource.clear();
console.log(data);
vectorSource.addFeatures(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
updateTimer = setTimeout(function() {
fetchData();
}, 3000);
};
fetchData();
最佳答案
你快明白了。 vectorSource.addFeature(feature);
是正确的方法。
但是,它只接受 ol.Feature对象,而不是原始数据。 VectorSource 的 format
选项仅适用于通过 url 加载,不用于 addFeatures
。
但是将数据转换为特征很容易:
var feature = new ol.format.GeoJSON()({ featureProjection: 'EPSG:3857' }).readFeature(data));
vectorSource.addFeatures(feature);
或阅读多个功能:
var features = new ol.format.GeoJSON()({ featureProjection: 'EPSG:3857' }).readFeatures(data));
vectorSource.addFeaturess(features);
关于jquery - OpenLayers 4 Vector - 附加新功能,但不清除其他功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49925035/