百度地图自定义头像

百度地图自定义头像

一、功能需求
地图上添加水滴背景的用户头像,并附带点击功能。效果如下:
在这里插入图片描述
二、代码模块

  1. 自定义覆盖物的构造函数
//自定义覆盖物
function CircleImgOverlay(point, headerImg, { width = 57, height = 64 }) {
  this._point = point;
  this._headerImg = headerImg;
  this._width = width;
  this._height = height;
}
  1. 继承覆盖物的抽象基类
CircleImgOverlay.prototype = new BMap.Overlay();
  1. 调用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;
}
  1. 实现绘制方法,将覆盖物放到正确的位置
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";
}
  1. 调用方法,实现功能
let headerImg = new CircleImgOverlay(new BMap.Point(user.longitude, user.latitude),"../../assets/grid/head.png", {});
map.addOverlay(headerImg);
  1. 效果展示
    在这里插入图片描述
    三、参考文档
    官方文档(自定义覆盖物)
    博客文档
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值