getFeatures() is empty

2020-08-01 07:16发布

问题:

I have a similar question like POI in OpenLayer 3 but not the same.

I'm drawing a map with an KML File:

var layerVector = new ol.layer.Vector({
    source : new ol.source.KML({
        projection : projection,
        url : _url
    }),
});

It works fine and I can see the points from the KML file in the map.

(Using <Style> and <styleUrl> Tags in the KML file.)

But if I try to see the features i get an empty Array.

console.log( layerVector.getSource().getFeatures() );

==> Array [ ]

any idea?

thx mx

回答1:

See the answer in our upcoming FAQ:

https://github.com/openlayers/ol3/blob/master/doc/faq.md

from the above link:

Why aren't there any features in my source?

Suppose you want to load a KML file and display the contained features on the map. Code like the following could be used:

var vector = new ol.layer.Vector({
  source: new ol.source.KML({
    projection: 'EPSG:3857',
    url: 'data/kml/2012-02-10.kml'
  })
});

You may ask yourself how many features are in that KML, and try something like the following:

var vector = new ol.layer.Vector({
  source: new ol.source.KML({
    projection: 'EPSG:3857',
    url: 'data/kml/2012-02-10.kml'
  })
});
var numFeatures = vector.getSource().getFeatures().length;
console.log("Count right after construction: " + numFeatures);

This will log a count of 0 features to be in the source. This is because the loading of the KML-file will happen in an asynchronous manner. To get the count as soon as possible (right after the file has been fetched and the source has been populated with features), you should use an event listener function on the source:

vector.getSource().on('change', function(evt){
  var source = evt.target;
  if (source.getState() === 'ready') {
    var numFeatures = source.getFeatures().length; 
    console.log("Count after change: " + numFeatures);
  }
});

This will correctly report the number of features, 1119 in that particular case.