How to download the OSM tiles for selected part of map

故事扮演 提交于 2019-12-04 06:59:59

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/53607810/how-to-download-the-osm-tiles-for-selected-part-of-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!