代码
var map = new BMap.Map('map');
map.centerAndZoom(new BMap.Point(116.404, 39.915), 14);
map.enableScrollWheelZoom();
function createCanvas(properties) {
var size = 60;
var canvas = document.createElement('canvas');
canvas.width = size * 2;
canvas.height = size * 2;
canvas.style.width = size + 'px';
canvas.style.height = size + 'px';
var ctx = canvas.getContext('2d');
var cx = size,
cy = size,
r = size * 0.7;
// 外圈
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fillStyle = properties.color;
ctx.globalAlpha = 0.2;
ctx.fill();
// 内圈
ctx.beginPath();
ctx.arc(cx, cy, r * 0.6, 0, Math.PI * 2);
ctx.globalAlpha = 1;
ctx.fillStyle = properties.color;
ctx.fill();
// 文字
ctx.fillStyle = '#fff';
ctx.font = 'bold ' + r * 0.6 + 'px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(properties.label, cx, cy);
return canvas;
}
var canvasLayer = new BMap.DOMLayer(createCanvas, {
anchors: [0.5, 0.5],
useTranslate: true,
});
map.addLayer(canvasLayer);
canvasLayer.setData({
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.404, 39.915]},
properties: {label: 'A', color: '#ff4d4f'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.425, 39.93]},
properties: {label: 'B', color: '#1677ff'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.38, 39.905]},
properties: {label: 'C', color: '#52c41a'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.415, 39.9]},
properties: {label: 'D', color: '#722ed1'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.39, 39.935]},
properties: {label: 'E', color: '#faad14'},
},
],
});
var textInfo = document.querySelector('#text');
canvasLayer.addEventListener('click', function (e) {
var properties = e.target.properties;
textInfo.innerText = '点击了 ' + properties.label;
textInfo.style.background = properties.color;
textInfo.style.color = '#fff';
});
预览