基于openlayer的地图切换功能快速实现

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,
	})
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值