Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a path centroid d3

I cant use the .centroid() method because its returns [NaN,Nan]. I dont know what is the right data format.

    var pathh = d3.geo.path();
    d3.selectAll("path.line")
        .each(function (d, i) {
        var centroid = pathh.centroid(d);
        console.log('Centroid at: ', d,+ centroid[0] + ', ' + centroid[1]);
     });

My data format is: One object is one point(vertex) of the polygon

0: Object
   area_id: "IVP001"
   vertex_id: "37451"
   x: "100"
   y: "100"

1: Object
   area_id: "IVP001"
   vertex_id: "37452"
   x: "150"
   y: "120"

2: Object
   area_id: "IVP001"
   vertex_id: "37453"
   x: "50"
   y: "120"

There is the parent array what contains the polygon's vertex point objects. I would like to get the each centroid of the polygons, and append a text there.

My half-right solution, but its not so accurate, and its ugly...

    var areas = cg.selectAll("g.area-group")
        .data(data);    

    var ag = areas
            .enter()
            .append("g")
            .attr("class","area-group")
            .attr("data-area-id",function(d) {return d[0].area_id; });

    var area_path = ag.insert("path")
            .attr("class", "line")
            .call(dragArea);

        d3.selectAll("text").remove();




var area_id_text = areas.append("text")
            .attr("dx", function(d) {
                    var text_x = 0;
                    $.each(d, function( index, value ) { text_x += +value.x;});
                    return text_x/d.length;
              })
            .attr("dy", function(d) {
                    var text_y = 0;
                    $.each(d, function( index, value ) { text_y += +value.y; });
                    return text_y/d.length;
              })
            .text(function(d) {return d[0].area_id; })
        ;
like image 352
Peter Avatar asked Mar 15 '23 06:03

Peter


1 Answers

You can do something like this:

//calculate the centroid using the bbox
function getMyCentroid(element) {
    var bbox = element.getBBox();
    return [bbox.x + bbox.width/2, bbox.y + bbox.height/2];
}

d3.selectAll("path.line")[0].forEach(function (d, i) {
   console.log(getMyCentroid(d));
});
like image 112
Cyril Cherian Avatar answered Mar 23 '23 04:03

Cyril Cherian