Sergio
Sergio

Reputation: 668

openlayers 4 get features from ol.layer.Vector

I'm new to OpenLayers, so I'm kind of lost here. I'm trying to get all features from a kml vector layer, but I haven't been able to do it. I just don't understand what am I doing wrong.

Here's my code:

var vector2 = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: './energeticos.kml',
        format: new ol.format.KML()
    })
});

var features = vector2.getSource().getFeatures();
alert(features.length); //this alerts '0', but there's more than 50 features!!

for (var i in features) {
    var feature = features[i];
    var featureName = feature.get('name');
    $("#containerLeft").append('<li>' + featureName + '</li>');
}

the kml layer is properly displayed on the map, and as it's mentioned in the code, when I use the getFeatures function, it doesn't get anything.

any help will be really appreciated.

P.S. I'll try to get some sleep, so I'll be back in a few hours.

Upvotes: 0

Views: 4501

Answers (2)

Lucien
Lucien

Reputation: 129

You can type vector2.getSource().getFeatures() individually on Console. Seems like rendering KML is asynchronous.

Upvotes: 0

Sergio
Sergio

Reputation: 668

I've just found a solution here:

getFeatures() is empty

I had to add an event listener since the loading of the KML-file will happen in an asynchronous manner, as it's explained in that answer.

Upvotes: 1

Related Questions