// 定義構造函數並繼承Overlay
function CustomOverlay(center, img, name, text){
this._center = center;
this._img = img;
this._name = name;
this._text = text;
}
// 繼承API BMap.Overlay
CustomOverlay.prototype = new BMap.Overlay();
// 初始化自定義覆蓋物
CustomOverlay.prototype.initialize = function (map) {
// 保存map對象實例
this._map = map;
// 創建div元素,作爲自定義覆蓋物的容器
var div = document.createElement("div");
div.style.position = 'absolute';
// 根據參數設置元素外觀
div.style.background = "url(" + this._img + ") no-repeat 0 -18px";
div.style.MozUserSelect = 'none';
var oneDiv = document.createElement("div");
$(oneDiv).css({
"height":"30",
"width":"18",
"white-space": "nowrap",
"color":"#fff",
"text-align":"center",
"line-height":"30px"
});
$(div).append('<div class="detail" style="display:none; position:absolute;padding:10px; left:25px; background:#fff;">' +
'<div style="width:258px;height: 20px;"><span style="float: left;">名稱:</span><span style="float: left;">' + this._name +
'</span></div><div style="width: 258px;height: 20px;"><span style="float:left;">備註:</span><span style="float:left;">'+ this._text +'</span></div></div>');
div.appendChild(oneDiv);
$(div).mousemove(function(){
$(this).css("z-index","999999");
$(this).children(".detail").css("display","block");
});
$(div).mouseout(function(){
$(this).children(".detail").css("display","none");
});
// 將div添加到覆蓋物容器中
map.getPanes().markerPane.appendChild(div);
// 保存div實例
this._div = div;
// 需要將div元素作爲方法的返回值,當調用該覆蓋物的show、
// hide方法,或者對覆蓋物進行移除時,API都將操作此元素
return div;
}
// 繪製覆蓋物
CustomOverlay.prototype.draw = function () {
// 根據地理座標轉換爲像素座標,並設置給容器
var position = this._map.pointToOverlayPixel(this._center);
this._div.style.left = position.x - 10 + 'px';
this._div.style.top = position.y - 10 + 'px';
}
// 實現顯示方法
CustomOverlay.prototype.show = function () {
if(this._div){
this._div.style.display = '';
}
}
// 實現隱藏方法
CustomOverlay.prototype.hide = function () {
if(this._div){
this._div.style.display = 'none';
}
}
在百度地圖上,創建自定義覆蓋物,鼠標經過時顯示詳情
關鍵代碼:
function buildBaiduMap(result) {
// 創建Map實例
// 構造地圖時,關閉地圖可點功能
var map = new BMap.Map("allmap", {
enableMapClick: false
});
var pointArray = [];
for (var i = 0; i < result.length; i++) {
var one = result[i];
var longitude = one['longitude'];
var latitude = one['latitude'];
var name = one['name'];
var remark = one['remark'];
var point = new BMap.Point(longitude, latitude);
var marker = new CustomOverlay(point, 'images/cursor.png', name, remark);
pointArray.push(point);
map.addOverlay(marker);
}
//讓所有點在視野範圍內
map.setViewport(pointArray);
}
效果展示:
result數據格式形如:
[{"longitude":"120.489327","latitude":"31.501122","name":"**社區**棟","remark":"測試樓棟1"},{"longitude":"120.489839","latitude":"31.502023","name":"**社區**棟","remark":"測試樓棟2"},{"longitude":"120.490629","latitude":"31.502323","name":"**一社區**棟","remark":"測試樓棟3"}]