高德地图API之DOM事件+自定义事件

AMap.event.addDomListener() 绑定事件

AMap.event.removeListener() 解绑事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>map</title>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=ce3b1a3a7e67fc75810ce1ba1f83c01a"></script> 
    <style>
        *{margin:0;padding:0;list-style: none;}
        #container {width:100%; height: 100%;top:0;left:0;position: absolute; }  
        #panel{position: fixed;width:280px;top:10px;right:10px;background-color: #fff;}
        #box{position: absolute;top:20px;right:20px;width:100px;height:50px;background-color: #fff;z-index:10;}
    </style>
</head>
<body>
    <div id="container"></div> 
    <div id="box">
        <button id="btn1">绑定事件</button>
        <button id="btn2">解除绑定</button>
    </div>

    <script>
        var map=new AMap.Map("container",{
            zoom:11,
            center:[121.549792,29.868388],
            resizeEnable:true//不开启则无法触发resize事件
        });

        var lis1=AMap.event.addDomListener(btn1,"click",function(){
            map.zoomIn();
        }) 

        AMap.event.addDomListener(btn2,"click",function(){
            AMap.event.removeListener(lis1);
        }) 

        

    </script>    
</body>
</html>

 

 

自定义事件

1、使用 AMap.event.addListener() 或者 on 来进行绑定

2、使用 emit 方法进行事件派发

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>map</title>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=ce3b1a3a7e67fc75810ce1ba1f83c01a"></script> 
    <style>
        *{margin:0;padding:0;list-style: none;}
        #container {width:100%; height: 100%;top:0;left:0;position: absolute; }  
        #panel{position: fixed;width:280px;top:10px;right:10px;background-color: #fff;}
        #box{position: absolute;top:20px;right:20px;width:100px;height:50px;background-color: #fff;z-index:10;}
    </style>
</head>
<body>
    <div id="container"></div> 

    <script>
        var map=new AMap.Map("container",{
            zoom:11,
            center:[121.549792,29.868388],
            resizeEnable:true//不开启则无法触发resize事件
        });

        var count=0;
        
        function _myfn(){
            console.log("使用AMap.event.addListener绑定事件");
            //触发count
            map.emit("count",{count:count+=1});//第二步
            
        }
        function _count(){
            console.log(count);//第四步
        }

        AMap.event.addListener(map,"click",_myfn);//第一步

        //on监听变量的改变
        map.on("count",_count);//第三步

        

    </script>    
</body>
</html>

 

posted @ 2020-03-07 21:15  陈莺莺呀  阅读(2072)  评论(0编辑  收藏  举报