<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 1、导入openlayers的依赖 -->
<link rel="stylesheet" href="https://lib.baomitu.com/ol3/4.6.5/ol.css">
<script src="https://lib.baomitu.com/ol3/4.6.5/ol.js"></script>
<script src="https://lib.baomitu.com/FileSaver.js/2.0.5/FileSaver.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
#map {
width: 100vw;
height: 100vh;
}
#btn {
position: fixed;
top: 20px;
left: 60px;
width: 100px;
height: 40px;
z-index: 100;
}
</style>
</head>
<body>
<button id="btn" onclick="exportImg()">下载地图</button>
<!-- 2、设置地图容器的挂载点 -->
<div id="map">
</div>
<script>
/* 3、设置一个瓦片图层 */
const gaode = new ol.layer.Tile({
title: "高德地图",
source: new ol.source.XYZ({
url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
wrapX: false,
crossOrigin: "Anonymous"
})
});
var image = new ol.layer.Tile({
title: "高德地图-image",
source: new ol.source.XYZ({
url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=6&x={x}&y={y}&z={z}",
wrapX: false,
crossOrigin: "Anonymous"
}),
opacity: 0.5
})
/* 4、实例化地图 */
/* new Vue({
el
}) */
const origin = [114.30, 30.50]
const map = new ol.Map({
/* 将实例化的地图挂载到对应的DOM元素上 */
target: "map",
layers: [gaode, image],
/* 设置地图以中心点显示/坐标显示/方法级别显示 */
view: new ol.View({
center: origin,
zoom: 6,
/* 坐标 */
projection: "EPSG:4326"
})
})
function exportImg() {
map.once('postcompose', function (event) {
const canvas = event.context.canvas
console.log(canvas)
canvas.toBlob(function (blob) {
console.log(blob)
saveAs(blob, 'map.png')
})
})
map.renderSync()
}
</script>
</body>
</html>
OpenLayer-地图下载
于 2024-04-27 12:46:13 首次发布