jquery - OpenLayers 4 Vector - 附加新功能,但不清除其他功能

标签 jquery ajax openlayers geoserver

我正在使用 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/

相关文章:

javascript - 复选框 : on/off using button

javascript - JSP 代码如何操作 Ajax javascript 代码中的值?

php - 在 &lt;input&gt; 上按 Enter 会提交错误的 <form>(一页上有 2 个表单)

html - 设置 OpenLayers map 容器的尺寸

javascript - OpenLayers/OpenStreetMap 远足自行车 map

javascript - OpenLayer图标用户自由变换

javascript - 将函数放入 td 中

javascript - 如何获取窗口 "right"?

javascript - 仅对 img 进行填充

php - 如何使用jquery序列化进行文件上传