iosswiftmapkitmkannotationmkpolyline

How to add annotations at a certain distance along a MKPolyline route using iOS MapKit in Swift?


I was wondering if anyone knows how to add an annotation to a polyline a certain distance from the start in iOS MapKit?

enter image description here

As you can see from the picture above (sorry for the bad drawing). I have drawn a polyline which is 100 miles long. Now I want to be able to add a map annotation at 13 miles along the line.

Is this something that is possible?

Any information would be greatly appreciated.

Thanks, Dan


Solution

  • Treat your poly line points as a sequence of line segments. Start out with the target distance, 13 miles. Iterate over the points as line segments - .windows(ofCount: 2), compute the length of that line segment, if remaining distance is < line segment length, then your target point is the point that is 'remaining distance' from start of line segment in the direction of end of line segment. Otherwise, subtracting the line segment's length from remaining distance, until either you find your target or fall off the end of the poly line. The question of whether each line segment on poly line represents straight line (along map projection) or great circles (on surface of earth) is unimportant unless the distance between points is large.