The centroid
function of Turf's measurement
module computes the geometric center (centroid) of a GeoJSON feature.
geojson
(GeoJSON Feature): the input feature for which the centroid is to be calculated.coords
(Array): an array containing the [longitude, latitude] coordinates of the centroid.var centroid = require('@turf/measurement').centroid;
var polygon = {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [[
[-77.031669, 38.878605],
[-77.029609, 38.881946],
[-77.020339, 38.884084],
[-77.025661, 38.878605],
[-77.031669, 38.878605]
]]
}
};
var center = centroid(polygon);
console.log(center); // [-77.025664, 38.87988]
The centroid computation algorithm follows the approach described in the Geospatial Data Abstraction Library (GDAL) documentation. Essentially, the polygon is divided into a grid of fine-grained points, and the centroid is calculated as the average of all points weighted by the area of each cell that the point falls within.