[GIS] OpenLayers: GeoJSON Vector-Layer refresh / redraw every second

openlayers

I do not get to move the Vector Layer in my OpenLayers script. The layer should be renewed every second. I have already tried a lot, like refresh() and redraw() or OpenLayers.Strategy.Refresh, but nothing has worked for me.

The GeoJSON-"polygon" should be re-layered every second.

Here is a JSFiddle:
https://jsfiddle.net/ejts8foc/4/

Best Answer

In your case you call the _compute() function just once when page is loaded that's why Geojson coordinates are not updated every second.
Add this function at the end:

 setInterval(function(){ 
        source.clear();
            geojsonObject = {
            'type': 'FeatureCollection',
            'crs': {
              'type': 'name',
              'properties': {
                'name': 'EPSG:4326'
              }
            },
            'features': [{
              'type': 'Feature',
              'geometry': {
                'type': 'Polygon',
                'coordinates': [_compute()]
                }}]
          };
      source.addFeatures((new ol.format.GeoJSON()).readFeatures(geojsonObject,{featureProjection: 'EPSG:3857'}));
    source.refresh();
    },1000);

The function creates Geojson Object every second with new coordinates and updates the layer. Here is the working Fiddle: https://jsfiddle.net/ygh249ur/