christiansr85
christiansr85

Reputation: 877

How to represent a feature outside an OpenLayers 4 cluster?

I am working with OpenLayers angular dependency, actually, I'm uing v4.1.1 and, at current' I can't update it to the latest version.

I have a map with an ol.source.Cluster. It clusterizes all my ol.layer.Vector layers, which are composed by pushpin features, similar to this example.

The features in my application can be selected by the user. This action highlights the single specified feature and zooms the map in to the feature in order to let user know which one is selected. My problem arises when the feature is clusterized; I would like that the feature could be rendered outside the cluster, and that it could be added again to a cluster when it is unselected. Is this possible easily? I have read the documentation of the involved classes, ol.source.Cluster and ol.source.Vector (I know they are v4.6.5 but I didn't find the v4.1.1) and perhaps I'm skipping something or maybe you know a way to do this.

I have tried two solutions, but I don't like very much:

    let clusterSource = new ol.source.Cluster({
       distance: 40,
       source: vectorSource,
       geometryFunction: (feature) => {
           if (feature.get('selected')) {
               return null;
           }
           return feature.getGeometry() as ol.geom.Point;
       }
    });

So, to sum up, is there a way to remove a feature from a cluster and represent it individually along with the clusters?

Upvotes: 0

Views: 538

Answers (1)

christiansr85
christiansr85

Reputation: 877

Finally, as I didn't find anything in the OpenLayers 4 API to easily reach my goal, I implemented the auxiliar layer's approach. Just as remainder, I clusterize all the pushpins under the same source (those pushpins represent entities of diferent types so each type can be displayed/hidden individually). But when I select a single entity, I stop clusterizing it through the geometryFunction of the cluster source and clone it in the auxiliar layer, displaying in the map it as a single selected feature (with a specific style).

Because a set of pushpins can be excluded from being clustered when user modifies its visibility, through a sublayer specific for each type of entity, I've created an auxiliar layer for each one of these sublayers, so when their visibility is modified I modify the visibility of its auxiliar layer along with it, in order to hide/display the single feature.

To reach this I created a js class which inherits from ol.layer.Vector in order to extend its functionality, to add what I need.

As I did this in a legacy code, which is more complex than the goal I explained here, it's a little complicated to paste code snippets as examples, because I should have to remove a lot of not useful lines and perhaps it wouldn't be correct at all. So if you have any specific question I could explain it better.

Upvotes: 0

Related Questions