OpenLayers – How to Fire Select Event Only When Adding a Feature

interactionopenlayersselect

So I have various Points (comments) across a map on a comments layer and I have a select interaction which is used to show a text popup when the comments point is selected. When I select a point once, it works as it is supposed to. However, if I click anywhere else on the map after that, the select event still gets fired when it is not supposed to since I have used filter for the select interaction to select only the comments layer. Any idea what is causing this problem?

let select = new ol.interaction.Select({
    layers: [commentsLayer]
    style: commentsLayerStyle,
})

map.addInteraction(select);

select.on('select', function (e) {
    const comment = select.getFeatures().item(0).getProperties().comment
    if (comment) {
        const content = document.getElementById('popup-content')
        content.innerHTML = comment;
        commentOverlay.setPosition(e.mapBrowserEvent.coordinate);
    }
})

EDIT:

I have realized the issue. The on select event is getting fired for de-selection of features too (clicking outside of the filtered layer). So I need to figure out a way for the on select event to fire only when a feature is selected and not when it is deselected. Does it have anything to do with addCondition option of Select?

Best Answer

When you do select.on() the event agets registered to the map as Active. There is method to getActive getActive() state on map base on that boolean value you have to setActive() setActive so that map interaction gets disabled once the action is complete. So it will get back to its normal state.

Related Question