Skip to content

Commit

Permalink
Add accessor for RFC compliant JSON in Coordinate3D
Browse files Browse the repository at this point in the history
  • Loading branch information
trasch committed Jul 3, 2024
1 parent 831a87e commit bc89c78
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Sources/GISTools/GeoJson/Coordinate3D.swift
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,22 @@ extension Coordinate3D: GeoJsonReadable {
return result
}

/// Dump the coordinate as a JSON object, as defined in the specification.
///
/// - important: The returned array will always contain ``latitude`` and ``longitude``,
/// and ``altitude`` only if it exists.
public var asMinimalJson: [Double] {
var result: [Double] = (projection == .epsg4326 || projection == .noSRID
? [longitude, latitude]
: [longitudeProjected(to: .epsg4326), latitudeProjected(to: .epsg4326)])

if let altitude {
result.append(altitude)
}

return result
}

}

// Custom implementation, because the protocol has different prerequisites
Expand Down
4 changes: 4 additions & 0 deletions Tests/GISToolsTests/GeoJson/CoordinateTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ final class CoordinateTests: XCTestCase {

XCTAssertEqual(String(data: coordinateDataM, encoding: .utf8), "[10,15,null,1234]")
XCTAssertEqual(String(data: coordinateDataZ, encoding: .utf8), "[10,15,500]")

XCTAssertEqual(coordinateM.asMinimalJson, [10, 15])
XCTAssertEqual(coordinateZ.asMinimalJson, [10, 15, 500])
}

func testEncodable3857() throws {
Expand Down Expand Up @@ -97,6 +100,7 @@ final class CoordinateTests: XCTestCase {
let decodedCoordinateZM = try JSONDecoder().decode(Coordinate3D.self, from: coordinateDataZM)

XCTAssertEqual(decodedCoordinateM.asJson, [10.0, 15.0, nil, 1234])
XCTAssertEqual(decodedCoordinateM.asMinimalJson, [10.0, 15.0])
XCTAssertEqual(decodedCoordinateZ.asJson, [10.0, 15.0, 500])
XCTAssertEqual(decodedCoordinateZM.asJson, [10.0, 15.0, 500])
}
Expand Down

0 comments on commit bc89c78

Please sign in to comment.