动态投影单个县

Dynamically project a Single County

这是一个简单但鼓舞人心的单一状态拓扑json:

https://bl.ocks.org/mbostock/7061976

它是由 json 中仅包含该状态的数据绘制的,如下所示:

d3.json("va-counties.json", function(error, topo) {
  if (error) throw error;

我想做的是动态投影一个县。假设有一个键盘事件或其他运行函数的东西:读入解析的数据,找到县 ID,然后 return 仅该县的拓扑 json 特征。上面的块和我的情况之间的区别是我的 json 文件将包含美国的所有县,但我一次只需要 1 个县。有没有办法在 D3 中实现这一点?

作为一个简单的石蕊试纸,对于 county id=1000,我试过:

  var current_county = topojson.feature(topo, topo.objects.counties).filter(function(d) { return d.id=1000;})),
      bounds = path.bounds(county);

然而,无论我多么努力地解决它,我仍然不断遇到错误。或者它会停止抛出错误,但仍然没有 'work'。也许 .filter() 不是完成这项工作的最佳工具?还有哪些意见?

感谢阅读

首先你的 filter 语法是错误的,我认为你的意思是比较而不是赋值:

d.id === 1000

其次,topojson.feature returns GeoJSON 在一个对象中,它不会像那样进行过滤。你最好的选择是在途中过滤它:

// filter the geometries of the topojson the structure you want
var geoCounty = topo.objects.counties.geometries.filter(function(d){
  return d.id === "51750";
});

// assign it back to the topojson object
topo.objects.counties.geometries = geoCounty;

// and off you go...
var county = topojson.feature(topo, topo.objects.counties),
    bounds = path.bounds(county);

完整 运行 代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.county {
  fill: #ccc;
}

</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/d3.geo.projection.v0.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>

var width = 500,
    height = 300;

var projection = d3.geo.conicConformal()
    .parallels([38 + 02 / 60, 39 + 12 / 60])
    .rotate([78 + 30 / 60, 0])
    .scale(200000)
    .translate([0, 0]);

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("https://jsonblob.com/api/ce96ca06-e1ce-11e6-90ab-03e5986c4e20", function(error, topo) {
  if (error) throw error;

  var geoCounty = topo.objects.counties.geometries.filter(function(d){
    return d.id === "51750";
  });

  topo.objects.counties.geometries = geoCounty;

  var county = topojson.feature(topo, topo.objects.counties),
      bounds = path.bounds(county);

  projection
      .translate([width / 2 - (bounds[0][0] + bounds[1][0]) / 2, height / 2 - (bounds[0][1] + bounds[1][1]) / 2]);

  svg.append("path")
      .datum(county)
      .attr("class", "county")
      .attr("d", path);

});

</script>