-
Notifications
You must be signed in to change notification settings - Fork 6
/
FeatureCollection.swift
248 lines (192 loc) · 7.39 KB
/
FeatureCollection.swift
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import Foundation
/// A GeoJSON `FeatureCollection`.
public struct FeatureCollection:
GeoJson,
EmptyCreatable
{
public var type: GeoJsonType {
return .featureCollection
}
public var projection: Projection {
features.first?.projection ?? .noSRID
}
/// The FeatureCollection's Feature objects.
public private(set) var features: [Feature]
public var allCoordinates: [Coordinate3D] {
features.flatMap(\.allCoordinates)
}
public var boundingBox: BoundingBox?
public var foreignMembers: [String: Sendable] = [:]
public init() {
self.features = []
}
/// Initialize a FeatureCollection with one Feature.
public init(_ feature: Feature, calculateBoundingBox: Bool = false) {
self.init([feature], calculateBoundingBox: calculateBoundingBox)
}
/// Initialize a FeatureCollection with some Features.
public init(_ features: [Feature], calculateBoundingBox: Bool = false) {
self.features = features
if calculateBoundingBox {
self.boundingBox = self.calculateBoundingBox()
}
}
/// Initialize a FeatureCollection with some geometry objects.
public init(_ geometries: [GeoJsonGeometry], calculateBoundingBox: Bool = false) {
self.features = geometries.compactMap { Feature($0) }
if calculateBoundingBox {
self.boundingBox = self.calculateBoundingBox()
}
}
/// Normalize any GeoJSON object into a FeatureCollection.
public init?(_ geoJson: GeoJson?, calculateBoundingBox: Bool = false) {
guard let geoJson = geoJson else { return nil }
switch geoJson {
case let featureCollection as FeatureCollection:
self.features = featureCollection.features
self.boundingBox = featureCollection.boundingBox
self.foreignMembers = featureCollection.foreignMembers
case let feature as Feature:
self.features = [feature]
self.boundingBox = feature.boundingBox
case let geometry as GeoJsonGeometry:
self.features = [Feature(geometry)]
self.boundingBox = geometry.boundingBox
default:
return nil
}
if calculateBoundingBox, self.boundingBox == nil {
self.boundingBox = self.calculateBoundingBox()
}
}
public init?(json: Any?) {
self.init(json: json, calculateBoundingBox: false)
}
/// This initializer is slightly different to the other initializers
/// because it will accept any valid GeoJSON object and normalize
/// it into a FeatureCollection.
///
/// - important: The source is expected to be in EPSG:4326.
public init?(json: Any?, calculateBoundingBox: Bool = false) {
guard let geoJson: GeoJson = FeatureCollection.tryCreate(json: json) else { return nil }
self.init(geoJson, calculateBoundingBox: calculateBoundingBox)
}
// To prevent an infinite recursion.
init?(geoJson: [String: Sendable], calculateBoundingBox: Bool = false) {
guard FeatureCollection.isValid(geoJson: geoJson),
let features: [Feature] = FeatureCollection.tryCreate(json: geoJson["features"])
else { return nil }
self.features = features
self.boundingBox = FeatureCollection.tryCreate(json: geoJson["bbox"])
if calculateBoundingBox, self.boundingBox == nil {
self.boundingBox = self.calculateBoundingBox()
}
if geoJson.count > 2 {
var foreignMembers = geoJson
foreignMembers.removeValue(forKey: "type")
foreignMembers.removeValue(forKey: "features")
foreignMembers.removeValue(forKey: "bbox")
self.foreignMembers = foreignMembers
}
}
public var asJson: [String: Any] {
var result: [String: Any] = [
"type": GeoJsonType.featureCollection.rawValue,
"features": features.map { $0.asJson }
]
if let boundingBox = boundingBox {
result["bbox"] = boundingBox.asJson
}
result.merge(foreignMembers) { (current, new) in
return current
}
return result
}
}
extension FeatureCollection {
public func calculateBoundingBox() -> BoundingBox? {
let featureBoundingBoxes: [BoundingBox] = features.compactMap({ $0.boundingBox ?? $0.calculateBoundingBox() })
guard !featureBoundingBoxes.isEmpty else { return nil}
return featureBoundingBoxes.reduce(featureBoundingBoxes[0]) { (result, boundingBox) -> BoundingBox in
return result + boundingBox
}
}
public func intersects(_ otherBoundingBox: BoundingBox) -> Bool {
if let boundingBox = boundingBox ?? calculateBoundingBox(),
!boundingBox.intersects(otherBoundingBox)
{
return false
}
return features.contains { $0.geometry.intersects(otherBoundingBox) }
}
}
extension FeatureCollection: Equatable {
public static func ==(
lhs: FeatureCollection,
rhs: FeatureCollection)
-> Bool
{
return lhs.projection == rhs.projection
&& lhs.features == rhs.features
}
}
// MARK: - Projection
extension FeatureCollection {
public func projected(to newProjection: Projection) -> FeatureCollection {
guard newProjection != projection else { return self }
var featureCollection = FeatureCollection(
features.map({ $0.projected(to: newProjection) }),
calculateBoundingBox: (boundingBox != nil))
featureCollection.foreignMembers = foreignMembers
return featureCollection
}
}
// MARK: - Features
extension FeatureCollection {
/// Insert a Feature into the receiver.
///
/// - note: `feature` must be in the same projection as the receiver.
public mutating func insertFeature(_ feature: Feature, atIndex index: Int) {
guard features.count == 0 || projection == feature.projection else { return }
if index < features.count {
features.insert(feature, at: index)
}
else {
features.append(feature)
}
if boundingBox != nil {
boundingBox = calculateBoundingBox()
}
}
/// Append a Feature to the receiver.
///
/// - note: `feature` must be in the same projection as the receiver.
public mutating func appendFeature(_ feature: Feature) {
guard features.count == 0 || projection == feature.projection else { return }
features.append(feature)
if boundingBox != nil {
boundingBox = calculateBoundingBox()
}
}
/// Remove a Feature from the receiver.
@discardableResult
public mutating func removeFeature(at index: Int) -> Feature {
let removedFeature = features.remove(at: index)
if boundingBox != nil {
boundingBox = calculateBoundingBox()
}
return removedFeature
}
/// Map Features in-place.
public mutating func mapFeatures(_ transform: (Feature) -> Feature) {
features = features.map(transform)
}
/// Map Features in-place, removing *nil* values.
public mutating func compactMapFeatures(_ transform: (Feature) -> Feature?) {
features = features.compactMap(transform)
}
/// Filter Features in-place.
public mutating func filterFeatures(_ isIncluded: (Feature) -> Bool) {
features = features.filter(isIncluded)
}
}