【问题标题】:d3 choropleth map is extremely smalld3 等值线图非常小
【发布时间】:2020-11-09 00:34:54
【问题描述】:

我正在尝试从位于 here 的 topojson 文件中绘制 svg 地图。当我运行下面的代码时,我看到一个小的红色集合g 元素就是那个地图,但我不知道如何使它更大。我试过 projection.scale(100) 但这不起作用。

Here 是个小提琴。

<svg width=500 height=500></svg>
async function run() {
  const res = await fetch(
    "https://rawcdn.githack.com/jasonicarter/toronto-geojson/0fb40bd54333bc3d397a26cf4f68abb1b6d94188/toronto_topo.json"
  );
  const jsondata = await res.json();

  const width = 500;
  const height = 500;


  const neighbourhoods = topojson.feature(jsondata, jsondata.objects.toronto);
    
  const projection = d3.geoAlbers().translate([width / 2, height / 2])
    
  const svg = d3.select("svg")

  svg
    .append("g")
    .selectAll("path")
    .data(neighbourhoods.features)
    .enter()
    .append("path")
    .attr("d", d3.geoPath().projection(projection))
    .attr("fill", "red")
    .attr("stroke", "white");
    
  console.log("done")
}

run();

【问题讨论】:

    标签: d3.js topojson


    【解决方案1】:

    确实,您必须使用scaletranslate 属性来缩放/居中地图。 但d3.geoProjection 还提供了一些便利功能,例如fitExtentfitSize,以便将投影拟合到一个特定的GeoJSON 特征对象上。

    由于您的数据集包含许多特征,我建议使用topojson.mesh 来获取代表您的整个数据集(作为网格)的唯一对象,以使用其范围和投影的fitSize 方法来缩放您的地图:

    const neighbourhoods = topojson.feature(jsondata, jsondata.objects.toronto);
    const mesh = topojson.mesh(jsondata, jsondata.objects.toronto);
    
    const projection = d3.geoAlbers()
      .fitSize([width, height], mesh);
        
    const svg = d3.select("svg")
    
    svg
      .append('g')
      .selectAll("path")
      .data(neighbourhoods.features)
      .enter()
      .append("path")
      .attr("d", d3.geoPath().projection(projection))
      .attr("fill", "red")
      .attr("stroke", "white");
    

    哪个(在 svg 元素上添加边框后)给出以下内容:

    如果您想使用一些填充(比如说 20 像素)来适应范围,您可以使用以下内容:

    const projection = d3.geoAlbers()
      .fitExtent([[20, 20], [width - 20, height - 20]], mesh);
    

    【讨论】: