I am trying to print coordinates of all route steps, similar to Google Maps SDK's "legs".
But it tells me that I cannot use polyline
property to obtain a coordinate?
I am trying to print coordinates of all route steps, similar to Google Maps SDK's "legs".
But it tells me that I cannot use polyline
property to obtain a coordinate?
Try this:
for step in self.route!.steps as [MKRouteStep] {
otherwise it treats step
as AnyObject
(which doesn't have a polyline
property defined so you get that compiler error).
polyline.coordinate
just gives the average center of the polyline or one endpoint. A polyline can have more than one line segment.
If you need to get all the line segments and coordinates along the polyline, see latitude and longitude points from MKPolyline (Objective-C).
Here's one possible translation to Swift (with help from 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 the first linked answer warns, you may get hundreds or thousands of coordinates per step depending on the route.
Swift 4.1, as of July 2018, based on the 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()