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);
@chlenc
Copy link

chlenc commented Apr 12, 2022

Hey cool guy. Tell me please, do you know how to calculate the zoom by coordinates?

@seyuf
Copy link
Author

seyuf commented Apr 12, 2022

Hi @chlenc, I don't know if people coding or understanding the above can be considered as cool :). If so, you're definitely part of the club.

As for the zoom, i've been postponing that work for months now 🙄 . But it all depends on the tech you intend to use for the display.

If we make abstraction of the tech, zooming should be pretty straight forward. Imma link this article which explains it better what i intend to do. You can even pick into the author's code here ;) Also, feel free to share if you have another idea or work, as a more simplistic approach can be taken if the data subset is relatively small.

@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