getFeatures()为空

时间:2015-04-03 12:58:30

标签: kml openlayers-3

我有类似的问题,例如POI in OpenLayer 3但不一样。

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

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

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

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

但如果我试图看到这些功能,我会得到一个空数组。

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

==> Array [ ]

任何想法?

thx mx

1 个答案:

答案 0 :(得分:8)

请参阅我们即将推出的常见问题解答中的答案:

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'
  })
});
  

您可能会问自己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);
  

这将记录源中的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);
  }
});
  

这将正确报告特定情况下的1119个功能。