高德地图 - 点击改变当前 marker 图标(marker点击切换 icon 上一个 icon 恢复原样)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>高德地图 - 点击改变当前marker图标</title>
    <link rel="shortcut icon" href="#" />
    <link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/>
    <style>
        #cm_map {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
<div id="cm_map"></div>
</body>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.6&key=fb5dce704318a76bbbdc4dfbff58cc83"></script>
<script type="text/javascript">

    var cmMap = new AMap.Map('cm_map', {
        resizeEnable: true, 
        zoom: 9,
        // center: [121.481041,31.683859],  //崇明东平森林公园经纬度
        center: [121.635058,31.576855]  //崇明岛经纬度
    });
    cmMap.setMapStyle('amap://styles/darkblue');    //  标准 darkblue

    // 停车场分布
    var preIcon, clickIcon, markers = [], lnglats = [
        [121.395354,31.6193],
        [121.610123,31.524003],
        [121.690257,31.380364],
    ];
    preIcon = new AMap.Icon({
        image: "img/cz/parking_unchecked.png",
        size: new AMap.Size(30, 37), //图标大小
        imageSize: new AMap.Size(30, 37)
    });
    clickIcon = new AMap.Icon({
        image: "img/cz/parking_checked.png",
        size: new AMap.Size(30, 37), //图标大小
        imageSize: new AMap.Size(30, 37)
    });

    for (var i = 0; i < lnglats.length; i++) {
        var marker = new AMap.Marker({
            map: cmMap,
            position: lnglats[i],
            icon: preIcon,
            offset: new AMap.Pixel(-0, -37)
        })

        cmMap.setFitView()

        // marker逐一push到markers
        markers.push(marker)

        marker.on('click', resetMap);
        // marker.emit('click', {target: marker});
    }

    //鼠标点击事件,设置地图中心点及放大显示级别
    function resetMap(e) {
        // cmMap.setCenter(e.target.getPosition());
        cmMap.setZoomAndCenter(11, e.target.getPosition());
        
        for (var i = 0; i < markers.length; i++) {
            markers[i].setIcon(preIcon);
        }

        e.target.setIcon(clickIcon);

    }
</script>
</html>

 

posted @ 2019-04-19 11:17  格鲁特baby  阅读(2382)  评论(0编辑  收藏  举报