[GIS] How to add dataURL image as source in OpenLayers

imagelayersopenlayerstiles

I am building a web application with OpenLayers that should have offline map support. I save pictures from a WMS server to the browser cache and load them from the cache as a dataURL. The next step is to input the dataURL to an tileWMS source in OpenLayers. When examining the documentation there seems to be an option called tileLoadFunction that should allow a dataURL to be passed in and added as the source. However I'm not able to understand how to use this option.

Does anyone know how to use the tileLoadFunction or know of some other way to input a dataURL as a source in OpenLayers?

Best Answer

I found a github issue that talked about how to input dataURL data to a layer.

I solved my problem by adding a custom tileLoadFunction.

const cacheSource = new ol.source.TileWMS({
    tileLoadFunction: function(imageTile, src) {
        var url = new URL(src);
        var bbox = url.searchParams.get("BBOX");
        var zoom = map.getView().getZoom();

        var key = zoom + "-" + bbox;

        if(cacheMode){
            imageTile.getImage().src = src;
            cacheTile(key, src);
        } 
        else if(!cacheMode){
            localforage.getItem(key, function(err, dataURL){
                imageTile.getImage().src = dataURL;
                console.log("Loaded Tile from cache: " + key);
            }).catch(function(err){
                console.log(err);
            });
        }
    },
    url: "http://your-wms-server.com",
    params: {
        'LAYERS': 'mapLayer'
    },

});

src is a url for a WMS call and imageTile is an ol.ImageTile who's source can be set to the url or a dataURL as can be seen in the github issue.