Search code examples
javascriptopenlayers-3

How do I get features from a geoJson load?


I've got some GeoJson loading into an openlayers 3 vector layer

var countriesLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: '/data/countriesandstates.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature, resolution) {
    countriesLayerTextStyle.getText().setText(resolution < 5000 ? feature.get('name') : '');
    return [countriesLayerStyle, countriesLayerTextStyle];
  }
});

I want to run over all the features in that source using

countriesLayer.getSource().forEachFeature(...);

However it never calls my callback, and if I try getFeatures() I get an empty array back. However it renders just fine so I know the data is loaded. I even tried doing in 5 seconds later on a timeout to make sure it was loaded and parsed.

What am I doing wrong?


Solution

  • This seems to work:

    countriesLayer.getSource().on("change", function(ev) {
        if( countriesLayer.getSource().getState() === "ready" ) {
            console.log(countriesLayer.getSource().getFeatures().length)
        }
    });