I was recently working on a project where I needed to find the distance from CGPoint to line segment defined by two CGPoints. I used it for selecting drawn objects.

1 2 3 4 5 6 7 8 9 10 |
+ (CGFloat)distanceFromPoint:(CGPoint)P toLineWithPointA:(CGPoint)A andPointB:(CGPoint)B { if ((P.x - A.x) * (B.x - A.x) + (P.y - A.y) * (B.y - A.y) < 0) return sqrt(pow((P.x - A.x), 2) + pow((P.y - A.y), 2)); if ((P.x - B.x) * (A.x - B.x) + (P.y - B.y) * (A.y - B.y) < 0) return sqrt(pow(P.x - B.x, 2) + pow(P.y - B.y, 2)); return ABS((P.x * (A.y - B.y) + P.y * (B.x - A.x) + (A.x * B.y - B.x * A.y)) / sqrt(pow(B.x - A.x, 2) + pow(B.y - A.y, 2))); } |

There are three cases:

If point A is closest – returning distance from point P to point A:

1 2 |
if ((P.x - A.x) * (B.x - A.x) + (P.y - A.y) * (B.y - A.y) < 0) return sqrt(pow((P.x - A.x), 2) + pow((P.y - A.y), 2)); |

If point B is closest – returning distance from point P to point B:

1 2 |
if ((P.x - B.x) * (A.x - B.x) + (P.y - B.y) * (A.y - B.y) < 0) return sqrt(pow(P.x - B.x, 2) + pow(P.y - B.y, 2)); |

Let’s say line X is defined by points A and B and line Y is perpendicular to line X and defined by point P making point Z the intersection of line X and Y – returning distance from point P to point Z. This is the only case where line Y intersects with line segment defined by A and B – previous two cases do not contain point of intersection so in those cases distances from point P to points A or B are calculated.

1 |
return ABS((P.x * (A.y - B.y) + P.y * (B.x - A.x) + (A.x * B.y - B.x * A.y)) / sqrt(pow(B.x - A.x, 2) + pow(B.y - A.y, 2))); |

Thanks, great code. My question is the following: My coordinates for the Points A, B and P are given in longitude/latitude. How to convert them (back) to cartesian coordinates in order to use your code?