Calculate SVG Path Centroid with D3.js

The D3 functions all seem to assume you’re starting with GeoJSON. However, I don’t actually think you need the centroid for this – what you really need is the bounding box, and fortunately this is available directly from the SVG DOM interface:

function getBoundingBoxCenter (selection) {
  // get the DOM element from a D3 selection
  // you could also use "this" inside .each()
  var element = selection.node();
  // use the native SVG interface to get the bounding box
  var bbox = element.getBBox();
  // return the center of the bounding box
  return [bbox.x + bbox.width/2, bbox.y + bbox.height/2];
}

This is actually slightly better than the true centroid for the purpose of zooming, as it avoids some projection issues you might otherwise run into.

Leave a Comment