centroid2D method

  1. @override
Position? centroid2D({
  1. PositionScheme scheme = Position.scheme,
})
override

Returns the centroid of this geometry calculated in a cartesian 2D plane.

The centroid is - as by definition - a geometric center of mass of a geometry.

The centroid is computed according to dimensionality of a geometry:

  • areal geometries: weighted by the area of areal geometries like polygons.
  • linear geometries: computed from midpoints of line segments that are weighted by the length of each line segment.
  • punctuat geometries: the arithmetic mean of all separate positions.

Note that a centroid do not always locate inside a geometry.

Returns null if a centroid position could not be calculated.

Use scheme to set the position scheme:

  • Position.scheme for generic position data (geographic, projected or any other), this is also the default
  • Projected.scheme for projected position data
  • Geographic.scheme for geographic position data

See also boundsAligned2D that allows calculating a center position or other aligned position related to a bounding box.

More info about Centroid can be read in Wikipedia.

Implementation

@override
Position? centroid2D({PositionScheme scheme = Position.scheme}) {
  final calculator = CompositeCentroid();
  for (final geom in geometries) {
    final centroid = geom.centroid2D(scheme: scheme);
    if (centroid != null) {
      calculator.addCentroid2D(
        centroid,
        area: geom.area2D(),
        length: geom.length2D(),
      );
    }
  }
  return calculator.centroid2D(scheme: scheme);
}