首页  编辑  

百度地图添加海量点和Marker后点击事件中如何获取点击对象数据或者索引?

Tags: /计算机文档/网页制作/   Date Created:
百度地图添加海量点并添加点击事件,在点击事件中知道是点击了那个点的最简单优美的方法:

p['tag'] = 你的附加属性,例如数组index,请看下划线处即可。

例如:

<script type="text/javascript">
    var map = new BMap.Map("map", {enableMapClick: false});
    var point = new BMap.Point(112.3, 23.4);
    map.addControl(new BMap.NavigationControl());    
    map.enableScrollWheelZoom(true);
    map.centerAndZoom(point, 10);
    
    function showPointInfo(e) {
        alert(e.point['index']);
    }
    
    function showMarkerInfo(e) {
        alert(e.target['index']);
    }
    
    var data = [
                [0, '', 0, 0, 0, ''],
                [0, '', 0, 0, 0, ''],
                [0, '', 0, 0, 0, ''],
                [0, '匿名设备', 112.3, 23.4, 1, '2021-01-29 18:19:48'],
                [2, '测试设备', 112.43, 23.5, 0, '2021-01-30 18:42:42'],
                [1, '设备1', 112.4, 22.5, 0, ''],
            ];
    var points = [];
    var offline = [];
    for (var i=0; i&lt;data.length; i++) {
        var p = new BMap.Point(data[i][2], data[i][3]);
        if (data[i][4] == 0) {
            p['index'] = i;
            points.push(p);
        } else {
            var mark = new BMap.Marker(p);
            mark['index'] = i;
            mark.setAnimation(BMAP_ANIMATION_BOUNCE);
            mark.addEventListener('click', showMarkerInfo);
            map.addOverlay(mark);
        }
    }
    var options = {
        size: BMAP_POINT_SIZE_BIG,
        shape: BMAP_POINT_SHAPE_CIRCLE,
        color: 'blue'
    };
    var pc = new BMap.PointCollection(points, options);
    pc.addEventListener('click', showPointInfo);
    map.addOverlay(pc);    
</script><br>