攻城狮Lee丶
2018-06-09 11:08
采纳率: 100%
浏览 3.2k

javascript百度地图多个多边形点击事件,个别的无法响应

我想实现点击每个多边形,提示响应的索引,但是点击正常提示,有的就不提示。实在搞不清楚什么问题。
这是我的代码

 <!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="json.js" ></script>-->
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=zga15SpUh7sMrZkXaBKicRBshkN3bKtR"></script>
    <title>添加行政区划</title>
</head>
<body>
    <div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
    // 百度地图API功能
    var map = new BMap.Map("allmap");
    var pointArray = [];
    map.centerAndZoom(new BMap.Point(116.403765, 39.914850), 5);
    map.enableScrollWheelZoom();
    var oneDev = ["北京市","上海市","天津市","重庆市","黑龙江","辽宁省","吉林省","河北省","河南省","湖北省","湖南省","山东省","山西省","陕西省","安徽省","浙江省","江苏省","福建省","广东省","海南省","四川省","云南省","贵州省","青海省","甘肃省","江西省","台湾","广西","西藏","新疆","宁夏","内蒙古","香港","澳门"];
    var colorArr = ['#ff541c','#1cecff','#3cff1c','#ff1c47',,'#000'];
    boundary();
    function boundary(){
        for(var j in oneDev){
            (function(index){
                var bdary = new BMap.Boundary();
                bdary.get(oneDev[index], function(rs){  //获取行政区域
                    //map.clearOverlays();        //清除地图覆盖物       
                    var count = rs.boundaries.length; //行政区域的点有多少个
                    for (var i = 0; i < count; i++) {
                        var color = colorArr[Math.floor(Math.random()*3+0)];
                        var ply = new BMap.Polygon(rs.boundaries[i], {fillColor:color,strokeWeight: 2, strokeColor:'#000'}); //建立多边形覆盖物
                        map.addOverlay(ply);  //添加覆盖物
                    }  
                    //map.setViewport(pointArray);    //调整视野  
                    ply.addEventListener('click',function(){
                        console.log(index)
                    })
                });
            })(j)
        }
    }
</script>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 已采纳

    覆盖物事件放到for循环里面,要不你的ply只是给返回的最后一个多边形添加事件而已,如果点击的不是最后一个当然无法触发事件

                         for (var i = 0; i < count; i++) {
                            var color = colorArr[Math.floor(Math.random() * 3 + 0)];
                            var ply = new BMap.Polygon(rs.boundaries[i], { fillColor: color, strokeWeight: 2, strokeColor: '#000' }); //建立多边形覆盖物
                            map.addOverlay(ply);  //添加覆盖物
                                                    ///////////////////事件放里面
                            ply.addEventListener('click', function () {
                                console.log(index)
                            })
                        }
    
    4 打赏 评论

相关推荐 更多相似问题