代码
const map = new BMap.Map('map');
map.centerAndZoom(new BMap.Point(116.404, 39.915), 14);
const data = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.38, 39.92]},
properties: {name: 'A点'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.4, 39.91]},
properties: {name: 'B点'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.42, 39.93]},
properties: {name: 'C点'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.41, 39.9]},
properties: {name: 'D点'},
},
{
type: 'Feature',
geometry: {type: 'Point', coordinates: [116.39, 39.89]},
properties: {name: 'E点'},
},
],
};
function createIcon(properties) {
const canvas = document.createElement('canvas');
canvas.width = 80;
canvas.height = 30;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#1b8eec';
ctx.beginPath();
ctx.roundRect(0, 0, 80, 30, 6);
ctx.fill();
ctx.fillStyle = '#fff';
ctx.font = 'bold 14px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(properties.name || 'POI', 40, 15);
return {canvas, id: properties.name};
}
const pointLayer = new BMap.PointLayer({
icon: (properties) => createIcon(properties),
iconSize: [60, 25],
opacity: 1,
isFlat: false,
enablePicked: true, // 开启点击拾取
referCenter: new BMap.Point(116.404, 39.915),
});
pointLayer.addEventListener('click', function (e) {
if (e.value) {
document.getElementById('text').textContent = '选中:' + e.value.properties.name;
}
});
pointLayer.setData(data);
map.addLayer(pointLayer);
BMap.PointLayer 支持通过 Canvas 自定义图标,并可根据点数据动态绘制图标内容
预览