thiagogcm
thiagogcm

Reputation: 103

Openlayers 3 vector source issue

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

Upvotes: 0

Views: 276

Answers (1)

Jonatas Walker
Jonatas Walker

Reputation: 14150

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());

});

Upvotes: 1

Related Questions