OpenLayers – Deleting Selected Feature on Alt+Click

featuresopenlayers

Im trying to delete a feature on alt+click. The alt+click code works since i can print out the feature when i click on it. But, i thought i could simply remove it by using source.removeFeature(feature) but I cannot get it to work.

const selectAltClick = new Select({
  condition: function (mapBrowserEvent) {
    return click(mapBrowserEvent) && altKeyOnly(mapBrowserEvent);
  },
});

let select=selectAltClick;
map.addInteraction(select);

select.on('select', (e)=>{
  console.log(e.selected)
  vectorSource.removeFeature(e.selected);
})

My error:

Vector.js:1041 Uncaught TypeError: Cannot read properties of undefined (reading 
'forEach')
at VectorSource2.removeFeatureInternal (Vector.js:1041:41)
at VectorSource2.removeFeature (Vector.js:1030:10)
at Select2.<anonymous> (main.js:256:16)
at Select2.Target2.dispatchEvent (Target.js:111:13)
at Select2.handleEvent (Select.js:537:12)
at Map2.PluggableMap2.handleMapBrowserEvent (PluggableMap.js:1073:34)
at MapBrowserEventHandler2.Target2.dispatchEvent (Target.js:111:13)
at MapBrowserEventHandler2.emulateClick_ (MapBrowserEventHandler.js:134:10)
at MapBrowserEventHandler2.handlePointerUp_ (MapBrowserEventHandler.js:210:12)

I´ve tried this as well
vectorSource.removeFeature(e.selected[0])


I found that my problem was that i had to remove my interactions for snapping and modifying before I can altclick on the feature to delete it. It now works.

Best Answer

If you look at the docs https://openlayers.org/en/latest/apidoc/module-ol_interaction_Select.SelectEvent.html for select interaction select event, you'll see that e.selected is an array of all selected features, so in your case you need to refer to the first element of the array to remove selected feature:

vectorSource.removeFeature(e.selected[0]);

Here is working JSFiddle: https://jsfiddle.net/TomazicM/s9Lo6a8v/