Quick Tip: Getting the centroid of an individual SVG path selection in D3

Published Feb 13, 2013 (11 years ago)
Danger icon
The last modifications of this post were around 11 years ago, some information may be outdated!

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!