百度地图添加自定义点标记、文本标注、点标记

 网页效果:添加文字标签https://demo.foreval.cn/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=你的密钥"></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/c6bea076b54ffae2.png'
let imgBlue = 'https://s3.bmp.ovh/imgs/2022/04/11/4d650aa0123df092.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); //开启信息窗口
    }); 
})
</script>

欢迎大家关注我的公众号「踏浪而行生活圈」,这里不仅有更多好玩的内容,还会同步更新 踏浪而行 最新资讯,让你时刻掌握科技前沿,快来加入我们吧!

猜你喜欢

转载自blog.csdn.net/weixin_45849072/article/details/124101570