这是一个用于处理 GeoJSON 数据的 Swift 包。它包含必要的类型,这些类型遵循 Codable
协议,方便数据的编码/解码。
该包的实现旨在遵循 RFC 7946 中定义的规范。
您可以通过克隆存储库并在其中运行 swift run --repl
命令来快速体验此包。
创建一个 FeatureCollection
或者仅仅是一个 Feature
来生成一些 GeoJSON 数据。
let features = FeatureCollection(features: [
Feature(
geometry: .point(Point(longitude: 125.6, latitude: 10.1)),
properties: [
"name": "Dinagat Island"
]
)
])
let json = try JSONEncoder().encode(features)
反方向的操作方式相同。使用标准的 JSONDecoder
将 GeoJSON 数据解码为合适的类型。
let features = try JSONDecoder().decode(FeatureCollection.self, from: json)
如果您不知道要解码的数据是 Feature
还是 FeatureCollection
,请解码类型为 GeoJSONDocument
的值,它可以处理这两种情况。
let document = try JSONDecoder().decode(GeoJSONDocument.self, from: json)
switch document {
case .feature(let feature):
// ...
case .featureCollection(let featureCollection):
// ...
}
此包可以通过 Swift Package Manager 获取,将其克隆 URL 添加到您的项目中即可开始使用。