0

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

是一个小提琴。

<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();
4

1 回答 1

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 元素上添加边框后)给出以下内容:

结果图像

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

const projection = d3.geoAlbers()
  .fitExtent([[20, 20], [width - 20, height - 20]], mesh);
于 2020-07-19T20:26:02.870 回答