1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>自定义覆盖物的点击事件</title>
6 <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>
7 </head>
8 <body>
9 <div style="width:520px;height:340px;border:1px solid gray" id="container"></div>
10 <p>
11 <input type="button" value="移除覆盖物" onclick="mySquare.hide();" />
12 <input type="button" value="显示覆盖物" onclick="mySquare.show();" />
13 <input type="button" value="变成黄色" onclick="mySquare.yellow();" />
14 </p>
15 </body>
16 </html>
17 <script type="text/javascript">
18 var map = new BMap.Map("container"); // 创建Map实例
19 var point = new BMap.Point(116.404, 39.915); // 创建点坐标
20 map.centerAndZoom(point,15); // 初始化地图,设置中心点坐标和地图级别。
21
22 //1、定义构造函数并继承Overlay
23 // 定义自定义覆盖物的构造函数
24 function SquareOverlay(center, length, color){
25 this._center = center;
26 this._length = length;
27 this._color = color;
28 }
29 // 继承API的BMap.Overlay
30 SquareOverlay.prototype = new BMap.Overlay();
31
32 //2、初始化自定义覆盖物
33 // 实现初始化方法
34 SquareOverlay.prototype.initialize = function(map){
35 // 保存map对象实例
36 this._map = map;
37 // 创建div元素,作为自定义覆盖物的容器
38 var div = document.createElement("div");
39 div.style.position = "absolute";
40 // 可以根据参数设置元素外观
41 div.style.width = this._length + "px";
42 div.style.height = this._length + "px";
43 div.style.background = this._color;
44 // 将div添加到覆盖物容器中
45 map.getPanes().markerPane.appendChild(div);
46 // 保存div实例
47 this._div = div;
48 // 需要将div元素作为方法的返回值,当调用该覆盖物的show、
49 // hide方法,或者对覆盖物进行移除时,API都将操作此元素。
50 return div;
51 }
52
53 //3、绘制覆盖物
54 // 实现绘制方法
55 SquareOverlay.prototype.draw = function(){
56 // 根据地理坐标转换为像素坐标,并设置给容器
57 var position = this._map.pointToOverlayPixel(this._center);
58 this._div.style.left = position.x - this._length / 2 + "px";
59 this._div.style.top = position.y - this._length / 2 + "px";
60 }
61
62 //4、显示和隐藏覆盖物
63 // 实现显示方法
64 SquareOverlay.prototype.show = function(){
65 if (this._div){
66 this._div.style.display = "";
67 }
68 }
69 // 实现隐藏方法
70 SquareOverlay.prototype.hide = function(){
71 if (this._div){
72 this._div.style.display = "none";
73 }
74 }
75
76 //5、添加其他覆盖物方法
77 //比如,改变颜色
78 SquareOverlay.prototype.yellow = function(){
79 if (this._div){
80 this._div.style.background = "yellow";
81 }
82 }
83
84 //6、自定义覆盖物添加事件方法
85 SquareOverlay.prototype.addEventListener = function(event,fun){
86 this._div['on'+event] = fun;
87 }
88
89 //7、添加自定义覆盖物
90 var mySquare = new SquareOverlay(map.getCenter(), 100, "red");
91 map.addOverlay(mySquare);
92
93 //8、 为自定义覆盖物添加点击事件
94 mySquare.addEventListener('click',function(){
95 alert('click');
96 });
97 </script>