实现效果:
图标用的是字体图标,为了方便动态改变颜色
关键代码
function ComplexCustomOverlay(params) {
let defaultParams = {
point: { lng: 0, lat: 0 },
fontSize: 28,
deg: 0,
className: '',
color: 'red',
};
defaultParams = Object.assign(defaultParams, params);
this._point = defaultParams.point; // 坐标
this._fontSize = defaultParams.fontSize; // 字体图标大小
this._deg = defaultParams.deg; // 旋转角度
this._className = defaultParams.className; // class名称(图标名称)
this._color = defaultParams.color; // 设置图标的颜色
}
ComplexCustomOverlay.prototype = new BMap.Overlay();
// 实现初始化方法
ComplexCustomOverlay.prototype.initialize = function (map) {
// 保存map对象实例
this._map = map;
// 创建div元素,作为自定义覆盖物的容器
var div = (this._div = document.createElement('div'));
div.style.position = 'absolute';
div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat); // 聚合功能?
// 可以根据参数设置元素外观
div.style.height = this._fontSize + 'px';
div.style.width = this._fontSize + 'px';
var arrow = (this._arrow = document.createElement('i'));
arrow.className = 'iconfont ' + this._className;
arrow.style.display = 'inline-block';
arrow.style.fontSize = this._fontSize + 'px';
arrow.style.color = this._color;
arrow.style.transform = 'rotate(' + this._deg + 'deg)';
div.appendChild(arrow); // 将div添加到覆盖物容器中
map.getPanes().labelPane.appendChild(div); //getPanes(),返回值:MapPane,返回地图覆盖物容器列表 labelPane呢???
return div;
};
// 实现绘制方法
ComplexCustomOverlay.prototype.draw = function () {
var map = this._map;
var pixel = map.pointToOverlayPixel(this._point);
this._div.style.left = pixel.x - parseInt(this._fontSize) / 2 + 'px';
this._div.style.top = pixel.y - parseInt(this._fontSize) / 2 + 'px';
};
//4、自定义覆盖物添加事件方法
ComplexCustomOverlay.prototype.addEventListener = function (event, fun) {
this._div['on' + event] = fun;
};
调用方式:
let params = {
point: new BMap.Point(114.00491526048702, 22.53049351287813),
deg: 90,
className: 'icon-shangzhijiantou1', // 字体图标className
color: 'red',
};
var myCompOverlay = new ComplexCustomOverlay(params);
map.addOverlay(myCompOverlay); //将标注添加到地图中