因为OpenLayers
中没有提供混合地图这个api
,然后项目要求需要和百度地图一样有混合地图这个功能,然后通过new ol.layer.Tile
这个api找到了一些思路。
思路
1、需要两个完整的切片图层来达到可以混合地图切换功能
2、初始化地图博客中就有new ol.layer.Tile
并且是通过这个来引入街道图切片
3、new ol.layer.Tile
api中有一个属性值visible
,也就是说我们可以人为操控他的显示与不显示
4、new ol.layer.Tile
提供setVisible()
开工
1、右上角混合地图按钮布局
<style>
.mapSwitch{
z-index: 1000;
position:fixed;
top:10px;
right: 10px;
background:#fff;
font-size:0;
box-shadow: rgba(0, 0, 0, 0.34902) 2px 2px 3px;
border-radius:3px
}
.mapSwitch>a{
text-decoration: none;
font-size:12px;
display:inline-block;
padding:5px 10px;
color:black;
cursor: pointer;
}
.mapSwitch>a:first-child{
border-radius: 3px 0px 0px 3px;
}
.mapSwitch>a:last-child{
border-radius: 0px 3px 3px 0px;
}
.mapSwitch>a.active{
background:rgb(139, 164, 220);
color:#fff;
}
</style>
<div class="mapSwitch">
<a href="#" class="normal active">地图</a>
<a href="#" class="mix">混合</a>
</div>
2、初始化地图引入两个切片图层
这里的参数参考初始化那篇文章
//街道图
normalMap = new ol.layer.Tile({
visible: true,
source: new ol.source.XYZ({
minZoom: minZoom,
maxZoom: maxZoom,
projection: projection,
tileSize: tileSize,//512
url: url//url += "{z}/{x}/{y}" + format;
})
});
mixMap = new ol.layer.Tile({
visible: false,
source: new ol.source.XYZ({
minZoom: minZoom,
maxZoom: maxZoom,
projection: projection,
tileSize: mixSize,//256
url: mixUrl//mixUrl += "{z}/{x}/{y}" + format;
})
});
map = new ol.Map({
********
layers: [normalMap, mixMap],
********
});
3、右上角点击切换
$('.normal').click(function () {
if (!$(this).hasClass('active')) {
$(this).addClass('active').siblings().removeClass('active');
normalMap.setVisible(true); //显示瓦片
mixMap.setVisible(false); //关闭矢量
}
})
$('.mix').click(function () {
if (!$(this).hasClass('active')) {
$(this).addClass('active').siblings().removeClass('active')
normalMap.setVisible(false); //关闭瓦片
mixMap.setVisible(true); //显示矢量
}
})
大功告成
街道图
混合卫星图