高德地图API之DOM事件+自定义事件
程序员文章站
2022-09-27 10:31:08
AMap.event.addDomListener() 绑定事件 AMap.event.removeListener() 解绑事件 map
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>