R Leaflet使用clusterOptions实现集群饼图出现方形变形如何调整代码
解决方案
你的饼图变成方形的核心原因是原有代码的SVG画布尺寸固定为60px,当集群点位数量过大时,动态计算的饼图外半径超过了画布尺寸,边缘被截断,就出现了方形效果,和分组数量无关。你只需要修改代码中固定的SVG尺寸逻辑,改为动态适配饼图大小即可,具体修改如下:
需修改的核心位置
- 移除固定的SVG宽高、viewBox配置,改为根据饼图实际大小动态计算
- 同步调整SVG的偏移值,保证饼图中心和集群点位对齐
- 可选:给环形宽度增加上限,避免点位极多的时候饼图过大影响交互
修改后的完整JS代码
jsscript3<- paste0( "function(cluster) { const groups= [",paste("'",levels(factor(pts$Sector)),"'",sep="",collapse=","),"]; const colors= { groups: [",paste("'",beatCol(levels(factor(pts$Sector))),"'",sep="",collapse=","),"], center:'#ddd', text:'black' }; const markers= cluster.getAllChildMarkers(); const proportions= groups.map(group => markers.filter(marker => marker.options.group === group).length / markers.length); function sum(arr, first= 0, last) { return arr.slice(first, last).reduce((total, curr) => total+curr, 0); } const cumulativeProportions= proportions.map((val, i, arr) => sum(arr, 0, i+1)); cumulativeProportions.unshift(0); // 新增:给环形宽度加上限,避免无限变大,可根据需求调整最大值 const width = Math.min(2*Math.sqrt(markers.length), 40); const radius= 15+width/2; // 新增:计算饼图外半径+2px边距,得到需要的画布半长 const svgHalfSize = radius + width/2 + 2; // 新增:计算需要的偏移值,保证图标中心对准点位 const offset = -svgHalfSize + 6; // 6是leaflet集群图标默认的偏移修正,可微调 const arcs= cumulativeProportions.map((prop, i) => { return { x : radius*Math.sin(2*Math.PI*prop), y : -radius*Math.cos(2*Math.PI*prop), long: proportions[i-1] >.5 ? 1 : 0 }}); const paths= proportions.map((prop, i) => { if (prop === 0) return ''; else if (prop === 1) return `<circle cx='0' cy='0' r='${radius}' fill='none' stroke='${colors.groups[i]}' stroke-width='${width}' stroke-alignment='center' stroke-linecap='butt' />`; else return `<path d='M ${arcs[i].x} ${arcs[i].y} A ${radius} ${radius} 0 ${arcs[i+1].long} 1 ${arcs[i+1].x} ${arcs[i+1].y}' fill='none' stroke='${colors.groups[i]}' stroke-width='${width}' stroke-alignment='center' stroke-linecap='butt' />` }); return new L.DivIcon({ // 修改:动态设置SVG尺寸、viewBox、偏移 html: ` <svg width='${svgHalfSize*2}' height='${svgHalfSize*2}' viewBox='-${svgHalfSize} -${svgHalfSize} ${svgHalfSize*2} ${svgHalfSize*2}' style='width: ${svgHalfSize*2}px; height: ${svgHalfSize*2}px; position: relative; top: ${offset}px; left: ${offset}px;' > <circle cx='0' cy='0' r='15' stroke='none' fill='${colors.center}' /> <text x='0' y='0' dominant-baseline='central' text-anchor='middle' fill='${colors.text}' font-size='15'>${markers.length}</text> ${paths.join('')} </svg> `, className: 'marker-cluster' }); }")
如果需要控制集群图标最大尺寸,调整Math.min(2*Math.sqrt(markers.length), 40)里的40即可,数值越大允许的环形宽度越大,最大饼图尺寸也越大。
内容的提问来源于stack exchange,提问作者J.Doe
相关产品推荐
相关产品推荐

