1

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?

enter image description here

Sahat Yalkabov
  • 32,654
  • 43
  • 110
  • 175

2 Answers2

2

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).


By the way, note that 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.

Community
  • 1
  • 1
  • Swift is confusing. I can't seem to understand the need for optionals `?` and `!` and telling compiler to treat an object `as` some other type. Why can't a Swift be simple to use like JavaScript. – Sahat Yalkabov Mar 02 '15 at 07:11
  • Thanks for the help, I was able to get coordinates from each step of the route. – Sahat Yalkabov Mar 02 '15 at 07:14
1

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()
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Brian Hong
  • 930
  • 11
  • 15