269 words
1 min
Quick Tip Getting The Centroid Of An Individual Svg Path Selection In D3

Quick Tip

If you’re using D3 to render SVG paths, you’ll find that you can iterate through a collection of paths and get the centroids of each one through a simple loop:

d3.selectAll("#states path") .each(function (d, i)
{
var centroid = path.centroid(d);
alert('Centroid at: ' + centroid\[0] + ', ' + centroid\[1]);
});

However, if you try a similar approach on a single selection:

var state = d3.select("#state_01000");
var centroid = path.centroid(state);
alert('Centroid at: ' + centroid\[0] + ', ' + centroid\[1]);

Your centroid value comes back as undefined.

The trick is that the .each method that iterates through the collection is actually using an underlying property of the selection for its processing.

The solution is to use the .datum() method on the selection.

var state = d3.select("#state_01000");
var centroid = path.centroid(state.datum()); alert('Centroid at: ' + centroid\[0] + ', ' + centroid\[1]);

Happy coding!

Quick Tip

If you’re using D3 to render SVG paths, you’ll find that you can iterate through a collection of paths and get the centroids of each one through a simple loop:

d3.selectAll("#states path") .each(function (d, i)
{
var centroid = path.centroid(d);
alert('Centroid at: ' + centroid\[0] + ', ' + centroid\[1]);
});

However, if you try a similar approach on a single selection:

var state = d3.select("#state_01000");
var centroid = path.centroid(state);
alert('Centroid at: ' + centroid\[0] + ', ' + centroid\[1]);

Your centroid value comes back as undefined.

The trick is that the .each method that iterates through the collection is actually using an underlying property of the selection for its processing.

The solution is to use the .datum() method on the selection.

var state = d3.select("#state_01000");
var centroid = path.centroid(state.datum()); alert('Centroid at: ' + centroid\[0] + ', ' + centroid\[1]);

Happy coding!

Quick Tip Getting The Centroid Of An Individual Svg Path Selection In D3
https://dillieo.me/posts/development/2013-02-13-quick-tip-getting-the-centroid-of-an-individual-svg-path-selection-in-d3/
Author
Sean Patterson
Published on
2013-02-13
License
CC BY-NC-SA 4.0