D3 how to find Centroid of merged ploygons

528 views Asked by At

I have plot states map using D3 and I am able to plot Centroid of each state using path.Centroid() function but once I merge the states(polygons) to make it large region path.Centroid() does not work.

How to find Centroid of merged Ploygons ?

Reference: here is the link to merged states example

Note: I have list of lat/long for all states centroid.

1

There are 1 answers

1
Aurelius On BEST ANSWER

To find the centroid on the 'Merging States' example:

 var mergeTopo = topojson.merge(us, us.objects.states.geometries.filter(function(d) { return selected.has(d.id); }));
 var mergeCentroid = [path.centroid(mergeTopo)];

 svg.selectAll(".mergedcentroid").data(mergeCentroid)
      .enter().append("circle") 
      .attr("class", "mergedcentroid")
      .attr("fill", "black")
      .attr("stroke", "purple")
      .attr("stroke-width", 5)
      .attr("r", 15)
      .attr("cx", function (d){ return d[0]; })
      .attr("cy", function (d){ return d[1]; });

Wrapping the centroid coordinates in an array before creating the circle.