百度地图自定义头像
一、功能需求
地图上添加水滴背景的用户头像,并附带点击功能。效果如下:
二、代码模块
- 自定义覆盖物的构造函数
//自定义覆盖物
function CircleImgOverlay(point, headerImg, { width = 57, height = 64 }) {
this._point = point;
this._headerImg = headerImg;
this._width = width;
this._height = height;
}
- 继承覆盖物的抽象基类
CircleImgOverlay.prototype = new BMap.Overlay();
- 调用initialize抽象方法,初始化覆盖物
CircleImgOverlay.prototype.initialize = function(map){
this._map = map;//全局map对象
var divBox = document.createElement("div");
var divImg = document.createElement("div");
divBox.style.position = "absolute";
divBox.style.width = this._width + "px";
divBox.style.height = this._height + "px";
divBox.style.backgroundImage = "url("+require("../../assets/grid/union.png")+")";//水滴背景图
divBox.style.backgroundSize = "100% 100%";
divImg.style.backgroundImage = `url(${this._headerImg})`;
divImg.style.width = "53px";
divImg.style.height = "53px";
divImg.style.marginLeft = "2px";
divImg.style.marginTop = "2px";
divImg.style.borderRadius = "50%";
divImg.style.backgroundSize = "cover";
divImg.style.cursor="pointer";
divBox.appendChild(divImg);
//绑定头像点击事件
divBox.onclick = function(){
}
map.getPanes().markerPane.appendChild(divBox);
this._div = divBox;
return divBox;
}
- 实现绘制方法,将覆盖物放到正确的位置
CircleImgOverlay.prototype.draw = function(){
var map = this._map;
var position = map.pointToOverlayPixel(this._point);
this._div.style.left = position.x - this._width / 2 + "px";
this._div.style.top = position.y - this._height * 7 / 10 + "px";
}
- 调用方法,实现功能
let headerImg = new CircleImgOverlay(new BMap.Point(user.longitude, user.latitude),"../../assets/grid/head.png", {});
map.addOverlay(headerImg);
- 效果展示
三、参考文档
官方文档(自定义覆盖物)
博客文档