D3:为Voronoi多边形分配ID

时间:2018-01-08 16:17:17

标签: javascript d3.js

问题出在标题中。到目前为止,我可以通过将坐标数组[x,y]输入以下函数来构造Voronoi tesselation多边形:

var polygon = g.append("g")
  .attr("class", "polygons")
  .selectAll("path")
  .data(voronoi.polygons(sites))
  .enter().append("path");

如上所述,我现在想为每个多边形分配一个ID,但我很难这样做。我想要做的是提供一个可用于构建Voronoi单元格的数组,并且还包含“ID”(item.name)。这是我正在使用的代码,请让我知道我做错了什么:

for (var key in sites) {
  if (sites.hasOwnProperty(key)) {
    var item = sites[key];
    centroid = projection([item.lon, item.lat]);
    arrayz.push({
    name: item.name,
    coords: [centroid[0], centroid[1]]});
  }
}

var sites = arrayz;

var voronoi = d3.voronoi()
  .extent([
    [-1, -1],
    [width + 1, height + 1]
  ]);

var polygon = g.append("g")
  .attr("class", "polygons")
  .selectAll("path")
  .data(voronoi.polygons(sites))
  .enter().append("path");

var link = g.append("g")
  .attr("class", "links")
  .selectAll("line")
  .data(voronoi.links(sites))
  .enter().append("line");

var site = g.append("g")
  .attr("class", "sites")
  .selectAll("circle.sites")
  .data(sites)
  .enter()
  .append("circle")
  .attr("r", 2.5);

1 个答案:

答案 0 :(得分:0)

您似乎没有为voronoi函数提供一种方法来访问正在喂食的质心点。这是我建议您修改的方式:

var voronoi = d3.voronoi()
  .x( function(d) { return +d.coords[0]; })
  .y( function(d) { return +d.coords[1]; })
  .extent([
    [-1, -1],
    [width + 1, height + 1]
  ]);

我注意到您确定使用的是d3的哪个版本,但是对于v4,voronoi.polygons函数将输出一些点以创建voronoi多边形。它也〜输出您输入的原始数据。

除了所需的ID外,我还添加了d的属性,该属性是定义svg路径所必需的。

var polygon = g.append("g")
     .attr("class", "polygons")
   .selectAll("path")
   .data(voronoi.polygons(sites))
   .enter().append("path")
     .attr("d", function(d) { return d ? "M" + d.join("L") + "Z" : null; })
     .attr("id", function(d) { return d ? d.data['name'] : null; });

我使用了您的代码,并添加了工作示例所需的所有内容-进行检查:http://bl.ocks.org/zivvers/238713437237c13f21f85b7fd979824d

相关问题