OpenLayers – Step-by-Step Guide on Removing a Layer Property in OpenLayers Projects

openlayers

I am working on a digitizing application that also lets users delete a layer’s attribute (i.e. properties) by selecting a property from a dropdown.

The workflow: a user selects a feature (someFeature) by clicking it on the map and selects a property of that feature in a dropdown (removeProperty).
Now removeProperty should be removed from someFeature.

var features = layer.getSource().getFeatures();

features.forEach(function (feature) {

    if (feature === someFeature) {

        var properties = feature.getProperties();

        for (var prop in properties) {

            if (properties.hasOwnProperty(prop)) {

                if (prop === removeProperty) {

                    delete feature.getProperties()[prop];

                }

            }
        }

    }

});

The problem is that the line delete feature.getProperties()[prop]; does not work to achieve this as getProperties() seems to simply return a new object from which the key is then deleted (instead of being deleted from the actual layer).

Using setProperties by assigning an object without the selected key also does not work as setProperties, as stated in the docs changes any existing properties and adds new ones (it does not remove any existing properties).

So, how can I remove a property?

Best Answer

Instead of

delete feature.getProperties()[prop];

you just need to use the following

feature.unset(prop);

For the docs reference, go to https://openlayers.org/en/latest/apidoc/module-ol_Object-BaseObject.html#unset