I am using albersUSA projection to display a map. I want to add the name of the states to each state.
This is what I tried, and i can see the names of the states in
OK for anyone wondering, this is how I managed to do it:
function draw(){
d3.json("readme.json", function(json) {
g.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.on("click", click);
g.selectAll("text")
.data(json.features)
.enter()
.append("svg:text")
.text(function(d){
return d.properties.name;
})
.attr("x", function(d){
return path.centroid(d)[0];
})
.attr("y", function(d){
return path.centroid(d)[1];
})
.attr("text-anchor","middle")
.attr('font-size','6pt');
});
}
I took a similar approach to the answer you provided yourself, but I didn't like where "centroid" put all of the state names. Hawaii, Louisiana, Michigan, and Florida, for instance. So I added properties to the json data for the state info for dx and dy for those states, and added code to the drawing function.
Here's an example of some of the modified states (with the coordinates removed to keep it smaller):
{
"geometry": { "type": "Polygon", "coordinates": [] },
"type": "Feature",
"id": "12",
"properties": { "name": "Florida", "abbr": "FL", "dx": "1em" }
},
{
"geometry": { "type": "MultiPolygon", "coordinates": [] },
"type": "Feature",
"id": "15",
"properties": { "name": "Hawaii", "abbr": "HI", "dx": "1.15em", "dy": "1.25em" }
},
And here is the portion of the function that draws the labels:
g.selectAll("text")
.data(json.features)
.enter()
.append("text")
.attr("transform", function (d) { return "translate(" + path.centroid(d) + ")"; })
.attr("dx", function (d) { return d.properties.dx || "0"; })
.attr("dy", function (d) { return d.properties.dy || "0.35em"; })
.text(function (d) { return d.properties.abbr; });