openlayersopenstreetmapopenlayers-5angular-openlayers

How to download the OSM tiles for selected part of map


I want to download the map offline for a selected part of the map with single Zoom level with Openlayer OSM layer. I have got the four corner of map i.e display section of a map.

But need to get the all tiles image or tiles between that four corners. I have reviewed some example:

Openlayers get the image url of the tile under the mouse

https://gis.stackexchange.com/questions/167792/how-to-retrieve-the-tile-url-in-openlayers-3

But I need to download the tiles on customer button click. Can anyone please help me.


Solution

  • Here's a simple example to save tiles as data urls for later use. If you need saved tiles to remain available after closing and reopening the browser replace sessionStorage with localStorage.

    // load OSM zoom level 8 tiles for Switzerland to data urls
    
    var extent = ol.proj.transformExtent([5.9,45.8,10.55,47.85],'EPSG:4326','EPSG:3857');
    var zoom = 8;
    
    var source = new ol.source.OSM();
    
    source.getTileGrid().forEachTileCoord(extent, zoom, function(tileCoord) {
        var img = document.createElement("img");
        img.onload = function() {
            var canvas = document.createElement("canvas");
            canvas.width = source.getTileGrid().getTileSize(zoom);
            canvas.height = source.getTileGrid().getTileSize(zoom);
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            sessionStorage.setItem('OSM_' + tileCoord[0] + '_' + tileCoord[1] + '_' + (-tileCoord[2]-1), canvas.toDataURL());
            img.remove();
            canvas.remove();
        };
        img.crossOrigin = "Anonymous";
        img.src = source.getTileUrlFunction()(tileCoord);
    });
    
    // wait a few seconds to ensure data urls are ready, then create a map to use them
    
    setTimeout(function(){
    
        map = new ol.Map({
            target: 'map',
            layers: [
                new ol.layer.Tile({
                    extent: extent,
                    source: new ol.source.XYZ({
                        attributions: ol.source.OSM.ATTRIBUTION,
                        maxZoom: 8,
                        minZoom: 8,
                        tileUrlFunction: function(tileCoord) {
                            return sessionStorage.getItem('OSM_' + tileCoord[0] + '_' + tileCoord[1] + '_' + (-tileCoord[2]-1));
                        }
                    }),
                })
            ],
            view: new ol.View({
                center: ol.extent.getCenter(extent),
                zoom: 8
            }),
            controls: ol.control.defaults({
                attributionOptions: { collapsible: false },
            })
        });
    
    }, 3000);