Last active
January 9, 2024 03:04
-
-
Save seyuf/ab9c980776e4c2cb350a2d1e70976517 to your computer and use it in GitHub Desktop.
Calculate GeoJson polygon center in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function area(poly){ | |
var s = 0.0; | |
var ring = poly.coordinates[0]; | |
for(i= 0; i < (ring.length-1); i++){ | |
s += (ring[i][0] * ring[i+1][1] - ring[i+1][0] * ring[i][1]); | |
} | |
return 0.5 *s; | |
} | |
function centroid(poly){ | |
var c = [0,0]; | |
var ring = poly.coordinates[0]; | |
for(i= 0; i < (ring.length-1); i++){ | |
c[0] += (ring[i][0] + ring[i+1][0]) * (ring[i][0]*ring[i+1][1] - ring[i+1][0]*ring[i][1]); | |
c[1] += (ring[i][1] + ring[i+1][1]) * (ring[i][0]*ring[i+1][1] - ring[i+1][0]*ring[i][1]); | |
} | |
var a = area(poly); | |
c[0] /= a *6; | |
c[1] /= a*6; | |
return c; | |
} | |
//centroid(geojson.geometry); |
Turf.js not able to do the job with my (low quality) geoJSON file... this saved me too!
Anyone have a similar function for a multi polygon?
Anyone have a similar function for a multi polygon?
You could calc the average of the centroids like
function centroidMulti(poly) {
if (poly?.type === 'Feature' && poly?.geometry) {
poly = poly.geometry;
}
return poly.coordinates.map(centroid)
.reduce((r, pair) => {
r[0].push(pair[0]);
r[1].push(pair[1]);
return r
}, [[], []])
.map((a) => a.reduce(( p, c) => p + c, 0) / a.length);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dude, you saved my life!