【发布时间】:2018-07-11 09:15:14
【问题描述】:
我正在尝试打印所有路线步骤的坐标,类似于 Google Maps SDK 的“腿”。
但它告诉我不能使用polyline 属性来获取坐标?
【问题讨论】:
我正在尝试打印所有路线步骤的坐标,类似于 Google Maps SDK 的“腿”。
但它告诉我不能使用polyline 属性来获取坐标?
【问题讨论】:
试试这个:
for step in self.route!.steps as [MKRouteStep] {
否则它会将step 视为AnyObject(它没有定义polyline 属性,因此您会收到编译器错误)。
polyline.coordinate 只给出了折线的平均中心或一个端点。一条折线可以有多个线段。
如果您需要获取所有折线的线段和坐标,请参阅latitude and longitude points from MKPolyline(Objective-C)。
这是一种可能的 Swift 翻译(在 this answer 的帮助下):
for step in route!.steps as [MKRouteStep] {
let pointCount = step.polyline.pointCount
var cArray = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(pointCount)
step.polyline.getCoordinates(cArray, range: NSMakeRange(0, pointCount))
for var c=0; c < pointCount; c++ {
let coord = cArray[c]
println("step coordinate[\(c)] = \(coord.latitude),\(coord.longitude)")
}
cArray.dealloc(pointCount)
}
正如第一个链接的答案所警告的那样,根据路线,您每一步可能会获得数百或数千个坐标。
【讨论】:
? 和 ! 的需要,并告诉编译器将对象 as 处理为其他类型。为什么 Swift 不能像 JavaScript 那样简单易用。
Swift 4.1,截至 2018 年 7 月,基于 other answer。
let pointCount = step.polyline.pointCount
let cArray = UnsafeMutablePointer<CLLocationCoordinate2D>.allocate(capacity: pointCount)
step.polyline.getCoordinates(cArray, range: NSMakeRange(0, pointCount))
for c in 0..<pointCount {
let coord = cArray[c]
print("step coordinate[\(c)] = \(coord.latitude),\(coord.longitude)")
}
cArray.deallocate()
【讨论】: