百度地图添加文本标注+信息窗口

效果图:

 网页效果:添加文字标签

需求:

  • 页面展示marker
  • marker旁边有标注
  • 点击marker时有弹窗提示具体信息
  • 鼠标移除时关闭弹窗提示 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>添加文字标签</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <style>
    body,
    html,
    #container {
        overflow: hidden;
        width: 100%;
        height: 100%;
        margin: 0;
        font-family: "微软雅黑";
    }
    </style>
    <script src="http://api.map.baidu.com/api?type=webgl&v=1.0&ak=yourKey"></script>
</head>
<body>
    <div id="container"></div>
</body>
</html>
<script>
var map = new BMapGL.Map('container');
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 14);
map.enableScrollWheelZoom(true);
var pointArr = [
    {
        id: 1,
        belong: 1,
        lat: 39.925,
        lng: 116.404,
        title: '红色坐标',
        message: '我是红色坐标',
        popTitle: '标题1'
    },
    {
        id: 2,
        belong: 2,              // 判断是显示红色坐标还是蓝色坐标
        lat: 39.915,
        lng: 116.404,
        title: '蓝色坐标',              // 有右侧文本标注
        message: '我是蓝色坐标',        // 弹窗提示内容
        popTitle: '标题2'               // 弹窗标题
    }
]
var labelStyle = {
    color: 'blue',
    borderRadius: '5px',
    borderColor: '#ccc',
    padding: '3px',
    fontSize: '12px',
    height: '20px',
    lineHeight: '20px',
    fontFamily: '微软雅黑'
}
let imgRed = 'https://s3.bmp.ovh/imgs/2022/04/11/2b6652b74fff473f.png'
let imgBlue = 'https://s3.bmp.ovh/imgs/2022/04/11/1115f7e5f6d32c04.png'
pointArr.forEach((item, index)=>{
    var myIcon = new BMapGL.Icon(item.belong === 1?imgRed:imgBlue, new BMapGL.Size(32, 32))         // 根据条件判断icon的图标
    var marker = new BMapGL.Marker(new BMapGL.Point(item.lng, item.lat),{ icon: myIcon });          // 将图标和坐标进行关联
    map.addOverlay(marker);                                                                         // 将关联好的结果进行放置                                  
    var opts = {
        position: new BMapGL.Point(item.lng, item.lat), // 指定文本标注所在的地理位置
        offset: new BMapGL.Size(30, -30) // 设置文本偏移量
    };
    var label = new BMapGL.Label(item.title, opts);             // 创建文本标注对象
    label.setStyle(labelStyle);                                 // 自定义文本标注样式
    map.addOverlay(label);
    var infoWindow = new BMapGL.InfoWindow(item.message, {      // 创建信息窗口对象
        width : 200,     // 信息窗口宽度
	    height: 100,     // 信息窗口高度
	    title : item.popTitle , // 信息窗口标题
    })
	marker.addEventListener("click", function(){                // 创建点击事件    
		map.openInfoWindow(infoWindow, opts.position); //开启信息窗口
	}); 
    marker.addEventListener("onmouseout", function(){                // 创建点击事件    
		map.closeInfoWindow(); //关闭信息窗口
	}); 
})
</script>

猜你喜欢

转载自blog.csdn.net/weixin_45849072/article/details/124292173
今日推荐