openlayers实现地图的卷帘
示例:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Layer Swipe</title>
<link href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/css/ol.css"
rel="stylesheet" type="text/css" />
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"
type="text/javascript"></script>
<style>
#map {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- 用于控制卷帘位置的元素 -->
<input id="swipe" type="range" />
<script>
// oepn street map
var osm = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d', //注意tk就是自己调取天地图服务时,在天地图上申请的key值
})
});
// 微软高德地图
var gaode = new ol.layer.Tile({
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}'
})
});
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
map.addLayer(bing)
map.addLayer(osm)
var swipe = document.getElementById('swipe'); // 用于控制卷帘位置的DOM元素
gaode.on('prerender', function (event) { // 在gaode地图渲染之前触发
var ctx = event.context; //获得canvas渲染上下文
var width = ctx.canvas.width * (swipe.value / 100); // 用于保存卷帘的位置
ctx.save(); // 保存canvas设置
ctx.beginPath(); // 开始绘制路径
ctx.rect(width, 0, ctx.canvas.width - width, ctx.canvas.height); // 绘制矩形
ctx.clip(); // 裁剪Bing地图,以形成卷帘效果
})
gaode.on('postrender', function (event) { // 在gaode地图渲染之后触发
var ctx = event.context;
ctx.restore(); // 恢复canvas设置
});
swipe.addEventListener('input', function () { // 在每次用户改变swipe控件时触发
map.render(); // 渲染地图
}, false);
</script>
</body>