<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./dist/include-openlayers-local.js"></script>
<script src='https://lib.baomitu.com/jquery/2.2.4/jquery.js'></script>
<style>
* {
margin: 0;
padding: 0
}
#map {
position: absolute;
top: 0;
bottom: 0;
z-index: 100;
width: 100%;
}
.btn{
position: absolute;
z-index: 200;
left:50px;
}
</style>
</head>
<body>
<div class="btn">
<button>显示矢量图</button>
<button>显示卫星地球</button>
</div>
<div id="map">
</div>
<script>
var gaodeMapLayer = 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
})
});
var image = 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=6&x={x}&y={y}&z={z}",
wrapX: false
})
})
const map = new ol.Map({
target: "map",
layers: [gaodeMapLayer, image],
view: new ol.View({
center: [114, 30],
zoom: 4,
projection: "EPSG:4326"
})
})
$(".btn button").click(function(){
/* 点击对应的按钮让对应的图层显示 */
const index = $(this).index();
const layers = map.getLayers().getArray();
layers.forEach((item,i)=>{
if(i==index){
item.setVisible(true)
}else{
item.setVisible(false)
}
})
})
</script>
</body>
</html>
<script src="https://lib.baomitu.com/jquery/3.6.0/jquery.js"></script>
参考代码