OpenLayers 6 – How to Set and Modify Change Event on a Feature

featuresopenlayers

I created an onChange feature event and each time I drag the feature over the map, it console.log its properties.

var newFeature = new ol.Feature({
   geometry: new ol.geom.Point(e_coordinate),
   property: 1
});
newFeature.setId(33);
source.addFeature(newFeature);

I change the property as follows

source.getFeatureById(33).values_.property=2

And if I console.log the property I get 2, which is correct

Finally I add the on change event on the feature

newFeature.on('change',
  function () {
    try {
         console.log("on change props -->" + props);
    } catch (error) {
         alert('feature on change error 2\n' + error);
    }
  },
  newFeature
); 

The problem appears when I drag the feature over the map. It keeps logging the previous value (1) and not the latest one (2). Is there any way to reset the new property some how inside the on change event?

Am I missing something?

Best Answer

Features properties are useally a key-value pair ( {color : 'red'}) and modifications can be made with setProperties method

var newFeature = new ol.Feature({
  geometry: new ol.geom.Point(e_coordinate),
  property: {custom_val : 1}
 });

And modifying properties :

source.getFeatureById(33).setProperties({custom_val:2});