在gis系统中我们经常遇到将指定区域的地图导出为图片文件,在openlayer官网提供了导出样例https://openlayers.org/en/latest/examples/export-map.html,导出文件格式为base64编码。
but 大家在使用过程中肯能会遇到导出文件失败
该问题经过网上查阅资料发现,是由于跨域请求导致,加载地图时未设置允许跨域。设置为允许跨域后一切正常。
具体代码如下:
let layer = new ol.layer.Tile({
source: new ol.source.TileSuperMapRest({
url: url,
extent:_map.getView().getProjection().getExtent(),
crossOrigin: 'anonymous',
}),
});
map.addLayer(layer);
//导出图片文件
exportMapImg(callback){
let map = this.map();
map.once('rendercomplete', function() {
var mapCanvas = document.createElement('canvas');
var size = map.getSize();
mapCanvas.width = size[0];
mapCanvas.height = size[1];
var mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(document.querySelectorAll('.ol-layer canvas'), function(canvas) {
if (canvas.width > 0) {
var opacity = canvas.parentNode.style.opacity;
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
var transform = canvas.style.transform;
var matrix = transform.match(/^matrix\(([^\(]*)\)$/)[1].split(',').map(Number);
CanvasRenderingContext2D.prototype.setTransform.apply(mapContext, matrix);
mapContext.drawImage(canvas, 0, 0);
}
});
var data;
if (navigator.msSaveBlob) {
data = mapCanvas.toDataURL();
} else {
data = mapCanvas.toDataURL();
}
callback(data);
});
map.renderSync();
}