0

I'm upgrading from a much earlier version of Openlayers, and just can't seem to figure out how to get all of the features in a vector layer.

For context what my ultimate goal is, is to set the visibility on each feature based on certain data criteria - so if there is another way to do that I would be interested in that too.

My code is:

pointType is an internal reference string to allow me to differentiate between layers / data. All of my layers have it as a key.

public getFeatures(pointType: string): any {
    const layer = this.getLayer(pointType);
    const source = layer.getSource();

    const features = null; //source.getFeatures();

    return features;
}

private getLayer(pointType: string): Layer {
    const layers = this.getLayers();
    for (let l = 0; l < layers.length; l++) {
        if (pointType === layers[l].get("pointType"))
            return layers[l];
    }
    return null;
}

private getLayers(): Layer[] {

    if (!this.map)
        return null;

    return this.map.getAllLayers(); // this.map is typeof ol/Map
}

The Layer I get back is of type Vectorlayer and the Source is VectorSource - So I think I'm close. But I can't seem to figure out how to make that last jump to the actual features.

Any help would be appreciated!

EDIT: Additional info.

source.getFeatures() results in the error:

Error TS2339 (TS) Property 'getFeatures' does not exist on type 'Source'.

source is from ol/source/Source - do I need to convert / cast this to ol/source/Vector - somehow?

EDIT2: Simple fix! Just cast it to VecorSource

const features = (source as VectorSource).getFeatures();

Morvael
  • 3,478
  • 3
  • 36
  • 53
  • 1
    `source.getFeatures()` is correct, but features may be loaded on demand, so whether all the features are available will depend on the visibility of the layer and how the source is loaded. – Mike Sep 29 '22 at 11:58
  • Thanks @Mike Adding info to the question regarding `source.getFetaures()` – Morvael Sep 29 '22 at 12:14

1 Answers1

1

Thanks to @Mike (see comments) I worked out that all I needed to do was cast ol/source/Source to ol/source/Vector to fix the issue.

Complete getFeatures() code:

public getFeatures(pointType: string): any {
    const layer = this.getLayer(pointType);
    const source = layer.getSource();

    const features = (source as VectorSource).getFeatures();

    return features;
}
Morvael
  • 3,478
  • 3
  • 36
  • 53