OpenLayers – Access All Features of Vector Layer (GeoJSON)

geojsonopenlayers

For another project I need to compare the feature attributes from a GeoJSON layer with a given user input.

As a first step I created a basic map based on the OpenLayers Example and simply tried to get all features from the GeoJSON layer as an array.

 //def vectorLayer
  const vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
      url: 'https://openlayers.org/data/vector/ecoregions.json',
      format: new ol.format.GeoJSON(),
    }),
    style: new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#501020',
        width: 1
      })
    })
  });
  
  //def map
  const map = new ol.Map({
    layers: [vectorLayer],
    target: 'map',
    view: new ol.View({
      center: [0, 0],
      zoom: 2,
    }),
  });

//get simple array with all features
var vectorSource = vectorLayer.getSource();
console.log(vectorSource.getFeatures());

The source.getFeatures() method should return all features from the source as an array.
In my case the result is an empty array [].

So can I access the features from the vectorLayer?
I prepared a working jsfiddle for better understanding.

Best Answer

Since you are loading GeoJSON from web, operation is async, which means you have to wait till features are loaded before you try to use them. To detect when features are loaded you can use layer source featuresloadend event.

Code could then look something like this:

const vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/data/vector/ecoregions.json',
    format: new ol.format.GeoJSON(),
  }),
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: '#501020',
      width: 1
    })
  })
});

const vectorSource = vectorLayer.getSource();
vectorSource.on('featuresloadend', function() {
  console.log(vectorSource.getFeatures());
});

const map = new ol.Map({
  layers: [vectorLayer],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2,
  }),
});

And by the way, in your JSFiddle you are using OL 3.20.1, for which the above code wouldn't work. You have to use the latest OL.

Related Question