zsoooc
zsoooc

Reputation: 133

OpenLayers 4 Vector - append new features, but without clearing others

I'm using OpenLayers 4 with Gesoerver 2.12 WFS. I would like to add new features in every 1 second to the Vector Source and display on the map.

Now, my problem is that I can't add new features without the vectorSource.clear().

How can I add the new features without clearing the "old" features?

My code:

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();

Upvotes: 1

Views: 1394

Answers (1)

dube
dube

Reputation: 5039

You almost got it. vectorSource.addFeature(feature); is the correct method. However, it only accepts ol.Feature objects, not raw data. The format option of the VectorSource only applies to loading via url, it is not used for addFeatures.

But transforming the data to features is easy:

var feature = new ol.format.GeoJSON()({ featureProjection: 'EPSG:3857' }).readFeature(data));
vectorSource.addFeatures(feature);

or reading multiple features:

var features = new ol.format.GeoJSON()({ featureProjection: 'EPSG:3857' }).readFeatures(data));
vectorSource.addFeaturess(features);

Upvotes: 3

Related Questions