代码
var map = new BMap.Map('map', {
style: {styleJson: snowStyle},
});
map.centerAndZoom(new BMap.Point(116.38623, 39.95577), 14);
map.enableKeyboard();
map.enableScrollWheelZoom();
function createDOM(config) {
var canvas = document.createElement('canvas');
var dpr = window.devicePixelRatio || 1;
canvas.style.width = 150 + 'px';
canvas.style.height = 150 + 'px';
canvas.setAttribute('width', 150 * dpr);
canvas.setAttribute('height', 150 * dpr);
var ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
ctx.save();
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.arc(75, 75, 40, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.save();
ctx.beginPath();
ctx.translate(75, 75);
ctx.rotate(0.6 * Math.PI);
ctx.lineWidth = config.lineWidth;
ctx.lineCap = 'butt';
ctx.strokeStyle = '#add';
ctx.arc(0, 0, config.radius, 0, 1.8 * Math.PI * 0.5, true);
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, config.radius, 0, 1.8 * Math.PI * 0.8, true);
ctx.strokeStyle = '#9d55ef';
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, config.radius, 0, 1.8 * Math.PI * 0.5, false);
ctx.strokeStyle = 'blue';
ctx.stroke();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.fillStyle = '#000';
ctx.font = '26px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(config.data * 100 + '', config.width * 1.5, config.height * 1.5);
ctx.restore();
return canvas;
}
// 实例化自定义canvas覆盖物
var customOverlay = new BMap.CustomOverlay(createDOM, {
point: new BMap.Point(116.38623, 39.95577),
offsetX: 0,
offsetY: 0,
minZoom: 13,
maxZoom: 19,
properties: {
width: 50,
height: 50,
radius: 50,
lineWidth: 20,
data: 2,
},
});
// 添加自定义canvas到地图上
map.addOverlay(customOverlay);
// 绑定点击事件
customOverlay.addEventListener('click', function (e) {
var data = e.target.properties.data * 100;
alert(data);
});
添加 canvas 覆盖物
预览