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

openlayers check if vector has content, to avoid error message

每秒有以下代码运行。

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:

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

我考虑过检查源是否设置为就绪,但在没有坐标的情况下它也说就绪。

然后想看看有没有功能,结果有也没用。

所以我决定看看 "source" and/or "vector" 对象在调用和不调用包含坐标的情况下是否有任何区别,但可惜我没能做到找到任何我可以比较的东西。

错误可能是在 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
 });