从数据库和文件系统中获取某些数据后,我试图以编程方式向地图添加一些VectorLayers
。我面临的问题是,尽管将数据和VectorLayer
添加到了地图中,但未加载源要素。一切运行之后,如果我console.log(this.map.getLayers())
可以看到在那里添加了图层,但是如果我console.log(addedLayer.getSource().getFeatures())
则结果是一个空数组。
我的代码
this.storage.get("my_layers").then(layers => {
if (layers) {
let parsedLayers = JSON.parse(layers);
// Loop through the layers
for (let prop in parsedLayers) {
let file_location = parsedLayers[prop]['file_location'];
let filename = file_location.split('/').pop();
let newVectorLayer = new VectorLayer({
source: new VectorSource ({
format: new GeoJSON({dataProjection: 'EPSG:31982'})
}),
style: this.styleArea('rgba(11, 102, 35, 1)', 'rgba(0, 0, 0, 1)', 2), //Returns green with black border
name: parsedLayers[prop]['layer_id'],
visible: true
});
this.file.readAsText(this.file.externalDataDirectory + 'projects/' + this.projectId + '/layers/', filename)
.then(layer_file => {
newVectorLayer.getSource().addFeatures(JSON.parse(layer_file));
this.map.addLayer(newVectorLayer);
console.log(newVectorLayer.getSource().getFeatures()); // Returns an empty array
});
}
}
});
this.storage
,this.file
和this.map
是地图本身。
我也尝试以此方式添加功能,例如seen here,但得到了相同的结果:
newVectorLayer.getSource().getFormat().readFeatures(JSON.parse(layer_file));
我不知道这是否是加载本地文件并添加到源代码的最佳方法,所以请告诉我。首先,我尝试使用VectorSource
中的内置url
选项,但是当尝试从file://...
加载时,它使用的XHR加载器被CORS阻止了
答案 0 :(得分:0)
通过为源格式创建一个单独的变量解决了该问题,如here:
...
let newVectorLayer = new VectorLayer({
source: new VectorSource ({}),
style: this.styleArea('rgba(11, 102, 35, 1)', 'rgba(0, 0, 0, 1)', 2), // Returns green with black border
name: parsedLayers[prop]['layer_id'],
visible: true
});
this.file.readAsText(this.file.externalDataDirectory + 'projects/' + this.projectId + '/layers/', filename).then(layer_file => {
let format = new GeoJSON({
featureProjection:"EPSG:3857",
dataProjection:"EPSG:31982"
});
newVectorLayer.getSource().addFeatures(format.readFeatures(layer_file)); // Don't needed to parse here
this.map.addLayer(newVectorLayer);
});
...