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:
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:
in this case, at least the actual centroid is calculated properly, but i need to find the "visual centroid".