javascriptroom blog

Turf.js Centroid vs CenterOfMass: Key Differences & When to Use Each for Mean Geospatial Coordinates

In geospatial analysis, identifying the "center" of a shape is a common task—whether for labeling regions on a map, calculating distribution hubs, or analyzing spatial trends. Two popular tools for this in the JavaScript ecosystem are Turf.js’s centroid and centerOfMass functions. While both compute "mean" coordinates, they behave differently under the hood, leading to distinct results in many real-world scenarios.

This blog demystifies these two functions, breaking down their mathematical foundations, practical behavior, and ideal use cases. By the end, you’ll know exactly when to reach for centroid or centerOfMass to ensure your geospatial analyses are accurate and meaningful.

2025-12

Table of Contents#

  1. What is Turf.js?
  2. Centroid in Turf.js
    • Definition & Mathematical Foundation
    • Turf.js Implementation
    • Input/Output & Code Example
  3. CenterOfMass in Turf.js
    • Definition & Mathematical Foundation
    • Turf.js Implementation
    • Input/Output & Code Example
  4. Key Differences: Centroid vs. CenterOfMass
    • Calculation Methodology
    • Handling of Geometry Complexity
    • Output Location & Reliability
    • Comparison Table
  5. Practical Examples & Visualizations
    • Example 1: Regular Polygon (Square)
    • Example 2: Irregular Polygon (L-Shape)
    • Example 3: Multipolygon with Unequal Areas
  6. When to Use Each Function
    • Use Cases for centroid
    • Use Cases for centerOfMass
  7. Common Pitfalls & Best Practices
  8. Conclusion
  9. 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, or Feature/FeatureCollection containing these types.
  • Output: A GeoJSON Point representing the centroid coordinates.

Code Example#

First, install Turf.js via npm:

npm install @turf/turf

Then, 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, or Feature/FeatureCollection containing these types.
  • Output: A GeoJSON Point representing 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#

FactorcentroidcenterOfMass
Core PurposeGeometric center (vertex/average-based).Area-weighted center (mass-based).
Multipart GeometriesTreats all vertices equally.Weights sub-polygons by area.
Concave ShapesProne to lying outside the shape.More likely to lie inside the shape.
Use Case FocusSimple 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).

  • centroid Output: [5, 5] (exact center).
  • centerOfMass Output: [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).

  • centroid Calculation: Averages vertices, leading to a center biased toward the vertex-dense vertical section.
    • Output: [4.29, 4.29] (lies near the vertical section).
  • centerOfMass Calculation: 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).

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)).

  • centroid Output: Biased toward Sub-polygon A (more vertices per unit area), resulting in [5.14, 5.14] (near Sub-polygon A).

  • centerOfMass Output: 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 centroid for 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 centroid lies outside the shape, switch to centerOfMass.

Conclusion#

Turf.js’s centroid and centerOfMass are powerful tools for finding "mean" geospatial coordinates, but they serve distinct purposes:

  • centroid is best for simple, regular shapes where geometric symmetry is key.
  • centerOfMass shines 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#