【问题标题】:No feature is added to VectorLayer while trying to add programmatically尝试以编程方式添加时未向 VectorLayer 添加任何功能
【发布时间】:2020-04-10 09:49:04
【问题描述】:

在从数据库和文件系统获取一些数据后,我正在尝试以编程方式将一些 VectorLayers 添加到我的地图中。我面临的问题是,虽然数据和VectorLayer 已添加到地图中,但未加载源要素。一切运行后,如果我console.log(this.map.getLayers()) 可以看到添加的图层,但如果我console.log(addedLayer.getSource().getFeatures()) 结果是一个空数组。

  • OpenLayers v6.1.1

我的代码

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.storagethis.filethis.map 是地图本身。

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

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

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

【问题讨论】:

    标签: typescript ionic-framework openlayers


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      相关资源
      最近更新 更多