利用两个对象进行单个topojson合并。 d3.select中的多个数据(“svg”)

时间:2017-02-15 04:13:29

标签: javascript d3.js topojson

我试图将俄克拉荷马州与德克萨斯州的一个县合并。

我有两个变量,一个用于整个俄克拉荷马州的州id,另一个用于包含德克萨斯州县的县id。如何组合state.geometries.filter和county.geometries.filter?德克萨斯州实际上有许多县将被合并,但这个县是为了举例而随机选择的。

我的代码只返回最底部的数据,如下所示:

.county-borders {
  fill: none;
  stroke: #fff;
  stroke-width: 0.5px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}

.state-borders {
  fill: none;
  stroke: #fff;
  stroke-width: 0.7px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}

.state.southcentral {
  fill: steelblue;
  stroke: #fff;
}

<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>

var svg = d3.select("svg");

var path = d3.geoPath();

var southcentral = {
  "40": 1
};

var southcentral_c = {
  "48043": 1
};

d3.json("https://d3js.org/us-10m.v1.json", function(error, us) {
  if (error) throw error;

  svg.append("g")
      .attr("class", "counties")
      .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
      .enter().append("path")
      .attr("d", path);

  svg.append("path")
      .attr("class", "state-borders")
      .attr("d", path(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; })));

     //multiple datum, only shows the bottom most one. Need to combine into one merge but they use different objects in the JSON.

     svg.append("path")
      .datum(topojson.merge(us, us.objects.states.geometries.filter(function(d) { return d.id in southcentral; })))
      .datum(topojson.merge(us, us.objects.counties.geometries.filter(function(d) { return d.id in southcentral_c; })))
      .attr("class", "state southcentral")
      .attr("d", path);

});

1 个答案:

答案 0 :(得分:2)

尚未对其进行测试,但merge的api表示它接受多个多边形对象的数组。所以我认为你可以连接2个过滤的对象并传入us拓扑结构。

var arr = [];
arr[0] = us.objects.states.geometries.filter(function(d) { return d.id in southcentral; })
arr[1] = us.objects.counties.geometries.filter(function(d) { return d.id in southcentral_c; })

svg.append("path")
      .datum(topojson.merge(us, arr))
      .attr("class", "state southcentral")
      .attr("d", path);

EDIT ::

var arr = [];
Array.prototype.push.apply(arr,us.objects.states.geometries.filter(function(d) { return d.id in southcentral; }))
Array.prototype.push.apply(arr,us.objects.counties.geometries.filter(function(d) { return d.id in southcentral_c; }))