-
-
Save seyuf/ab9c980776e4c2cb350a2d1e70976517 to your computer and use it in GitHub Desktop.
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); |
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.
Dude, you saved my life!
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);
}
Hey cool guy. Tell me please, do you know how to calculate the zoom by coordinates?