// 定义构造函数并继承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"}]