getFeatures()为空

0 kml openlayers-3

在OpenLayer 3中有类似POI的问题,但不一样.

我正在使用KML文件绘制地图:

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

它工作正常,我可以在地图中看到KML文件中的点.

(Using <Style> and <styleUrl> Tags in the KML file.)
Run Code Online (Sandbox Code Playgroud)

但是,如果我试图看到我得到一个空数组的功能.

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

==> Array [ ]
Run Code Online (Sandbox Code Playgroud)

任何的想法?

thx mx

bar*_*vde 8

请参阅我们即将推出的FAQ中的答案:

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

从以上链接:

为什么我的源代码中没有任何功能?

假设您要加载KML文件并在地图上显示包含的功能.可以使用以下代码:

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

您可能会问自己KML中有多少功能,并尝试以下内容:

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);
Run Code Online (Sandbox Code Playgroud)

这将记录源中的0个要素的计数.这是因为KML文件的加载将以异步方式进行.要尽快获取计数(在获取文件并且源已填充功能之后),您应该在源上使用事件侦听器函数:

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

这将正确地报告特定情况下的特征数量1119.