摘要:不少API愛好者問我,爲何我點擊的是marker,而map也會響應該事件呢?怎樣才能判斷,我點擊的是標註,仍是地圖呢?下面一塊兒來看看。javascript
------------------------------------------------------------php
你們看到這裏的參數了麼?java
其實,在點擊物體時,經過這些參數就可以判斷所點擊的物體是什麼了。api
用marker舉例:post
先建立一個markerui
//覆蓋物Marker var pmk = new BMap.Point(116.249472,39.946583); var mk = new BMap.Marker(pmk); map.addOverlay(mk);
而後對地圖添加點擊事件,若是判斷出來是覆蓋物,就彈出相應的對話框。url
map.addEventListener("click",function(e){ if(e.overlay){ alert('你點擊的是覆蓋物:'+e.overlay.toString()); }else{ alert('你點擊的是地圖'); } });
添加一堆覆蓋物,而後給每一個覆蓋物寫點擊事件。spa
好比我點擊了多邊形,就會彈出這個。code
所有源代碼:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>點擊事件</title> <script type="text/javascript" src="http://api.map.baidu.com/api?key=v=1.3"></script> </head> <body> <!--百度地圖容器--> <div style="width:697px;height:550px;border:#ccc solid 1px;" id="dituContent"></div> </body> <script type="text/javascript"> var map = new BMap.Map("dituContent"); var point = new BMap.Point(116.331398,39.897445); map.centerAndZoom(point,12); map.enableScrollWheelZoom(); map.addEventListener("click",function(e){ if(e.overlay){ alert('你點擊的是覆蓋物:'+e.overlay.toString()); }else{ alert('你點擊的是地圖'); } }); //覆蓋物Marker var pmk = new BMap.Point(116.249472,39.946583); var mk = new BMap.Marker(pmk); map.addOverlay(mk); //覆蓋物Label var plb = new BMap.Point(116.408149,39.958087); var lb = new BMap.Label('我是覆蓋物Label',{point:plb}); map.addOverlay(lb); //覆蓋物Polyline var pl = new BMap.Polyline([new BMap.Point(116.250047,39.919583),new BMap.Point(116.441494,39.919583)],{strokeWeight:10}) map.addOverlay(pl); //覆蓋物Polygon var pg = new BMap.Polygon([new BMap.Point(116.248323,39.893016),new BMap.Point(116.440344,39.893016),new BMap.Point(116.440344,39.811036),new BMap.Point(116.248323,39.811036)]); map.addOverlay(pg); </script> </html>