1. 程式人生 > >OpenLayers3(三)混合地圖切換

OpenLayers3(三)混合地圖切換

因為OpenLayers中沒有提供混合地圖這個api,然後專案要求需要和百度地圖一樣有混合地圖這個功能,然後通過new ol.layer.Tile這個api找到了一些思路。

附:OpenLayers初始地圖

思路

1、需要兩個完整的切片圖層來達到可以混合地圖切換功能
2、初始化地圖部落格中就有new ol.layer.Tile並且是通過這個來引入街道圖切片
3、new ol.layer.Tileapi中有一個屬性值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); //顯示向量
	}
})

大功告成

街道圖

街道

混合衛星圖

混合