How to add Label to each state in d3.js (albersUsa)?

前端 未结 1 481
再見小時候
再見小時候 2021-02-06 03:33

The us.json loaded, but when i try to add Label name i can\'t make it work. I don\'t see the name property in .json file so how can i add each state name? I\'m real

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 03:59

    As you stated your us.json doesn't have state names in it. What it has, though, are unique ids and luckily, Mr. Bostock has mapped those ids to names here.

    So, let's fix up this code a bit.

    First, make the json requests to pull the data:

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

    Now add our visualization:

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

    Here's a working example.

    0 讨论(0)
提交回复
热议问题