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 ="#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 ="#state_01000");
var centroid = path.centroid(state.datum());
alert('Centroid at: ' + centroid[0] + ', ' + centroid[1]);

Happy coding!


What are your 10 bits on the matter? I want to know!

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s