Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through SVGElement paths with d3js?

I am following this tutorial: http://bl.ocks.org/2206529

I want to determine the center area of every state, but I have two problems:

  1. How do I iterate over every state's SVG element?
  2. 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.

like image 592
egidra Avatar asked Jan 15 '23 04:01

egidra


1 Answers

This 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.com/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)
});
like image 182
Matt Esch Avatar answered Jan 22 '23 13:01

Matt Esch