Swift GeoJson解析 [英] Swift GeoJson Parse
问题描述
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
126.9823439963945,
37.56461982743129
]
}
},
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[
126.9823439963945,
37.56461982743129
],
[
126.98230789017299,
37.564453179812105
],
[
126.98210513804034,
37.563703265276516
],
[
126.98207180945346,
37.56352550784786
],
[
126.9817857308457,
37.56284502921221
],
[
126.98166907678578,
37.562633941789535
],
[
126.98157186492477,
37.56247284870586
],
[
126.98128300624569,
37.56205345097403
],
[
126.98124689891416,
37.56200067907546
]
],
"traffic": [0, 8, 4, 12]
}}
这就是我得到的.而且我不知道解析关键的坐标".此类型取决于几何类型.如果类型是点",则类型变为[字符串].如果类型是"LineString",则类型变为[[String]].我该怎么解决?
This is what I got. And I don't have any idea to parse key "coordinates". This type depends on type of geometry. If type is "Point", type became [String]. If type is "LineString", type became [[String]]. How can I solve it?
推荐答案
您可以使用以下可可豆荚: CodableGeoJSON .
You can use this cocoa pod: CodableGeoJSON.
它具有为您编写的 Codable
结构.您似乎在这里具有未知几何的特征,因此可以执行以下操作:
It has the Codable
structs written up for you. You seem to have a feature with an unknown geometry here, so you can do something like this:
let geoJSON = try JSONDecoder().decode(GeoJSON.self, from: geoJSONData)
guard case .feature(let feature) = geoJSON else {
// the GeoJSON does not contain a feature!
}
// handle each kind of geometry...
switch feature.geometry {
case .point(let coordinates): // coordinates is a GeoJSONPosition
// ...
case .multiPoint(let coordinates): // coordinates is a [GeoJSONPosition]
// ...
case .lineString(let coordinates): // coordinates is a [GeoJSONPosition]
// ...
case .multiLineString(let coordinates): // coordinates is a [[GeoJSONPosition]]
// ...
case .polygon(let coordinates): // coordinates is a [[GeoJSONPosition]]
// ...
case .multiPolygon(let coordinates): // coordinates is a [[[GeoJSONPosition]]]
// ...
case .geometryCollection(let geometries):
// ...
}
如果您不喜欢为此使用库,请查看其源代码并尝试从中学习,特别是
If you don't like using a library just for this, have a look at their source code and try to learn from it, specifically, GeoJSON.swift.
这篇关于Swift GeoJson解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!