I am new to OpenLayers and I'm trying to label features on a map using a GeoJSON data. Here is my code:
var layer = new ol.layer.VectorTile({
source: new ol.source.VectorTile({
format: new ol.format.GeoJSON(),
tileGrid: ol.tilegrid.createXYZ(),
url: "http://abcd.com/cities/{z}/{x}/{y}.geojson"
})
})
Sometimes I get "features": null in the GeoJSON data:
{ "type": "FeatureCollection", "features": null }
and features parsing fails with error Uncaught TypeError: Cannot read property 'length' of null. Is it possible to replace null by [] before parsing features?
UPDATE. I found a solution, but got a new issue: I can't add features to the source. Here is my code (I'm using OpenLayers 3.9.0):
var format = new ol.format.GeoJSON();
var source = new ol.source.TileVector({
tileGrid: ol.tilegrid.createXYZ(),
tileLoadFunction: function (url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (XMLHttpRequest.DONE === xhr.readyState && 200 === xhr.status) {
var json = xhr.responseText.replace("null", "[]");
var features = format.readFeatures(json, {
featureProjection: "EPSG:3857"
});
features.forEach(function (f) {
console.log(f.getGeometry().getCoordinates()); // features are parsed correctly
});
source.addFeatures(features);
}
};
xhr.send();
},
url: "http://abcd.com/cities/{z}/{x}/{y}.geojson"
});
source.on("addfeature", function () {
console.log(source.getFeatures()); // outputs an empty array of the features; it seems that the features haven't been added
});
new ol.Map({
target: "map",
layers: [
new ol.layer.Vector({
source: source
})
],
view: new ol.View({
center: ol.proj.fromLonLat([0, 0]),
maxZoom: 12,
minZoom: 1,
zoom: 6
})
});
Any suggestions?