harry lakins - 2 months ago 10x
iOS Question

How to draw a line based on giving bearing/heading value at current location in iOS/swift?

I have been doing a ton of research but found nothing. With MapKit, I have got a map that shows current location and elsewhere a function that calculates a heading/bearing value (not necessarily the actual heading). How can I draw a line on the map that will start at current location, and point in direction of the given heading ? (Does not matter how long the line is, as in it has no meaningful end point). I am not asking you to write the code for me but would appreciate some detailed direction. Hope this helps others too.

Cheers

Your coordinates are polar, which means you have a direction and a length. You just need to convert them to Cartesian, which gives you a horizontal offset and a vertical offset. You do that with a little trigonometry.

``````let origin = CGPoint(x: 10, y: 10)
let length: CGFloat = 20

let endpoint = CGPoint(x: origin.x + cos(heading)*length,
``````func radians(forDegrees angle: CGFloat) -> CGFloat {