Updating Features in Openlayers 4.x

Let's say you have this following set-up:

var jsonObj = {
        "type": "FeatureCollection",
        "features": [
            {
                "geometry": {
                    "type": "Point",
                    "coordinates": [124.112122, 8.112132]
                },
                "type": "Feature",
                "properties": {
                    "device_id": 138,

                    "data":"old_data"
                }
            }, 

            ...
}

var vectorSource = new ol.source.Vector({
        features: (new ol.format.GeoJSON()).readFeatures(jsonObj)

 });
var vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: pointStyleFunction

});
 ...//other code like adding the layer to the map

setProperties

 Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties).

forEachFeature

Iterate through all features on the source, calling the provided callback with each one. If the callback returns any "truthy" value, iteration will stop and the function will return the same value.
var dev_id = '138';
vectorSource.forEachFeature(function(feat){
    if (dev_id === feat.get('device_id')) {
        feat.setProperties({
            'property1': val1,
            '
property2': val2,
            'property3': val3,

            'data':'new_data'//to update the value           
        })
    }

});

You just need to loop to the source's features then set its properties. Note that if you want to update the value of a certain property, you can just overwrite it.

When you examine the data after, the feature will have 5 properties with the updated value of data.

Popular posts from this blog

Auto-calculate your Splinterlands Assets/Income

Creating a Simple Button for Demo

Splinterlands: Water Deck for Beginners