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

us.json loaded, but when I try to add a shortcut name, I cannot get it to work. I do not see the name property in the .json file, so how can I add each state name? I am really new to this structure.

I try a different tutorial on Google and Stackoverflow, but none of them work for me. Here is a link to a couple of tutorials that I tried that I find worthy.

I have the following issues:

  • I think I am missing the name in the us.json file. (if this is a problem, is there any other .json file that includes the state name? And how to use the state name with this file?)
  • Is the name of the US state included in http://d3js.org/topojson.v1.min.js ?

.html File (downloaded from the platform)

 <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script src="http://d3js.org/topojson.v1.min.js"></script> 

.js file:

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

Thanks to everyone who has moved forward. I also appreciate if you tell me where you found d3.js.

+6
source share
1 answer

As you stated, your us.json does not have state names in it. However, these are unique identifiers and, fortunately, Mr. Bostok has named these identifiers here .

So, correct this code a bit.

First make json requests to output 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'); .... 

It works here.

+7
source

Source: https://habr.com/ru/post/981933/


All Articles