1

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.

1 Answer 1

3

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.

2
  • vectorSource.once('change', will work with old versions jsfiddle.net/zwgphfnu but beware that trying to log hundreds of features in jsfiddle is likely to lock the browser!
    – Mike
    Nov 29, 2022 at 17:29
  • For the original project I'm currently using OL 6.14.1. The featuresloadend event works fine. Thank you!
    – themojave
    Nov 30, 2022 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.