geokit/centroid

Centroid (geometric centre) of a Geometry.

For a Point, the centroid is the point itself. For a LineString it is the arithmetic mean of its vertices. For a Polygon it is the centroid of the exterior ring weighted by the signed area of each triangle, which is the correct mean for a planar polygon (Turfjs / Shapely use the same formula).

All computations treat the Earth as a flat plane in lat/lng — no projection is applied. For polygons spanning more than a few degrees, project to Web Mercator first (see geokit/mercator) for an area-accurate centroid.

Types

Errors returned by compute.

pub type CentroidError {
  EmptyGeometry
}

Constructors

  • EmptyGeometry

    The geometry contained no points.

Values

pub fn compute(
  geometry geometry: geometry.Geometry,
) -> Result(latlng.LatLng, CentroidError)

Compute the centroid of geometry.

pub fn of_points(
  points points: List(latlng.LatLng),
) -> Result(latlng.LatLng, CentroidError)

Convenience wrapper for callers who already hold a flat list of points and don’t want to mint a LineString just to feed it in. Mirrors the simplify.line_string shape: LineString carries edge / ordering semantics that the unweighted-mean-of-vertices computation used by centroid.compute for LineString does not actually rely on, so wrapping a bag of points in LineString reads as noise at the call site.

import geokit/centroid
import geokit/latlng

let assert Ok(a) = latlng.new(lat: 0.0, lng: 0.0)
let assert Ok(b) = latlng.new(lat: 10.0, lng: 10.0)
let assert Ok(c) = centroid.of_points([a, b])
// c is the mean of a and b.

Equivalent to centroid.compute(MultiPoint(points)) — wraps the list in the variant that matches a bag-of-points semantically (no edge or ordering implied). Empty input returns EmptyGeometry.

When the input is a closed ring (first vertex equal to last — the shape GeoJSON Polygon linear rings carry per RFC 7946 §3.1.6), the trailing duplicate is dropped before the mean so the closing vertex is not double-counted. Two-element rings where both vertices are equal are left alone (their mean is already that point). Interior adjacent duplicates are preserved — they may be deliberate.

For the geometric (signed-area) centroid of a Polygon, use centroid.compute(Polygon(...)).

Search Document