I am following this tutorial:
I want to determine the center area of every state, but I have two problems:
- How do I iterate over every state's SVG element?
- How do I determine the middle coordinate of that particular SVG element?
My g element contains many paths, where each path represents a state. It seems that when I use the following code:
states.selectAll("path")
I want to find the center of the path using:
states.selectAll("path").attr("d", function(d) {
// Get centroid(d)
});
But the function parameter doesn't do anything.
I am following this tutorial: http://bl.ocks/2206529
I want to determine the center area of every state, but I have two problems:
- How do I iterate over every state's SVG element?
- How do I determine the middle coordinate of that particular SVG element?
My g element contains many paths, where each path represents a state. It seems that when I use the following code:
states.selectAll("path")
I want to find the center of the path using:
states.selectAll("path").attr("d", function(d) {
// Get centroid(d)
});
But the function parameter doesn't do anything.
Share Improve this question edited Mar 3, 2013 at 14:26 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Oct 31, 2012 at 18:45 egidraegidra 9,08721 gold badges67 silver badges92 bronze badges1 Answer
Reset to default 9This is the incorrect use of attr. The attr function with a second argument is used for setting an attribute, not simply for iterating over a collection. You should use the each function
https://github./mbostock/d3/wiki/Selections#wiki-each
selection.each(function)
Invokes the specified function for each element in the current selection, passing in the current datum d and index i, with the this context of the current DOM element. This operator is used internally by nearly every other operator, and can be used to invoke arbitrary code for each selected element. The each operator can be used to process selections recursively, by using d3.select(this) within the callback function.
states.selectAll("path").each(function(d, i) {
// Get centroid(this.d)
});