使用D3.geoPath实现过滤后美国县域地图居中和缩放适配SVG容器
解决方案
你只需要给geoPath配置适配筛选后县域范围的投影即可,D3提供了fitSize方法可以自动计算投影的缩放、偏移参数,让选中的地理要素刚好填满指定的画布尺寸,修改后的代码如下:
var width=960, height=600, centered; const svgElement = d3.select(ref.current) .append("svg") .attr("preserveAspectRatio", "xMinYMin meet") .attr("viewBox", [0,0,width,height]); // 初始化美国常用的Albers投影,和原默认渲染的形状保持一致 const projection = d3.geoAlbersUsa(); // 将投影传入geoPath var path = d3.geoPath().projection(projection); d3.json("https://d3js.org/us-10m.v2.json").then((d) => { d.objects.counties.geometries = d.objects.counties.geometries.filter(function(item) { return props.data.indexOf(item.id) > -1 }) // 拿到筛选后的县域FeatureCollection const countiesCollection = topojson.feature(d, d.objects.counties); // 自动调整投影参数,让所有选中县域刚好铺满宽高为width*height的画布 projection.fitSize([width, height], countiesCollection); const counties = countiesCollection.features; svgElement.append("g") .attr("class", "filled-territory") .selectAll("path") .data(counties) .enter() .append("path") .attr("d", path) });
补充说明
如果需要给地图四周预留空白边距,可以把fitSize替换为fitExtent方法,示例如下,代码里的20就是四周的内边距,可自行调整:
projection.fitExtent([[20, 20], [width - 20, height - 20]], countiesCollection)
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

