Swift 的 Turf
为原生 iOS、macOS、tvOS、watchOS 和 Linux 应用程序编写的 Swift 空间分析库,由 Turf.js 迁移而来。
Swift 的 Turf 是 实验性的,其公共 API 可能会发生变化。请在看到任何问题时 Будьте бдительными, và 开放问题来解决或不应该添加的功能。
要求
Turf 使用 Swift 4 编写。它需要 Xcode 9.x,并支持以下最低部署目标:
- iOS 8.0 及以上
- macOS 10.10.0(Yosemite)及以上
- tvOS 9.0 及以上
- watchOS 2.0 及以上
此外,您可以在支持Swift的所有平台上将Turf集成到命令行工具中,无需Xcode,包括Linux。
如果您的项目是用Objective-C编写的,您需要在turf-swift和您的Objective-C代码之间编写兼容层。如果您的项目是用Objective-C++编写的,您可能可以使用spatial-algorithms作为Turf的替代方案。
安装
尽管这个库还没有稳定的发布版本,但是可以使用流行的Swift依赖关系管理器来安装预发行版本。
CocoaPods
要使用CocoaPods安装Turf
- 在您的Podfile中指定以下依赖项
pod 'Turf', '~> 0.2'
- 如果您还没有最近运行,请运行
pod repo update
。 - 运行
pod install
并打开生成的Xcode workspace。 - 在您的应用目标中,将
import Turf
添加到任何Swift文件中。
Carthage
要使用Carthage安装Turf
- 将以下依赖项添加到您的Cartfile中
github "mapbox/turf-swift" ~> 0.2
- 运行
carthage bootstrap
。 - 按照Carthage的集成说明的其余部分。您的应用目标中的嵌入式框架应包括Turf.framework。
- 在您的应用目标中,将
import Turf
添加到任何Swift文件中。
Swift Package Manager
要使用Swift Package Manager安装Turf,将以下包添加到您的Package.swift文件中的dependencies
.Package(url: "https://github.com/mapbox/turf-swift.git", .upToNextMinor(from: "0.2"))
然后在您的模块中的任何Swift文件中导入import Turf
。
提供的功能
此正在进行的Turf.js版本的移植包含以下功能
Turf.js | Turf-swift |
---|---|
turf-along | LineString.coordinateFromStart(distance:) |
turf-area | Polygon.area |
turf-boolean-point-in-polygon | Polygon.contains(point:ignoreBoundary:) |
turf-destination | CLLocationCoordinate2D.coordinate(at:facing:) RadianCoordinate2D.coordinate(at:facing:) |
turf-distance | CLLocationCoordinate2D.distance(to:) RadianCoordinate2D.distance(to:) |
turf-helpers#polygon | Polygon(outerRing:innerRings:) |
turf-helpers#lineString | LineString(_:) |
turf-helpers#degreesToRadians | CLLocationDegrees.toRadians() |
turf-helpers#radiansToDegrees | CLLocationDegrees.toDegrees() |
turf-helpers#convertLength turf-helpers#convertArea |
Measurement.converted(to:) |
turf-length | LineString.distance(from:to:) |
turf-line-intersect | Turf.intersection(_:_:) |
turf-line-slice | LineString.sliced(from:to:) |
turf-line-slice-along | LineString.trimmed(from:distance:) |
turf-nearest-point-on-line | LineString.closestCoordinate(to:) |
— | CLLocationCoordinate2D.direction(to:) RadianCoordinate2D.direction(to:) |
— | CLLocationDirection.difference(from:) |
— | CLLocationDirection.wrap(min:max:) |
GeoJSON
turf-swift还包含一个实验性的GeoJSON编码器/解码器,支持Codable。
// Decode unknown GeoJSON type
let geojson = try! GeoJSON.parse(data: data)
// Decode known GeoJSON type
let geojson = try! GeoJSON.parse(data: data, as: FeatureCollection.self)
// Initialize a PointFeature and encode as GeoJSON
let coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 1)
let point = Point(coordinate)
let pointFeature = PointFeature(point)
let data = try! JSONEncoder().encode(pointFeature)
let json = String(data: data, encoding: .utf8)
print(json)
/*
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
1,
0
]
}
}
*/