百度地圖API : 自定義標註圖示

LSG122800發表於2020-10-21

通過Icon類可實現自定義標註的圖示,下面示例通過引數MarkerOptionsicon屬性進行設定,
也可以使用marker.setIcon()方法。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body,
        html,
        #allmap {
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin: 0;
            font-family: "微軟雅黑";
        }
    </style>
    <script type="text/javascript"
        src="https://api.map.baidu.com/api?v=2.0&ak=LaQ2jfcObK42sDixAN2BraP2jbGMU6BC"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

    <title>GPS轉百度</title>
</head>

<body>
    <div id="allmap"></div>
</body>

</html>
<script type="text/javascript">
    // 百度地圖API功能 
    var map = new BMap.Map("allmap");    // 建立Map例項
    var ggpoint = new BMap.Point(129.879392, 32.790481)
    map.centerAndZoom(ggpoint, 16);  // 初始化地圖,設定中心點座標和地圖級別
    map.addControl(new BMap.MapTypeControl());   //新增地圖型別控制元件
    map.setCurrentCity("長崎");          // 設定地圖顯示的城市 此項是必須設定的
    map.enableScrollWheelZoom(true);     //開啟滑鼠滾輪縮放

    var points = [
        [123.319727767605, 41.4229349260951],
        [125.725967756961, 39.0269627713093],
        [126.976200904837, 37.559805362172],
        [126.995866800926, 37.5646576789431],
        [127.717276492584, 37.8846597149346],
        [127.845636602218, 36.5247159814598],
        [129.881057104894, 32.7479331075868],
        [129.877945175468, 32.7441603140361],
        [129.823280322228, 32.8551075968325],
        [129.996944752118, 33.439129860535],
        [129.857128998386, 33.2587933885413],
        [129.788714312017, 33.7842305297287],
        [130.241407289985, 32.7843329855946],
    ];

    // // 座標轉換完之後的回撥函式
    translateCallback = function (data) {
        if (data.status === 0) {
            // 向地圖新增標註
            for (var i = 0; i < points.length; i++) {
                var myIcon = new BMap.Icon("https://i.loli.net/2020/10/21/hQeUEjzTaZv63uB.png", new BMap.Size(23, 35));
                var point = new BMap.Point(points[i][0], points[i][1]);
                // 建立標註物件並新增到地圖 
                var marker = new BMap.Marker(point, { icon: myIcon });
                map.addOverlay(marker);
            };
            map.addOverlay(marker); // 將標註新增到地圖中
            var label = new BMap.Label("您現在的位置", { offset: new BMap.Size(20, -10) });
            marker.setLabel(label); //新增百度label
            map.setCenter(data.points[0]);
        }
    }

    setTimeout(function () {
        var convertor = new BMap.Convertor();
        var pointArr = [];
        pointArr.push(ggpoint);
        convertor.translate(pointArr, 1, 5, translateCallback)
    }, 1000)


    // 地圖的點選事件
    map.addEventListener('click', function (e) {
        console.log('點選位置經緯度:' + e.point.lng + ',' + e.point.lat);
    });
</script>

相關文章