Skip to content

Instantly share code, notes, and snippets.

@seyuf
Last active January 9, 2024 03:04
Show Gist options
  • Save seyuf/ab9c980776e4c2cb350a2d1e70976517 to your computer and use it in GitHub Desktop.
Save seyuf/ab9c980776e4c2cb350a2d1e70976517 to your computer and use it in GitHub Desktop.
Calculate GeoJson polygon center in javascript
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);
@WangNingning1994
Copy link

Dude, you saved my life!

@gregrowles
Copy link

Turf.js not able to do the job with my (low quality) geoJSON file... this saved me too!

@spaceboydavey
Copy link

Anyone have a similar function for a multi polygon?

@sebilasse
Copy link

sebilasse commented Dec 23, 2023

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