Distance from point to line segment

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.

There are three cases:

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

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

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.

Related Post

Remember to share...Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someone

One thought on “Distance from point to line segment

  1. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *