polygonSmooth function

FeatureCollection<GeometryObject> polygonSmooth(
  1. GeoJSONObject inputPolys, {
  2. int iterations = 1,
})

Smooths a Polygon, MultiPolygon, also inside Features, FeatureCollections, or GeometryCollection. Based on Chaikin's algorithm. Warning: may create degenerate polygons. The optional parameter iterations is the number of times to smooth the polygon. A higher value means a smoother polygon. The functions returns a FeatureCollection of Polygons and MultiPolygons.

var polygon = Polygon(coordinates: [
    [
        Position(11, 0),
        Position(22, 4),
        Position(31, 0),
        Position(31, 11),
        Position(21, 15),
        Position(11, 11),
        Position(11, 0),
    ]
]);

var smoothed = polygonSmooth(polygon, iterations: 3);

Implementation

FeatureCollection polygonSmooth(GeoJSONObject inputPolys,
    {int iterations = 1}) {
  var outPolys = <Feature>[];

  geomEach(inputPolys, (
    GeometryType? geom,
    int? geomIndex,
    Map<String, dynamic>? featureProperties,
    BBox? featureBBox,
    dynamic featureId,
  ) {
    dynamic outCoords;
    dynamic poly;
    dynamic tempOutput;

    switch (geom?.type) {
      case GeoJSONObjectType.polygon:
        outCoords = <List<Position>>[[]];
        for (var i = 0; i < iterations; i++) {
          tempOutput = <List<Position>>[[]];
          poly = geom;
          if (i > 0) poly = Polygon(coordinates: outCoords);
          _processPolygon(poly, tempOutput);
          outCoords = List<List<Position>>.of(tempOutput);
        }
        outPolys.add(Feature(
            geometry: Polygon(coordinates: outCoords),
            properties: featureProperties));
        break;
      case GeoJSONObjectType.multiPolygon:
        outCoords = [
          [<Position>[]]
        ];
        for (var y = 0; y < iterations; y++) {
          tempOutput = <List<List<Position>>>[
            [[]]
          ];
          poly = geom;
          if (y > 0) poly = MultiPolygon(coordinates: outCoords);
          _processMultiPolygon(poly, tempOutput);
          outCoords = List<List<List<Position>>>.of(tempOutput);
        }
        outPolys.add(Feature(
            geometry: MultiPolygon(coordinates: outCoords),
            properties: featureProperties));
        break;
      default:
        throw Exception("geometry is invalid, must be Polygon or MultiPolygon");
    }
  });
  return FeatureCollection(features: outPolys);
}