0

Inside the ajax callback I have all the features as expected, but I don't have them outside.

What am I missing ?

var geojsonSource = new ol.source.Vector();
$.ajax('assets/data/data.geojson').then(function(response) {
    var geojsonFormat = new ol.format.GeoJSON();
    var features = geojsonFormat.readFeatures(response, {featureProjection: 'EPSG:4326'});

    geojsonSource.addFeatures(features);
    console.log(geojsonSource.getFeatures()); // this work
});
console.log(geojsonSource.getFeatures()); // this doesn't work
kryger
  • 12,906
  • 8
  • 44
  • 65
thiagogcm
  • 103
  • 1
  • 10
  • This is not OpenLayers (or vector source) problem, this is caused because JavaScript is asynchronous and the last line is executed *before* the AJAX handler function is executed (it is only called when the remote data is fully loaded). – kryger Jul 18 '15 at 09:12
  • possible duplicate of [How do you make javascript code execute \*in order\*](http://stackoverflow.com/questions/2637626/how-do-you-make-javascript-code-execute-in-order) – kryger Jul 21 '15 at 08:57

1 Answers1

1

Everything's fine with your snippet. As @kryger said, AJAX is Asynchronous Javascript and XML. So, register a listener to know when your features are added to the source, like:

geojsonSource.on('addfeature', function(event){
    console.log(geojsonSource.getFeatures());

});
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82