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 ext = exterior;
  if (ext != null) {
    final cext = ext.centroid2D(scheme: scheme);
    if (cext != null) {
      final aext = ext.signedArea2D().abs();
      if (aext > 0.0) {
        final calculator = CompositeCentroid()
          // "positive" weighted centroid for an exterior ring
          ..addCentroid2D(cext, area: aext);

        // "negative" weighted centroids for interior rings
        // (only holes with area are used)
        for (final hole in interior) {
          final chole = hole.centroid2D(scheme: scheme);
          if (chole != null) {
            final ahole = hole.signedArea2D().abs();
            if (ahole > 0.0) {
              calculator.addCentroid2D(chole, area: -ahole);
            }
          }
        }

        // return composite if non-null, otherwise just centroid for exterior
        final composite = calculator.centroid2D(scheme: scheme);
        return composite ?? cext;
      } else {
        // no area, return linear or punctual centroid for exterior
        return cext;
      }
    }
  }

  return null;
}