Search code examples
ionic-frameworkcorsopenlayers

Image access permission issue using OpenLayers


I am having a problem loading an image using the OpenLayers library. I am trying to load an image that is stored on the device dynamically. If I declare the options manually everything works as expected. If I try to load the image through path using file://... I get the following error:

Not allowed to load local resource: file:///storage/emulated/0/Android/data/io.ionic.starter/files/projects/1/layers/volume.png

To resolve this error I used the Ionic Web View path converter: window.Ionic.WebView.convertFileSrc() .

But this gives me another error, now related to CORS, considering that the access method now uses HTTP GET, which I quite don't understand since I trying to load a local image and not a remote one:

Access to image at 'http://localhost/_app_file_/storage/emulated/0/Android/data/io.ionic.starter/files/projects/1/layers/volume.png' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET http://localhost/_app_file_/storage/emulated/0/Android/data/io.ionic.starter/files/projects/1/layers/volume.png net::ERR_FAILED

If I include the file in the assets folder and try to upload it, everything works as expected, but it's not how I want it to work.


Working code (manually configured):

let layerImage = new ImageLayer({
    source: new Static({
        url: 'assets/layers/volume.png',
        crossOrigin: '',
        projection: 'EPSG:31982',
        imageExtent: layerExtent
    }),
    name: "layerImage",
    visible: true,
});
this.map.addLayer(layerImage);

Not working code (dinamically configured inside a for loop):

let filePath = this.win.Ionic.WebView.convertFileSrc(this.file.externalDataDirectory + 'projects/' + this.projectId + '/layers/' + filename);
let layerImage = new ImageLayer({
    source: new Static({
        url: filePath,
        crossOrigin: '',
        projection: 'EPSG:31982',
        imageExtent: layerExtent
    }),
    name: "layerImage",
    visible: true,
});
this.map.addLayer(layerImage);

I saw in some related questions that this can be caused by debugging with Chrome, but the same problem happens if I not use it.


Solution

  • As per @Mike comment, the problem is solved if I remove the crossOrigin: '' option from Static.

    let layerImage = new ImageLayer({
        source: new Static({
            url: filePath,
            projection: 'EPSG:31982',
            imageExtent: layerExtent
        }),
        name: "layerImage",
        visible: true,
    });