如何在d3.js(albersUsa)的每个状态中添加标签?

法哈德

us.json加载,但是当我尝试添加标签名称时,我无法使其正常运行。我在.json文件中看不到name属性,所以如何添加每个州的名称?我真的是这个框架的新手。

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

我有以下担忧:

  1. 我想我在us.json文件中缺少名称属性。(如果是这个问题,是否还有其他包含状态名称的.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>

.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);
});

谢谢大家。如果您告诉我在哪里学习d3.js,我也非常感谢。

标记

正如您所说的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;
    });

现在添加我们的可视化:

// 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');

  ....

这是一个有效的例子

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章