1.核心代码
map.getLayers().item(0).setVisible(true);
2.效果展示
默认地图
混合地图
3.代码实现
(1)定义右上角的地图标签选项卡,并为其设置圆角、阴影等样式;
var switch_map_html = '<div id="switchMap" style="border-radius: 3px; box-shadow: 5px 5px 10px 2px rgba(0, 0, 0, .2); cursor: pointer; position:fixed; text-align: center; background-color: rgba(142, 168, 224, 1); color: white; z-index: 19891016; padding: 1px; top: 140px; right: 0px; font-size: 13px; color: white;">'
+ '<div id="switchMap_normal" class="active" style="border-radius: 3px 0 0 3px; padding: 5px 10px 5px 10px; display: inline-block; background-color: white; color: black; font-weight: 600;">地图</div>'
+ '<div id="switchMap_fix" style="border-radius: 0 3px 3px 0; padding: 5px 10px 5px 10px; display: inline-block; background-color: rgba(142, 168, 224, 1); font-weight: 600;">混合</div>'
+ '</div>';
(2)使用jQuery将右上角的地图选项卡添加到body标签中;
$('body').append(switch_map_html);
(3)设置地图标签选项卡点击事件;
$('#switchMap').click(function() {
let target = window.event.srcElement || window.event.target ;
if ($(target).text() == "混合" && !$(target).hasClass('active')) {
//切换到混合图层
$(target).addClass('active');
$(target).css({'background-color' : 'white', 'color' : 'black'});
$('#switchMap_normal').removeClass('active');
$('#switchMap_normal').css({'background-color' : 'rgba(142, 168, 224, 1)', 'color' : 'white'});
map.getLayers().item(0).setVisible(false);
} else if ($(target).text() == "地图" && !$(target).hasClass('active')) {
//切换到普通路线图层
$(target).addClass('active');
$(target).css({'background-color' : 'white', 'color' : 'black'});
$('#switchMap_fix').removeClass('active');
$('#switchMap_fix').css({'background-color' : 'rgba(142, 168, 224, 1)', 'color' : 'white'});
map.getLayers().item(0).setVisible(true);
}
});
(4)定义map容器,其中offlineMapLayer为普通地图,satelliteMapLayer和overlayMapLayer为混合地图的图层。
var map = new ol.Map({
// 让id为map的div作为地图的容器
target: "map",
// 设置地图图层
layers: [offlineMapLayer,satelliteMapLayer,overlayMapLayer],
// 设置显示地图的视图
view: new ol.View({
projection: "EPSG:3857",
center: convertLL2MC({x: 121.362116, y: 28.381469}),
minZoom: 11,
maxZoom: 19,
zoom: 11,
})
});