OpenLayers检查Vector是否有内容,以避免错误消息



每秒运行一次以下代码。

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:

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

我考虑过检查源是否设置为就绪,但是当没有坐标时,它也会显示就绪。

然后我想检查其中是否有功能,但后来即使有功能也不起作用。

所以我决定看看"源"和/或"矢量"对象之间是否有任何区别,有和没有包含坐标的调用,但唉,我找不到任何可以比较的东西。

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

相关内容

最新更新