如何在d3.js(albersUsa)中为每个州添加Label?

Far*_*had 8 javascript json dom d3.js

在us.json加载,但是当我尝试添加标签的名字我不能使它发挥作用.我没有在.json文件中看到name属性,所以如何添加每个州名?我是这个框架的新手.

我在Google和Stackoverflow上尝试了不同的教程,但它们都不适合我.这是我试过的情侣教程的链接,我认为值得.

我担心的问题:

  1. 我想我在us.json文件中缺少name属性.(如果这是问题,是否有任何其他.json文件包含州名?如何使用该文件的州名?)
  2. 美国州名是否包括在内http://d3js.org/topojson.v1.min.js?

.html 文件(框架已加载)

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

.js 文件:

var width = 1500,
    height = 1100,
    centered;


var usData = ["json/us.json"];
var usDataText = ["json/us-states.json"];

var projection = d3.geo.albersUsa()
    .scale(2000)
    .translate([760, height / 2]);

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

var svg = d3.select("body").append("svg")
    .style("width", "100%")
    .style("height", "100%");


svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", clicked);

var g = svg.append("g");

d3.json(usData, function(unitedState) {
  g.append("g")
    .attr("class", "states-bundle")
    .selectAll("path")
    .data(topojson.feature(unitedState, unitedState.objects.states).features)
    .enter()
    .append("path")
    .attr("d", path)
    .attr("class", "states")
    .on("click", clicked);
});
Run Code Online (Sandbox Code Playgroud)

先谢谢大家.如果你告诉我你在哪里学习d3.js我也很感激.

Mar*_*ark 8

如你所说,你的us.json州名没有.然而,它拥有独特的ID,幸运的是,Bostock先生已将这些ID映射到这里.

所以,让我们稍微修改一下这段代码.

首先,json请求提取数据:

// path data
d3.json("us.json", function(unitedState) {
  var data = topojson.feature(unitedState, unitedState.objects.states).features;
  // our names
  d3.tsv("us-state-names.tsv", function(tsv){
    // extract just the names and Ids
    var names = {};
    tsv.forEach(function(d,i){
      names[d.id] = d.name;
    });
Run Code Online (Sandbox Code Playgroud)

现在添加我们的可视化

// build paths
g.append("g")
  .attr("class", "states-bundle")
  .selectAll("path")
  .data(data)
  .enter()
  .append("path")
  .attr("d", path)
  .attr("stroke", "white")
  .attr("class", "states");

 // add state names
 g.append("g")
  .attr("class", "states-names")
  .selectAll("text")
  .data(data)
  .enter()
  .append("svg:text")
  .text(function(d){
    return names[d.id];
  })
  .attr("x", function(d){
      return path.centroid(d)[0];
  })
  .attr("y", function(d){
      return  path.centroid(d)[1];
  })
  .attr("text-anchor","middle")
  .attr('fill', 'white');

  ....
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子.