代码
const map = new BMap.Map('map');
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
var layer = new BMap.ClusterLayer({
renderStage: 'poi',
// 返回 {canvas, id},id 相同的贴图在图集里只存一份
clusterIcon: function (props) {
var size = 26 + Math.min(24, Math.round(props.pointCount / 40));
return {
canvas: makeSquareBubble(props.pointCountAbbrev, size),
id: 'square_' + props.pointCount,
};
},
clusterIconSize: function (props) {
var size = 26 + Math.min(24, Math.round(props.pointCount / 40));
return [size, size];
},
});
layer.setData(randomPoints(5000));
map.addLayer(layer);
function makeSquareBubble(text, size) {
var dpr = window.devicePixelRatio || 1;
var canvas = document.createElement('canvas');
canvas.width = canvas.height = size * dpr;
var ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
ctx.fillStyle = 'rgba(20, 20, 40, 0.85)';
ctx.fillRect(0, 0, size, size);
ctx.strokeStyle = 'rgba(0, 220, 255, 1)';
ctx.lineWidth = 2;
ctx.strokeRect(1, 1, size - 2, size - 2);
ctx.fillStyle = '#0df';
ctx.font = 'bold 13px 微软雅黑';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(String(text), size / 2, size / 2);
return canvas;
}
/**
* 随机点数据(北京附近),properties.count 用于自定义样式演示
*/
function randomPoints(n, spread) {
spread = spread || 1;
var feats = [];
for (var i = 0; i < n; i++) {
feats.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [116.1 + Math.random() * 0.6 * spread, 39.7 + Math.random() * 0.45 * spread],
},
properties: {count: Math.round(Math.random() * 100), name: 'poi_' + i},
});
}
return {type: 'FeatureCollection', features: feats};
}
通过 clusterIcon 自定义聚合气泡样式
预览