Akansha
Akansha

Reputation: 943

Modifying values of existing layer in OpenLayers 3

I am adding a marker on the map using ol3 by calling the following function

function addmarker(lat, long, flag) {

            iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.transform([+long, +lat], 'EPSG:4326', 'EPSG:3857')),
                name: 'NULL'
            });

            iconStyle = new ol.style.Style({

                fill: new ol.style.Fill({
                    color: '#008000'
                }),
                stroke: new ol.style.Stroke({
                    color: '#008000',
                    width: 3
                }),
                image: new ol.style.Circle({
                    radius: 6,
                    fill: new ol.style.Fill({
                        color: '#008000'
                    })
                })

            });

            iconFeature.setStyle(iconStyle);

            vectorSource[flag] = new ol.source.Vector({
                features: [iconFeature]
            });

            vectorLayer[flag] = new ol.layer.Vector({
                source: vectorSource[flag]
            });

            map.addLayer(vectorLayer[flag]);

        }

And to change the marker position, I am removing the layer and adding a new layer again

 function changemarker(lat, long, flag) {

             vectorSource[flag].clear();

            map.removeLayer(vectorLayer[flag]);

            addmarker(lat, long, flag);

        }

I am facing performance issues as I am changing the marker that is calling the changemarker method every 500 milliseconds. Can a layer be modified without removing it or is there a better approach that can be followed.

Please help.

Upvotes: 0

Views: 719

Answers (2)

user4773894
user4773894

Reputation:

If you set an ID on a feature ol.Feature.setId(<your id>) you can change it directly like so:-

//Setting up your feature 
iconFeature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.transform([+long, +lat], 'EPSG:4326', 'EPSG:3857')),
    name: 'NULL'
});

iconFeature.setId('feature1');

Then

var myFeature = vectorSource.getFeatureById('feature1');

myFeature.getGeometry().setCoordinates(ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857'));

That should update the feature immediately without any redraw calls - OL redraws the layer when a feature is updated. Using this approach I'm displaying several hundred features with complex geometries on-screen with no major speed penalty.

Upvotes: 1

oterral
oterral

Reputation: 471

If you have only one feature in your layer, you can modify directly the geometry of your feature:

function changemarker(lat, long, flag) {

  vectorSource[flag].getFeatures()[0].getGeometry().setCoordinates(ol.proj.transform([+long, +lat], 'EPSG:4326', 'EPSG:3857'));
}

Upvotes: 0

Related Questions