0

Im very new to working with Leaflet, my goal is to find the centroid of a complex polygon.

I tried using the classic centroid formula and also many functions that i found on the internet, but they return the actual centroid, not a visible center (in the case of a U-shaped polygon for example).

I found a library on github by mapbox, called "polylabel" but it doesn't work properly for me, i don't know why.

i tried this:

var coords = polylabel(geojson.features[0].geometry.coordinates, 1.0);

but the end result doesn't look right: result

i also tried to write another function:

function calculateCentroid(geojsonn) {
                    var sumX = 0;
                    var sumY = 0;
                    var sumArea = 0;
                    var coordinates = geojsonn.features[0].geometry.coordinates[0];
                    for (var i = 0; i < coordinates.length - 1; i++) {
                      
                        var x1 = coordinates[i][1];
                        var y1 = coordinates[i][0];
                        var x2 = coordinates[i + 1][1];
                        var y2 = coordinates[i + 1][0];
                        var a = (x1 * y2) - (x2 * y1);
                        sumX += (x1 + x2) * a;
                        sumY += (y1 + y2) * a;
                        sumArea += a;
                    }
                    var area = sumArea / 2;
                    var x = sumX / (6 * area);
                    var y = sumY / (6 * area);
                    
                    return [y,x];
                }

but this also doesn't look right: result

in this case, at least the actual centroid is calculated properly, but i need to find the "visual centroid".

Stas
  • 11
  • 1
  • Does this answer your question? [What is the fastest way to find the "visual" center of an irregularly shaped polygon?](https://stackoverflow.com/questions/1203135/what-is-the-fastest-way-to-find-the-visual-center-of-an-irregularly-shaped-pol) – simon04 Feb 04 '23 at 22:47

0 Answers0