【问题标题】:openlayers check if vector has content, to avoid error messageopenlayers 检查向量是否有内容,以避免错误消息
【发布时间】:2018-08-31 08:56:22
【问题描述】:

让以下代码每秒运行一次。

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】:

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

    【讨论】:

    • "404" 页面在尝试解析 json 时具有类似的效果。我通过让代理过滤掉它们来避免这种情况。也许您的 php 可以设置为根本不响应,而不是发送空的或不完整的 XML?
    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 2012-07-21
    • 2021-12-03
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多