openlayers检查vector是否有内容,以避免错误消息

问题描述 投票:1回答:1

每秒运行以下代码。

var new_source = new ol.source.Vector({
    url: 'pages/Coordinates.php',
    format: new ol.format.KML({
        extractStyles: false,
        extractAttributes: false
    })
});



var new_layer = new ol.layer.Vector({
    source: new_source,
    style: styling
});

map.addLayer(new_layer);


new_source.once('change', function() {
    if (x) {
        map.removeLayer(x);
    }
    x = new_layer;
});

工作正常,但如果没有源的坐标,我得到此错误消息。

XML Parsing Error: no root element found Location: localhost/test/ Line Number 1, Column 1:

有关如何避免此错误消息的任何想法?

我已经考虑过检查源是否已准备就绪,但是当没有坐标时它也会准备就绪。

然后我考虑检查它中是否有功能,但是即使有功能也没有用。

所以我决定看看有没有包含坐标的调用的“源”和/或“向量”对象之间是否存在任何差异,但是我无法找到任何可以比较的内容。

openlayers kml error-messaging
1个回答
1
投票

当OL尝试读取这些功能时,可能会发生错误,因此您需要使用http://openlayers.org/en/v4.6.5/apidoc/ol.source.Vector.html中的自定义加载器并使用它来捕获错误,因此类似于:

var vectorSource = new ol.source.Vector({
  format: new ol.format.KML({
        extractStyles: false,
        extractAttributes: false
  }),
  loader: function(extent, resolution, projection) {
     var proj = projection.getCode();
     var url = 'pages/Coordinates.php';
     var xhr = new XMLHttpRequest();
     xhr.open('GET', url);
     var onError = function() {
       vectorSource.removeLoadedExtent(extent);
     }
     xhr.onerror = onError;
     xhr.onload = function() {
       if (xhr.status == 200) {
         try {
           vectorSource.addFeatures(
             vectorSource.getFormat().readFeatures(xhr.responseText));
         } catch(err) { onError(); }
       } else {
         onError();
       }
     }
     xhr.send();
   },
   strategy: ol.loadingstrategy.bbox
 });
© www.soinside.com 2019 - 2024. All rights reserved.