Have the following code run every second.
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;
});
Works fine but if there's no coordinates for the source to get I get this error message.
XML Parsing Error: no root element found
Location: localhost/test/
Line Number 1, Column 1:
Any ideas on how to avoid this error message?
I've thought about checking if the source was set to ready, but it's also says ready when there's no coordinates.
Then I thought about checking if there is features in it, but then it didn't work even when there was.
So I decided to see if there was any differences between a "source" and/or "vector" object with and without a call that includes coordinates, but alas I haven't been able to find anything I can compare.
The error is presumably happening when OL tries to read the features, so you would need to use a custom loader as in http://openlayers.org/en/v4.6.5/apidoc/ol.source.Vector.html and use that catch the error, so something like:
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
});