Table of Contents#
- What is Turf.js?
- Centroid in Turf.js
- Definition & Mathematical Foundation
- Turf.js Implementation
- Input/Output & Code Example
- CenterOfMass in Turf.js
- Definition & Mathematical Foundation
- Turf.js Implementation
- Input/Output & Code Example
- Key Differences: Centroid vs. CenterOfMass
- Calculation Methodology
- Handling of Geometry Complexity
- Output Location & Reliability
- Comparison Table
- Practical Examples & Visualizations
- Example 1: Regular Polygon (Square)
- Example 2: Irregular Polygon (L-Shape)
- Example 3: Multipolygon with Unequal Areas
- When to Use Each Function
- Use Cases for
centroid - Use Cases for
centerOfMass
- Use Cases for
- Common Pitfalls & Best Practices
- Conclusion
- References
What is Turf.js?#
Turf.js is an open-source JavaScript library for advanced geospatial analysis. It provides over 150 modular functions for tasks like distance calculation, polygon clipping, and centroid computation, making it a go-to tool for developers building mapping applications, spatial dashboards, or geospatial backends.
All Turf.js functions work with GeoJSON, the standard format for encoding geospatial data, ensuring compatibility with tools like Leaflet, Mapbox, and PostGIS.
Centroid in Turf.js#
Definition & Mathematical Foundation#
The centroid (or geometric centroid) of a shape is its "balance point" if the shape were a thin, uniform sheet of material. Mathematically, for a polygon, it is calculated as the average of the vertices’ coordinates, weighted by the area of the sub-polygons formed by triangulating the shape.
For a simple polygon with vertices ((x_1,y_1), (x_2,y_2), ..., (x_n,y_n)), the centroid ((C_x, C_y)) is computed using the formula:
[
C_x = \frac{1}{6A} \sum_{i=1}^{n} (x_i + x_{i+1})(x_i y_{i+1} - x_{i+1} y_i)
]
[
C_y = \frac{1}{6A} \sum_{i=1}^{n} (y_i + y_{i+1})(x_i y_{i+1} - x_{i+1} y_i)
]
where (A) is the area of the polygon, and (x_{n+1}=x_1, y_{n+1}=y_1) (closing the polygon).
Turf.js Implementation#
Turf.js’s centroid function (turf.centroid) computes the geometric centroid of a polygon, multipolygon, or feature collection. It treats all vertices and sub-polygons equally, regardless of their area.
Key Notes:
- Works with polygons, multipolygons, and feature collections containing these types.
- Ignores "weight" (e.g., area, population) of sub-polygons; all vertices contribute equally.
- May return a point outside the polygon if the shape is highly concave (e.g., a crescent moon).
Input/Output#
- Input: A GeoJSON
Polygon,MultiPolygon, orFeature/FeatureCollectioncontaining these types. - Output: A GeoJSON
Pointrepresenting the centroid coordinates.
Code Example#
First, install Turf.js via npm:
npm install @turf/turfThen, calculate the centroid of a square polygon:
import { centroid, polygon } from '@turf/turf';
// Define a square polygon (GeoJSON)
const square = polygon([
[[0, 0], [0, 10], [10, 10], [10, 0], [0, 0]] // Outer ring (closed)
]);
// Calculate centroid
const squareCentroid = centroid(square);
console.log(squareCentroid.geometry.coordinates);
// Output: [5, 5] (exact center of the square)CenterOfMass in Turf.js#
Definition & Mathematical Foundation#
The center of mass (or area-weighted centroid) is the "balance point" of a shape when accounting for the area of its sub-components. For a single polygon, it is equivalent to the geometric centroid. For complex shapes (e.g., multipolygons with unequal parts), it weights each sub-polygon’s centroid by its area, ensuring larger regions influence the final center more.
Mathematically, for a multipolygon with (k) sub-polygons, the center of mass ((M_x, M_y)) is:
[ M_x = \frac{\sum_{i=1}^{k} (A_i \cdot C_{x_i})}{\sum_{i=1}^{k} A_i}, \quad M_y = \frac{\sum_{i=1}^{k} (A_i \cdot C_{y_i})}{\sum_{i=1}^{k} A_i} ]
where (A_i) is the area of sub-polygon (i), and ((C_{x_i}, C_{y_i})) is its centroid.
Turf.js Implementation#
Turf.js’s centerOfMass function (turf.centerOfMass) computes the area-weighted centroid of a polygon, multipolygon, or feature collection. Unlike centroid, it prioritizes larger sub-polygons, making it ideal for shapes with unevenly distributed area.
Key Notes:
- Treats each sub-polygon (e.g., in a multipolygon) as a weighted component based on area.
- For single polygons, it behaves like the geometric centroid (since there’s only one area to weight).
- More likely to lie inside the shape than
centroid, especially for concave or irregular polygons.
Input/Output#
- Input: A GeoJSON
Polygon,MultiPolygon, orFeature/FeatureCollectioncontaining these types. - Output: A GeoJSON
Pointrepresenting the area-weighted center of mass.
Code Example#
Using the same square polygon as before, calculate its center of mass:
import { centerOfMass, polygon } from '@turf/turf';
// Define the same square polygon
const square = polygon([
[[0, 0], [0, 10], [10, 10], [10, 0], [0, 0]]
]);
// Calculate center of mass
const squareCenterOfMass = centerOfMass(square);
console.log(squareCenterOfMass.geometry.coordinates);
// Output: [5, 5] (same as centroid for regular shapes)Key Differences: Centroid vs. CenterOfMass#
While centroid and centerOfMass may return the same result for simple shapes, their behavior diverges for complex geometries. Here’s a breakdown of their core differences:
1. Calculation Methodology#
centroid: Computes the geometric centroid by averaging vertices, weighted by the area of triangulated sub-polygons. For multipolygons, it treats all vertices equally, ignoring sub-polygon area.centerOfMass: Computes the area-weighted centroid. For multipolygons, it first calculates the centroid of each sub-polygon, then averages these centroids weighted by their areas.
2. Handling of Geometry Complexity#
centroid: Struggles with multipolygons or polygons with holes. For example, a multipolygon with a small and large sub-polygon will have a centroid biased toward the vertex-dense small polygon.centerOfMass: Excels with complex geometries. It explicitly accounts for sub-polygon area, ensuring larger regions dominate the final center.
3. Output Location & Reliability#
centroid: May lie outside the shape for concave polygons (e.g., a crescent moon or "U" shape).centerOfMass: Is more likely to lie inside the shape, as area weighting reduces sensitivity to extreme vertex positions.
4. Comparison Table#
| Factor | centroid | centerOfMass |
|---|---|---|
| Core Purpose | Geometric center (vertex/average-based). | Area-weighted center (mass-based). |
| Multipart Geometries | Treats all vertices equally. | Weights sub-polygons by area. |
| Concave Shapes | Prone to lying outside the shape. | More likely to lie inside the shape. |
| Use Case Focus | Simple labeling, geometric symmetry. | Resource allocation, area-based analysis. |
Practical Examples & Visualizations#
To see these differences in action, let’s test both functions on three common geometries.
Example 1: Regular Polygon (Square)#
Geometry: A 10x10 square with vertices at (0,0), (0,10), (10,10), (10,0).
centroidOutput:[5, 5](exact center).centerOfMassOutput:[5, 5](same as centroid, since area is uniformly distributed).
Why? For regular shapes with symmetric vertices, both methods converge to the geometric center.
Example 2: Irregular Polygon (L-Shape)#
Geometry: An L-shaped polygon with vertices: (0,0), (0,10), (5,10), (5,5), (10,5), (10,0), (0,0). This shape has a "tall thin" vertical section (area = 50) and a "short wide" horizontal section (area = 25).
centroidCalculation: Averages vertices, leading to a center biased toward the vertex-dense vertical section.- Output:
[4.29, 4.29](lies near the vertical section).
- Output:
centerOfMassCalculation: Weights the vertical section (area = 50) and horizontal section (area = 25), pulling the center toward the larger vertical section.- Output:
[3.33, 5.83](lies deeper in the "mass" of the L-shape).
- Output:
Example 3: Multipolygon with Unequal Areas#
Geometry: A multipolygon with two sub-polygons:
-
Sub-polygon A: Small square (area = 10, vertices:
(0,0),(0,3),(3,3),(3,0)). -
Sub-polygon B: Large square (area = 100, vertices:
(10,10),(10,20),(20,20),(20,10)). -
centroidOutput: Biased toward Sub-polygon A (more vertices per unit area), resulting in[5.14, 5.14](near Sub-polygon A). -
centerOfMassOutput: Biased toward Sub-polygon B (larger area), resulting in[9.09, 9.09](near Sub-polygon B).
When to Use Each Function#
Use Cases for centroid#
- Simple Labeling: When placing a label (e.g., city name) on a regular polygon (e.g., a square state boundary).
- Geometric Symmetry Analysis: Studying shape regularity (e.g., "how symmetric is this region?").
- Uniform Vertex Distribution: For shapes with evenly spaced vertices (e.g., circles approximated by polygons).
Use Cases for centerOfMass#
- Resource Allocation: Distributing goods/services based on region size (e.g., "place a warehouse in the area-weighted center of a sales territory").
- Multipolygon Analysis: Working with complex regions (e.g., countries with islands, where larger landmasses should dominate the center).
- Concave or Irregular Shapes: Ensuring the center lies inside the shape (e.g., disaster response zones).
Common Pitfalls & Best Practices#
- Assuming Interchangeability: Never use
centroidfor multipolygons or irregular shapes if area matters—you’ll get misleading results. - Ignoring Projections: Turf.js uses WGS84 (latitude/longitude) by default. For large areas, project coordinates to a planar system (e.g., UTM) first to avoid distance/area distortion.
- Validating Output: Always plot results on a map. If
centroidlies outside the shape, switch tocenterOfMass.
Conclusion#
Turf.js’s centroid and centerOfMass are powerful tools for finding "mean" geospatial coordinates, but they serve distinct purposes:
centroidis best for simple, regular shapes where geometric symmetry is key.centerOfMassshines for complex geometries, multipolygons, or area-weighted analyses.
By understanding their mathematical foundations and practical behavior, you can ensure your geospatial applications deliver accurate, actionable insights.
References#
- Turf.js Documentation: centroid, centerOfMass
- De Smith, M., Goodchild, M. F., & Longley, P. A. (2018). Geospatial Analysis: A Comprehensive Guide.
- Wikipedia: Centroid, Center of Mass