Jesper Jørgensen
Jesper Jørgensen

Reputation: 81

Use D3.js to find Centroid of SVG Path

This is a re-make of a question, because people didnt read the last one properly. I need the actual weighted centroid of a path. Not just a center, that is very important.

How do you use D3.js to find centroid of a region.

SVG Region code looks like this:

        <path id="JP" title="Japan" class="land" d="M852.76,362.01l0.36,1.15l-1.58,2.03l-1.15,-1.07l-1.44,0.78l-0.74,1.95l-1.83,-0.95l0.02,-1.58l1.55,-2l1.6,0.39l1.15,-1.42L852.76,362.01zM870.53,351.73l-1.06,2.78l0.49,1.73l-1.46,2.42l-3.58,1.6l-4.93,0.21l-3.99,3.84l-1.88,-1.29l-0.12,-2.52l-4.88,0.75l-3.32,1.59l-3.28,0.06l2.84,2.46l-1.87,5.61l-1.81,1.37l-1.36,-1.27l0.69,-2.96l-1.77,-0.96l-1.14,-2.28l2.65,-1.03l1.47,-2.11l2.82,-1.75l2.06,-2.33l5.58,-1.02l3,0.7l2.93,-6.17l1.87,1.67l4.11,-3.51l1.6,-1.38l1.76,-4.38l-0.48,-4.1l1.19,-2.33l2.98,-0.68l1.53,5.11l-0.08,2.94l-2.59,3.6L870.53,351.73zM878.76,325.8l1.97,0.83l1.98,-1.65l0.62,4.35l-4.16,1.05l-2.45,3.76l-4.41,-2.58l-1.52,4.12l-3.12,0.06l-0.39,-3.74l1.39,-2.94l3,-0.21l0.82,-5.38l0.83,-3.09l3.3,4.12L878.76,325.8z"/>

enter image description here

So how do i place a DOT/Icon etc. on the centroid on this, so that its on the actual svg.

It needs to be CENTROID, so a fiddle example with a working example would make me very happy.

Thanks in advance

Upvotes: 1

Views: 1503

Answers (1)

Ga&#235;l Barbin
Ga&#235;l Barbin

Reputation: 3919

You can get the centroid with a basic average calculation:

var centroid= {x:0,y:0};
var pointCount=0;
for( var i=0; i< parsedPath.length; i++ ){
    var point= parsedPath[i];

    if( point.relative == true){
        if( i > 0 ){
            point.x += +parsedPath[i-1].x;
            point.y += +parsedPath[i-1].y;
        }
    }
    if( point.x && point.y ){

        centroid.x += point.x;
        centroid.y += point.y;

        placePoint(point , "blue" , 0.2 );

        pointCount++
    }else{
        // close pathes -> ignored
    }

}
centroid.x /= pointCount;
centroid.y /= pointCount;

but, depending on your need, this may be not what you are loonking for. See my answer in a previous related question.

The demo

Upvotes: 3

Related Questions