getFeatures() is empty

◇◆丶佛笑我妖孽 提交于 2019-12-04 21:10:39

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!