尝试以编程方式添加时,未向 VectorLayer 添加任何功能

No feature is added to VectorLayer while trying to add programmatically

我试图在从数据库和文件系统中获取一些数据后,以编程方式向我的地图添加一些 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.filethis.map 是地图本身。

我也尝试过以这种方式添加功能,如 seen here,但得到了相同的结果:

newVectorLayer.getSource().getFormat().readFeatures(JSON.parse(layer_file));

我不知道这是否是加载本地文件并添加到源的最佳方式,所以请告诉我。首先,我尝试使用 VectorSource 中的内置 url 选项,但它使用的 XHR 加载器在尝试从 file://...

加载时被 CORS 阻止

通过为源格式创建一个单独的变量解决了问题,如 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);          
});
...