[GIS] Disable selection of clusters OpenLayers 3

openlayers

At the moment I have my OpenLayers 3 map set up to cluster icons upon zooming out. I want to disable the ability to select clusters but allow the user to select individual markers if they zoom in. Preferably, clicking on a cluster could select each individual feature in the cluster (in their correct locations). My select code is like so:

var selectClick = new ol.interaction.Select({
    condition: ol.events.condition.click,
    style: selectedMarkerStyle,
    addCondition: function(mapBrowserEvent){
        var features = null;
        map.forEachFeatureAtPixel(mapBrowserEvent.pixel, function (feature_, layer) {
            features = feature_.values_.features;
        });
        if(features !== null && features.length > 1){
            return false;
        }
        return true;
    }
});
map.addInteraction(selectClick);

However the addCondition doesn't seem to be working. At the moment clicking on a cluster selects one of the features in the cluster, in the location of the cluster, rather than the features correct location.

Is there any way to fix this?

Best Answer

It's been a while but I stumbled upon the same problem. Your code helped me a lot, this is the solution I came up with (not that I'm using typescript, to convert it to JS remove the types after the variables):

Here is my code:

// create the select interaction
var select = new ol.interaction.Select({
    style: styleClick,
    condition: function (mapBrowserEvent) {
        // check if it is a click event
        if (!ol.events.condition.singleClick(mapBrowserEvent))
            return false;

        // collect all the features at the click event
        var features = [];
        self.map.forEachFeatureAtPixel(mapBrowserEvent.pixel, function (feature_, layer) {
            var features_ = feature_.get('features');
            // get all the features in that place
            for (let i = 0; i < features_.length; i++)
                features.push(features_[i]);
        });
        // check if one or more featres on this place (a cluster always contains multiple features!)
        if (features !== null && features.length > 1) {
            return false;
        } else if (features.length === 1) {
            // trigger the callback for the selected feature (best place I found, since the  ol.interaction.Select doesn't seem to have a change event)
            // YOURCALLBACK FKT (e.g. callback(features[0])
            return true;
        }

        // default exit rout
        return false;
    }
});
this.map.addInteraction(select);
Related Question