-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathpolygon_to_line.dart
69 lines (60 loc) · 1.99 KB
/
polygon_to_line.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import 'package:turf/src/invariant.dart';
import '../helpers.dart';
/// Converts a [Polygon] to [LineString] or [MultiLineString] or a [MultiPolygon]
/// to a [FeatureCollection] of [LineString] or [MultiLineString].
/// Returns [FeatureCollection] or [Feature<LineString>] or [Feature<MultiLinestring>]
/// example:
/// ```dart
/// var poly = Polygon(coordinates:
/// [
/// [
/// Position.of([125, -30]),
/// Position.of([145, -30]),
/// Position.of([145, -20]),
/// Position.of([125, -20]),
/// Position.of([125, -30])
/// ]
/// ]);
/// var line = polygonToLine(poly);
/// //addToMap
/// var addToMap = [line];
/// ```
GeoJSONObject polygonToLine(GeoJSONObject poly,
{Map<String, dynamic>? properties}) {
var geom = getGeom(poly);
properties =
properties ?? ((poly is Feature) ? poly.properties : <String, dynamic>{});
if (geom is Polygon) {
return _polygonToLine(geom, properties: properties);
} else if (geom is MultiPolygon) {
return _multiPolygonToLine(geom, properties: properties);
} else {
throw Exception("invalid poly");
}
}
Feature _polygonToLine(Polygon geom, {Map<String, dynamic>? properties}) {
var coords = geom.coordinates;
properties = properties ?? <String, dynamic>{};
return _coordsToLine(coords, properties);
}
FeatureCollection _multiPolygonToLine(MultiPolygon geom,
{Map<String, dynamic>? properties}) {
var coords = geom.coordinates;
properties = properties ?? <String, dynamic>{};
var lines = <Feature>[];
for (var coord in coords) {
lines.add(_coordsToLine(coord, properties));
}
return FeatureCollection(features: lines);
}
Feature _coordsToLine(
List<List<Position>> coords, Map<String, dynamic>? properties) {
if (coords.isEmpty) {
throw RangeError("coordinates is empty");
} else if (coords.length > 1) {
return Feature(
geometry: MultiLineString(coordinates: coords), properties: properties);
}
return Feature(
geometry: LineString(coordinates: coords[0]), properties: properties);
}