InfoBox.prototype.initialize = function (map) { var me = this; var div = this._div = baidu.dom.create('div', { "class": this._opts.boxClass }); baidu.dom.setStyles(div, this._opts.boxStyle); //設置position為absolute,用於定位 div.style.position = "absolute"; this._setContent(this._content); var floatPane = map.getPanes().floatPane; floatPane.style.width = "auto"; floatPane.appendChild(div); //設置完內容后,獲取div的寬度,高度 this._getInfoBoxSize(); //this._boxWidth = parseInt(this._div.offsetWidth,10); //this._boxHeight = parseInt(this._div.offsetHeight,10); //阻止各種冒泡事件 baidu.event.on(div, "onmousedown", function (e) { me._stopBubble(e); }); baidu.event.on(div, "onmouseover", function (e) { me._stopBubble(e); }); baidu.event.on(div, "click", function (e) { me._stopBubble(e); }); baidu.event.on(div, "dblclick", function (e) { me._stopBubble(e); }); // 手機端阻止冒泡 baidu.event.on(div, "touchstart", function (e) { me._stopBubble(e); }); baidu.event.on(div, "touchend", function (e) { me._stopBubble(e); }); baidu.event.on(div, "touch", function (e) { me._stopBubble(e); }); return div; }
在電腦上正常,可以關閉彈出窗,手機端不行,參照上面的修改源碼部分即可。
問題地址:http://bbs.lbsyun.baidu.com/forum.php?mod=viewthread&tid=135430
源碼分享:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edgechrome=1"> <meta name="viewport" content="width=device-width initial-scale=1.0 user-scalable=no"> <meta name="format-detection" content="telephone=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="stylesheet" type="text/css" href="/css/global.css"> <link rel="stylesheet" type="text/css" href="/css/main.css"> <link rel="stylesheet" type="text/css" href="/css/swiper.min.css"> <title>【斑斕·家】西安服務式酒店公寓地段</title> </head> <body> <div class="map" id="allmap" style="width: 100%; font-size: 12px; padding: 0 0px; margin: 0 auto;"> </div> <script type="text/javascript" src="/Scripts/jquery-1.7.1.min.js"></script> <script src="/datepicker/js/jquery.cookie.js"></script> <script src="/datepicker/js/jquery.cookie.js"></script> <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=e5mycIBbzN1Y2tcat74nacHQTsVbvPoh"></script> <script src="/Content/baidu/InfoBox.js"></script> <script type="text/javascript" src="http://api.map.baidu.com/library/RichMarker/1.2/src/RichMarker_min.js "></script> <style type="text/css"> /*地圖標題*/ .anchorBL { display: none; } .BMap_bubble_title { color: black; font-size: 13px; font-weight: bold; text-align: left; } .BMap_pop div:nth-child(1) { border-radius: 7px 0 0 0; } .BMap_pop div:nth-child(3) { border-radius: 0 7px 0 0; background: #ABABAB; /*background: #ABABAB;*/ width: 23px; width: 0px; height: 0px; } .BMap_pop div:nth-child(3) div { border-radius: 7px; } .BMap_pop div:nth-child(5) { border-radius: 0 0 0 7px; } .BMap_pop div:nth-child(5) div { border-radius: 7px; } .BMap_pop div:nth-child(7) { border-radius: 0 0 7px 0; } .BMap_pop div:nth-child div(7) { border-radius: 7px; } table.customoverlay { margin: 20px auto 0px auto; } .overlaybackground { background-image: url("/Images/HotPlace/overlaybig.png"); background-repeat: no-repeat; background-position: center; width: 98px; height: 121px; position: absolute; color: white; white-space: normal; line-height: 10px; text-align: center; font-size: 14px; } .customoverlay th { height: 40px; min-height: 18px; line-height: 18px; font-weight: bold; font-size: 14px; text-align: center; } .customoverlay td { min-height: 14px; line-height: 14px; font-size: 12px; text-align: center; } .infowindow { background-image: url("/content/baidu/infowindowbj.png"); background-repeat: no-repeat; background-position: center; width: 300px; height: 142px; margin: 0px 4px; padding: 4px; } .infoTitle { font-size: 18px; font-weight: bolder; } .infowindow td { vertical-align: top; } </style> <script type="text/javascript"> wx.config({ debug: false, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。 appId: 'wxbbf496a1ed712716', // 必填,公眾號的唯一標識 timestamp: '1508473423', // 必填,生成簽名的時間戳 nonceStr: '98F13708210194C475687BE6106A3B84', // 必填,生成簽名的隨機串 signature: 'e4dabfa5c5553ee67be88441b87a4b4f87af59fb',// 必填,簽名 jsApiList: [ // 所有要調用的 API 都要加到這個列表中 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage' ] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2。詳見:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html }); wx.error(function (res) { console.log(res); }); wx.ready(function () { // config信息驗證后會執行ready方法,所有接口調用都必須在config接口獲得結果之后,config是一個客戶端的異步操作,所以如果需要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則可以直接調用,不需要放在ready函數中。 var imgUrls = 'http://www.ihuo6.com/Images/V3/logo.png'; var link = 'http://www.ihuo6.com' + '/hotel/HotPlaceByMapTest'; wx.onMenuShareTimeline({ title: '【斑斕·家】西安服務式酒店公寓地段', // 分享標題 link: link, // 分享鏈接 imgUrl: imgUrls, // 分享圖標 success: function () { // 用戶確認分享后執行的回調函數 //alert('轉發成功!'); }, cancel: function () { // 用戶取消分享后執行的回調函數 //alert('轉發失敗!'); } }); wx.onMenuShareAppMessage({ title: '【斑斕·家】西安服務式酒店公寓地段', // 分享標題 desc: '曲江雁塔店、鍾樓南門店、高新店更多精彩房型陸續開通中……', // 分享描述 link: link, // 分享鏈接 imgUrl: imgUrls, // 分享圖標 success: function () { // 用戶確認分享后執行的回調函數 //alert('轉發成功!'); }, cancel: function () { // 用戶取消分享后執行的回調函數 //alert('轉發失敗!'); } }); }); // 限定縮放級別 var mapOptions = { 'minZoom': 12, 'maxZoom': 18 }; var map = new BMap.Map("allmap", mapOptions); // 創建Map實例 map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] })); //添加地圖類型控件 map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_ZOOM, offset: new BMap.Size(5, 5) })); var imgurl = "/Images/HotPlace/overlaybig.png"; var myGeo = new BMap.Geocoder(); var points = new Array(); // 當前城市 var city = '西安市'; // 標注 var mapData = ['34.2218208200039|108.967331106256,30,曲江雁塔店,曲江雁塔店.png,慈恩西路,大雁塔','34.2554845576708|108.96625890407,53,鍾樓南門店,鍾樓南門店.png,,鍾樓南門店','34.2308766900118|108.902508785079,30,高新店,高新店.png,號陝西省西安市雁塔區科技二路,高新店']; var infoBoxTemp = null; $(function () { $("#allmap").css("height", ($(window).height()) + "px"); // map.centerAndZoom(poin, 14); // 初始化地圖,城市名設置中心點 if (city == "上海市") { map.centerAndZoom("上海市", 14); } else if (city == "西安市") { map.centerAndZoom("西安市", 13); } else if (city == "北京市") { map.centerAndZoom("北京市", 13); } else if (city == "成都市") { map.centerAndZoom("成都市", 14); } else if (city == "廣州市") { map.centerAndZoom("廣州市", 14); } else { map.centerAndZoom(city); } for (var i = 0; i < mapData.length; i++) { (function () { var content = "<table class='infowindow'>"; content += "<tr>"; content += "<td rowspan='4' style='width:106px;height:120px'><img src='/Images/HotPlace/100120/" + mapData[i].split(',')[3] + "' /></td>"; content += "<td class='infoTitle'>" + mapData[i].split(',')[2] + "</td>"; content += "</tr>"; content += "<tr>"; content += "<td>地址:" + mapData[i].split(',')[4] + "</td>"; content += "</tr>"; content += "<tr>"; content += "<td>周邊:" + mapData[i].split(',')[5] + "</td>"; content += "</tr>"; content += "<tr>"; content += "<td><a href='http://map.baidu.com'>查看房源詳情</a></td>"; content += "</tr>"; content += "</table>"; var opts = { //title: "查看房源詳情", enableMessage: true, }; //var infoBox = new BMap.InfoWindow(content, opts); //新建infobox容器 var infoBox = new BMapLib.InfoBox( map, content, { boxStyle: { background: "transparent none repeat scroll 0% 0%", width: "308px", height: "123px" }, offset: new BMap.Size(10, 18),//此處貌似只能調整y的偏移 closeIconMargin: "4px 8px", closeIconUrl: "/Content/baidu/close.png", enableAutoPan: true } ); var pintx = mapData[i].split(',')[0].split('|')[1]; var pinty = mapData[i].split(',')[0].split('|')[0]; var point = new BMap.Point(pintx, pinty) points.push(point); var markerContent = "<div class='overlaybackground'><table class='customoverlay'>"; markerContent += "<thead>"; markerContent += "<tr>"; markerContent += "<th>"; markerContent += mapData[i].split(',')[2]; markerContent += "</th>"; markerContent += "</tr>"; markerContent += "</thead>"; markerContent += "<tbody>"; markerContent += "<tr>"; markerContent += "<td>(" + mapData[i].split(',')[1] + "個房源)</td>"; markerContent += "</tr>"; markerContent += "</tbody>"; markerContent += "</table></div>"; //新建富標注 var richMarker = new BMapLib.RichMarker( markerContent, point, { "anchor": new BMap.Size(-150, 0), "enableDragging": false } ); map.addOverlay(richMarker); richMarker.addEventListener("onclick", function (e) { //map.openInfoWindow(infoBox, point); if (infoBoxTemp) { infoBoxTemp.close(); } infoBoxTemp = infoBox; infoBox.open(richMarker.getPosition()); }); })() } //$("close").onclick = function () { // infoBox.close(); //} // document.getElementsByTagName('a')[0].addEventListener("touchstart", function (e) { alert(110) }) $("img").one("error", function (e) { $(this).attr("src", "/Images/HotPlace/100120/default.png"); }); }); function setCenter() { map.setViewport(points); } window.onresize = function () { $("#allmap").css("height", ($(window).height()) + "px"); } window.setTimeout(setCenter, 1000); </script> </body> </html>
InfoBox.js的源碼
/** * @fileoverview 百度地圖的自定義信息窗口,對外開放。 * 用戶自定義信息窗口的各種樣式。例如:border,margin,padding,color,background等 * 主入口類是<a href="symbols/BMapLib.InfoBox.html">InfoBox</a>, * 基於Baidu Map API 1.2。 * * @author Baidu Map Api Group * @version 1.2 */ /** * @namespace BMap的所有library類均放在BMapLib命名空間下 */ var BMapLib = window.BMapLib = BMapLib || {}; //常量,infoBox可以出現的位置,此版本只可實現上下兩個方向。 var INFOBOX_AT_TOP = 1, INFOBOX_AT_RIGHT = 2, INFOBOX_AT_BOTTOM = 3, INFOBOX_AT_LEFT = 4; (function () { //聲明baidu包 var T, baidu = T = baidu || { version: '1.5.0' }; baidu.guid = '$BAIDU$'; //以下方法為百度Tangram框架中的方法,請到http://tangram.baidu.com 查看文檔 (function () { window[baidu.guid] = window[baidu.guid] || {}; baidu.lang = baidu.lang || {}; baidu.lang.isString = function (source) { return '[object String]' == Object.prototype.toString.call(source); }; baidu.lang.isFunction = function (source) { return '[object Function]' == Object.prototype.toString.call(source); }; baidu.lang.Event = function (type, target) { this.type = type; this.returnValue = true; this.target = target || null; this.currentTarget = null; }; baidu.object = baidu.object || {}; baidu.extend = baidu.object.extend = function (target, source) { for (var p in source) { if (source.hasOwnProperty(p)) { target[p] = source[p]; } } return target; }; baidu.event = baidu.event || {}; baidu.event._listeners = baidu.event._listeners || []; baidu.dom = baidu.dom || {}; baidu.dom._g = function (id) { if (baidu.lang.isString(id)) { return document.getElementById(id); } return id; }; baidu._g = baidu.dom._g; baidu.event.on = function (element, type, listener) { type = type.replace(/^on/i, ''); element = baidu.dom._g(element); var realListener = function (ev) { // 1. 這里不支持EventArgument, 原因是跨frame的事件掛載 // 2. element是為了修正this listener.call(element, ev); }, lis = baidu.event._listeners, filter = baidu.event._eventFilter, afterFilter, realType = type; type = type.toLowerCase(); // filter過濾 if (filter && filter[type]) { afterFilter = filter[type](element, type, realListener); realType = afterFilter.type; realListener = afterFilter.listener; } // 事件監聽器掛載 if (element.addEventListener) { element.addEventListener(realType, realListener, false); } else if (element.attachEvent) { element.attachEvent('on' + realType, realListener); } // 將監聽器存儲到數組中 lis[lis.length] = [element, type, listener, realListener, realType]; return element; }; baidu.on = baidu.event.on; baidu.event.un = function (element, type, listener) { element = baidu.dom._g(element); type = type.replace(/^on/i, '').toLowerCase(); var lis = baidu.event._listeners, len = lis.length, isRemoveAll = !listener, item, realType, realListener; while (len--) { item = lis[len]; if (item[1] === type && item[0] === element && (isRemoveAll || item[2] === listener)) { realType = item[4]; realListener = item[3]; if (element.removeEventListener) { element.removeEventListener(realType, realListener, false); } else if (element.detachEvent) { element.detachEvent('on' + realType, realListener); } lis.splice(len, 1); } } return element; }; baidu.un = baidu.event.un; baidu.dom.g = function (id) { if ('string' == typeof id || id instanceof String) { return document.getElementById(id); } else if (id && id.nodeName && (id.nodeType == 1 || id.nodeType == 9)) { return id; } return null; }; baidu.g = baidu.G = baidu.dom.g; baidu.dom._styleFixer = baidu.dom._styleFixer || {}; baidu.dom._styleFilter = baidu.dom._styleFilter || []; baidu.dom._styleFilter.filter = function (key, value, method) { for (var i = 0, filters = baidu.dom._styleFilter, filter; filter = filters[i]; i++) { if (filter = filter[method]) { value = filter(key, value); } } return value; }; baidu.string = baidu.string || {}; baidu.string.toCamelCase = function (source) { //提前判斷,提高getStyle等的效率 thanks xianwei if (source.indexOf('-') < 0 && source.indexOf('_') < 0) { return source; } return source.replace(/[-_][^-_]/g, function (match) { return match.charAt(1).toUpperCase(); }); }; baidu.dom.setStyle = function (element, key, value) { var dom = baidu.dom, fixer; // 放棄了對firefox 0.9的opacity的支持 element = dom.g(element); key = baidu.string.toCamelCase(key); if (fixer = dom._styleFilter) { value = fixer.filter(key, value, 'set'); } fixer = dom._styleFixer[key]; (fixer && fixer.set) ? fixer.set(element, value) : (element.style[fixer || key] = value); return element; }; baidu.setStyle = baidu.dom.setStyle; baidu.dom.setStyles = function (element, styles) { element = baidu.dom.g(element); for (var key in styles) { baidu.dom.setStyle(element, key, styles[key]); } return element; }; baidu.setStyles = baidu.dom.setStyles; baidu.browser = baidu.browser || {}; baidu.browser.ie = baidu.ie = /msie (\d+\.\d+)/i.test(navigator.userAgent) ? (document.documentMode || +RegExp['\x241']) : undefined; baidu.dom._NAME_ATTRS = (function () { var result = { 'cellpadding': 'cellPadding', 'cellspacing': 'cellSpacing', 'colspan': 'colSpan', 'rowspan': 'rowSpan', 'valign': 'vAlign', 'usemap': 'useMap', 'frameborder': 'frameBorder' }; if (baidu.browser.ie < 8) { result['for'] = 'htmlFor'; result['class'] = 'className'; } else { result['htmlFor'] = 'for'; result['className'] = 'class'; } return result; })(); baidu.dom.setAttr = function (element, key, value) { element = baidu.dom.g(element); if ('style' == key) { element.style.cssText = value; } else { key = baidu.dom._NAME_ATTRS[key] || key; element.setAttribute(key, value); } return element; }; baidu.setAttr = baidu.dom.setAttr; baidu.dom.setAttrs = function (element, attributes) { element = baidu.dom.g(element); for (var key in attributes) { baidu.dom.setAttr(element, key, attributes[key]); } return element; }; baidu.setAttrs = baidu.dom.setAttrs; baidu.dom.create = function (tagName, opt_attributes) { var el = document.createElement(tagName), attributes = opt_attributes || {}; return baidu.dom.setAttrs(el, attributes); }; T.undope = true; })(); /** * @exports InfoBox as BMapLib.InfoBox */ var InfoBox = /** * InfoBox類的構造函數 * @class InfoBox <b>入口</b>。 * 可以自定義border,margin,padding,關閉按鈕等等。 * @constructor * @param {Map} map Baidu map的實例對象. * @param {String} content infoBox中的內容. * @param {Json Object} opts 可選的輸入參數,非必填項。可輸入選項包括:<br /> * {<br />"<b>offset</b>" : {Size} infoBox的偏移量 * <br />"<b>boxClass</b>" : {String} 定義infoBox的class, * <br />"<b>boxStyle</b>" : {Json} 定義infoBox的style,此項會覆蓋boxClass<br /> * <br />"<b>closeIconMargin</b>" : {String} 關閉按鈕的margin <br /> * <br />"<b>closeIconUrl</b>" : {String} 關閉按鈕的url地址 <br /> * <br />"<b>enableAutoPan</b>" : {Boolean} 是否啟動自動平移功能 <br /> * <br />"<b>align</b>" : {Number} 基於哪個位置進行定位,取值為[INFOBOX_AT_TOP,INFOBOX_AT_BOTTOM]<br /> * }<br />. * @example <b>參考示例:</b><br /> * var infoBox = new BMapLib.InfoBox(map,"百度地圖api",{boxStyle:{background:"url('tipbox.gif') no-repeat center top",width: "200px"},closeIconMargin: "10px 2px 0 0",enableAutoPan: true ,alignBottom: false}); */ BMapLib.InfoBox = function (map, content, opts) { this._content = content || ""; this._isOpen = false; this._map = map; this._opts = opts = opts || {}; this._opts.offset = opts.offset || new BMap.Size(0, 0); this._opts.boxClass = opts.boxClass || "infoBox"; this._opts.boxStyle = opts.boxStyle || {}; this._opts.closeIconMargin = opts.closeIconMargin || "2px"; this._opts.closeIconUrl = opts.closeIconUrl || "close.png"; this._opts.enableAutoPan = opts.enableAutoPan ? true : false; this._opts.align = opts.align || INFOBOX_AT_TOP; } InfoBox.prototype = new BMap.Overlay(); InfoBox.prototype.initialize = function (map) { var me = this; var div = this._div = baidu.dom.create('div', { "class": this._opts.boxClass }); baidu.dom.setStyles(div, this._opts.boxStyle); //設置position為absolute,用於定位 div.style.position = "absolute"; this._setContent(this._content); var floatPane = map.getPanes().floatPane; floatPane.style.width = "auto"; floatPane.appendChild(div); //設置完內容后,獲取div的寬度,高度 this._getInfoBoxSize(); //this._boxWidth = parseInt(this._div.offsetWidth,10); //this._boxHeight = parseInt(this._div.offsetHeight,10); //阻止各種冒泡事件 baidu.event.on(div, "onmousedown", function (e) { me._stopBubble(e); }); baidu.event.on(div, "onmouseover", function (e) { me._stopBubble(e); }); baidu.event.on(div, "click", function (e) { me._stopBubble(e); }); baidu.event.on(div, "dblclick", function (e) { me._stopBubble(e); }); // 手機端阻止冒泡 baidu.event.on(div, "touchstart", function (e) { me._stopBubble(e); }); baidu.event.on(div, "touchend", function (e) { me._stopBubble(e); }); baidu.event.on(div, "touch", function (e) { me._stopBubble(e); }); return div; } InfoBox.prototype.draw = function () { this._isOpen && this._adjustPosition(this._point); } /** * 打開infoBox * @param {Marker|Point} anchor 要在哪個marker或者point上打開infobox * @return none * * @example <b>參考示例:</b><br /> * infoBox.open(); */ InfoBox.prototype.open = function (anchor) { var me = this, poi; if (!this._isOpen) { this._map.addOverlay(this); this._isOpen = true; //延遲10ms派發open事件,使后綁定的事件可以觸發。 setTimeout(function () { me._dispatchEvent(me, "open", { "point": me._point }); }, 10); } if (anchor instanceof BMap.Point) { poi = anchor; //清除之前存在的marker事件綁定,如果存在的話 this._removeMarkerEvt(); } else if (anchor instanceof BMap.Marker) { //如果當前marker不為空,說明是第二個marker,或者第二次點open按鈕,先移除掉之前綁定的事件 if (this._marker) { this._removeMarkerEvt(); } poi = anchor.getPosition(); this._marker = anchor; !this._markerDragend && this._marker.addEventListener("dragend", this._markerDragend = function (e) { me._point = e.point; me._adjustPosition(me._point); me._panBox(); me.show(); }); //給marker綁定dragging事件,拖動marker的時候,infoBox也跟隨移動 !this._markerDragging && this._marker.addEventListener("dragging", this._markerDragging = function () { me.hide(); me._point = me._marker.getPosition(); me._adjustPosition(me._point); }); } //打開的時候,將infowindow顯示 this.show(); this._point = poi; this._panBox(); this._adjustPosition(this._point); } /** * 關閉infoBox * @return none * * @example <b>參考示例:</b><br /> * infoBox.close(); */ InfoBox.prototype.close = function () { if (this._isOpen) { this._map.removeOverlay(this); this._remove(); this._isOpen = false; this._dispatchEvent(this, "close", { "point": this._point }); } } /** * 打開infoBox時,派發事件的接口 * @name InfoBox#Open * @event * @param {Event Object} e 回調函數會返回event參數,包括以下返回值: * <br />{"<b>target</b> : {BMap.Overlay} 觸發事件的元素, * <br />"<b>type</b>:{String} 事件類型, * <br />"<b>point</b>:{Point} infoBox的打開位置} * * @example <b>參考示例:</b> * infoBox.addEventListener("open", function(e) { * alert(e.type); * }); */ /** * 關閉infoBox時,派發事件的接口 * @name InfoBox#Close * @event * @param {Event Object} e 回調函數會返回event參數,包括以下返回值: * <br />{"<b>target</b> : {BMap.Overlay} 觸發事件的元素, * <br />"<b>type</b>:{String} 事件類型, * <br />"<b>point</b>:{Point} infoBox的關閉位置} * * @example <b>參考示例:</b> * infoBox.addEventListener("close", function(e) { * alert(e.type); * }); */ /** * 啟用自動平移 * @return none * * @example <b>參考示例:</b><br /> * infoBox.enableAutoPan(); */ InfoBox.prototype.enableAutoPan = function () { this._opts.enableAutoPan = true; } /** * 禁用自動平移 * @return none * * @example <b>參考示例:</b><br /> * infoBox.disableAutoPan(); */ InfoBox.prototype.disableAutoPan = function () { this._opts.enableAutoPan = false; } /** * 設置infoBox的內容 * @param {String|HTMLElement} content 彈出氣泡中的內容 * @return none * * @example <b>參考示例:</b><br /> * infoBox.setContent("百度地圖API"); */ InfoBox.prototype.setContent = function (content) { this._setContent(content); this._getInfoBoxSize(); this._adjustPosition(this._point); } /** * 設置信息窗的地理位置 * @param {Point} point 設置position * @return none * * @example <b>參考示例:</b><br /> * infoBox.setPosition(new BMap.Point(116.35,39.911)); */ InfoBox.prototype.setPosition = function (poi) { this._point = poi; this._adjustPosition(poi); this._removeMarkerEvt(); } /** * 獲得信息窗的地理位置 * @param none * @return {Point} 信息窗的地理坐標 * * @example <b>參考示例:</b><br /> * infoBox.getPosition(); */ InfoBox.prototype.getPosition = function () { return this._point; } /** * 返回信息窗口的箭頭距離信息窗口在地圖 * 上所錨定的地理坐標點的像素偏移量。 * @return {Size} Size * * @example <b>參考示例:</b><br /> * infoBox.getOffset(); */ InfoBox.prototype.getOffset = function () { return this._opts.offset; }, /** *@ignore * 刪除overlay,調用Map.removeOverlay時將調用此方法, * 將移除覆蓋物的容器元素 */ InfoBox.prototype._remove = function () { var me = this; if (this.domElement && this.domElement.parentNode) { //防止內存泄露 baidu.event.un(this._div.firstChild, "click", me._closeHandler()); this.domElement.parentNode.removeChild(this.domElement); } this.domElement = null; this._isOpen = false; this.dispatchEvent("onremove"); }, baidu.object.extend(InfoBox.prototype, { /** * 獲取關閉按鈕的html * @return IMG 關閉按鈕的HTML代碼 */ _getCloseIcon: function () { var img = "<img src='" + this._opts.closeIconUrl + "' align='right' style='position:absolute;right:0px;cursor:pointer;margin:" + this._opts.closeIconMargin + "'/>"; return img; }, /** * 設置infoBox的內容 * @param {String|HTMLElement} content 彈出氣泡中的內容 * @return none * * @example <b>參考示例:</b><br /> * infoBox.setContent("百度地圖API"); */ _setContent: function (content) { if (!this._div) { return; } var closeHtml = this._getCloseIcon(); //string類型的content if (typeof content.nodeType === "undefined") { this._div.innerHTML = closeHtml + content; } else { this._div.innerHTML = closeHtml; this._div.appendChild(content); } this._content = content; //添加click關閉infobox事件 this._addEventToClose(); }, /** * 調整infobox的position * @return none */ _adjustPosition: function (poi) { var pixel = this._getPointPosition(poi); var icon = this._marker && this._marker.getIcon(); switch (this._opts.align) { case INFOBOX_AT_TOP: if (this._marker) { this._div.style.bottom = -(pixel.y - this._opts.offset.height - icon.anchor.height + icon.infoWindowAnchor.height) - this._marker.getOffset().height + 2 + "px"; } else { this._div.style.bottom = -(pixel.y - this._opts.offset.height) + "px"; } break; case INFOBOX_AT_BOTTOM: if (this._marker) { this._div.style.top = pixel.y + this._opts.offset.height - icon.anchor.height + icon.infoWindowAnchor.height + this._marker.getOffset().height + "px"; } else { this._div.style.top = pixel.y + this._opts.offset.height + "px"; } break; } if (this._marker) { this._div.style.left = pixel.x - icon.anchor.width + this._marker.getOffset().width + icon.infoWindowAnchor.width - this._boxWidth / 2 + "px"; } else { this._div.style.left = pixel.x - this._boxWidth / 2 + "px"; } }, /** * 得到infobox的position * @return Point infobox當前的position */ _getPointPosition: function (poi) { this._pointPosition = this._map.pointToOverlayPixel(poi); return this._pointPosition; }, /** * 得到infobox的高度跟寬度 * @return none */ _getInfoBoxSize: function () { this._boxWidth = parseInt(this._div.offsetWidth, 10); this._boxHeight = parseInt(this._div.offsetHeight, 10); }, /** * 添加關閉事件 * @return none */ _addEventToClose: function () { var me = this; baidu.event.on(this._div.firstChild, "click", me._closeHandler()); this._hasBindEventClose = true; }, /** * 處理關閉事件 * @return none */ _closeHandler: function () { var me = this; return function (e) { me.close(); } }, /** * 阻止事件冒泡 * @return none */ _stopBubble: function (e) { if (e && e.stopPropagation) { e.stopPropagation(); } else { window.event.cancelBubble = true; } }, /** * 自動平移infobox,使其在視野中全部顯示 * @return none */ _panBox: function () { if (!this._opts.enableAutoPan) { return; } var mapH = parseInt(this._map.getContainer().offsetHeight, 10), mapW = parseInt(this._map.getContainer().offsetWidth, 10), boxH = this._boxHeight, boxW = this._boxWidth; //infobox窗口本身的寬度或者高度超過map container if (boxH >= mapH || boxW >= mapW) { return; } //如果point不在可視區域內 if (!this._map.getBounds().containsPoint(this._point)) { this._map.setCenter(this._point); } var anchorPos = this._map.pointToPixel(this._point), panTop, panBottom, panY, //左側超出 panLeft = boxW / 2 - anchorPos.x, //右側超出 panRight = boxW / 2 + anchorPos.x - mapW; if (this._marker) { var icon = this._marker.getIcon(); } //基於bottom定位,也就是infoBox在上方的情況 switch (this._opts.align) { case INFOBOX_AT_TOP: //上側超出 var h = this._marker ? icon.anchor.height + this._marker.getOffset().height - icon.infoWindowAnchor.height : 0; panTop = boxH - anchorPos.y + this._opts.offset.height + h + 2; break; case INFOBOX_AT_BOTTOM: //下側超出 var h = this._marker ? -icon.anchor.height + icon.infoWindowAnchor.height + this._marker.getOffset().height + this._opts.offset.height : 0; panBottom = boxH + anchorPos.y - mapH + h + 4; break; } panX = panLeft > 0 ? panLeft : (panRight > 0 ? -panRight : 0); panY = panTop > 0 ? panTop : (panBottom > 0 ? -panBottom : 0); this._map.panBy(panX, panY); }, _removeMarkerEvt: function () { this._markerDragend && this._marker.removeEventListener("dragend", this._markerDragend); this._markerDragging && this._marker.removeEventListener("dragging", this._markerDragging); this._markerDragend = this._markerDragging = null; }, /** * 集中派發事件函數 * * @private * @param {Object} instance 派發事件的實例 * @param {String} type 派發的事件名 * @param {Json} opts 派發事件里添加的參數,可選 */ _dispatchEvent: function (instance, type, opts) { type.indexOf("on") != 0 && (type = "on" + type); var event = new baidu.lang.Event(type); if (!!opts) { for (var p in opts) { event[p] = opts[p]; } } instance.dispatchEvent(event); } }); })();