lineToPolygon function
Converts LineStrings & MultiLineString to Polygon or MultiPolygon.
Takes an optional boolean autoComplete
that auto completes LineStrings
(matches first & last coordinates).
Takes an optional orderCoords
that sorts LineStrings to place outer ring
at the first Position of the coordinates.
Takes an optional mutate
that mutates the original LineString using
autoComplete
(matches first & last coordinates.
Returns Feature<Polygon> or Feature<MultiPolygon> converted to Polygons.
example:
var line = LineString(coordinates: [
Position.of([125, -30]),
Position.of([145, -30]),
Position.of([145, -20]),
Position.of([125, -20]),
Position.of([125, -30])]);
var polygon = lineToPolygon(line);
//addToMap
var addToMap = [polygon];
Implementation
Feature lineToPolygon(
GeoJSONObject lines, {
Map<String, dynamic>? properties,
bool autoComplete = true,
bool orderCoords = true,
bool mutate = false,
}) {
Exception exc = Exception(
"""allowed types are Feature<LineString||MultiLineString>, LineString,
MultiLineString, FeatureCollection<LineString || MultiLineString>""");
if (lines is FeatureCollection) {
featureEach(
lines,
(currentFeature, index) {
if (currentFeature.geometry is! LineString &&
currentFeature.geometry is! MultiLineString) {
throw exc;
}
},
);
List<List<Position>> list = [];
geomEach(
lines,
(
GeometryType? currentGeometry,
int? featureIndex,
Map<String, dynamic>? featureProperties,
BBox? featureBBox,
dynamic featureId,
) {
if (currentGeometry is LineString) {
list.add(currentGeometry.coordinates.map((e) => e.clone()).toList());
} else if (currentGeometry is MultiLineString) {
list = [
...list,
...currentGeometry.coordinates
.map((e) => e.map((p) => p.clone()).toList())
.toList()
];
} else {
throw Exception("$currentGeometry type is not supperted");
}
},
);
lines = FeatureCollection<MultiLineString>(features: [])
..features.add(Feature(geometry: MultiLineString(coordinates: list)));
} else if (lines is Feature) {
if (lines.geometry is LineString) {
lines = Feature<LineString>(
geometry: lines.geometry as LineString,
properties: lines.properties,
id: lines.id,
);
} else if (lines.geometry is MultiLineString) {
lines = Feature<MultiLineString>(
geometry: lines.geometry as MultiLineString,
properties: lines.properties,
id: lines.id,
);
} else {
throw exc;
}
} else if (lines is LineString) {
lines = Feature<LineString>(geometry: lines);
} else if (lines is MultiLineString) {
lines = Feature<MultiLineString>(geometry: lines);
} else {
throw exc;
}
if (!mutate) {
lines = lines.clone();
}
if (lines is FeatureCollection) {
List<List<List<Position>>> coords = [];
featureEach(
lines,
((line, featureIndex) => coords.add(getCoords(lineStringToPolygon(
line, autoComplete, orderCoords, properties: {}))
as List<List<Position>>)),
);
return Feature(
geometry: MultiPolygon(coordinates: coords), properties: properties);
} else {
return lineStringToPolygon(lines, autoComplete, orderCoords,
properties: properties);
}
}