0

I'm building a geo-aware iPhone app and I would like to calculate the distance between the user's location and a line between two points. I found this answer that does something like this:

Shortest distance between a point and a line segment

However this doesn't take into account that the line is finite - if the user is far away from the line but near where an infinite projection of the line would be, it would come out as the distance between the point and the infinite projection, rather than the nearest point on the line.

Community
  • 1
  • 1
benwad
  • 6,414
  • 10
  • 59
  • 93
  • i guess you are talking about circle over a sphere surface, where "lines" are always "circle" – meronix May 25 '12 at 12:20
  • Technically yes, however I was thinking the distances I'm dealing with are small enough that I could treat them as euclidean coordinates rather than spherical coordinates - would that be a valid simplification? – benwad May 25 '12 at 12:29
  • Maybe you could take a sample set of points (with a reasonable resoulution) and compare each point and break when you reach the end of points or starting to get further away than the distnace to the last point. – picknick May 25 '12 at 12:35
  • 1
    the first answer of Grumdrig there takes it into account - "if (t < 0.0) return distance(p, v); // Beyond the 'v' end of the segment " and similar for other end – MBo May 25 '12 at 12:38
  • maybe this could help: http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html – CarlJ May 25 '12 at 13:05
  • @picknick that's a good idea - I'll give that a go. – benwad May 25 '12 at 17:29

2 Answers2

1

if you have line AB and point P you should find Distance from a point P to a line AB, then distance AP and BP and choose the shortest one (sorry for bad English)

sheraza
  • 511
  • 4
  • 11
1

Using the solution you linked to to give you a point on an infinite line as you describe. Then check to see if that point is within your bounded line (i.e. x coord lies within min and max x coord and same for y). If it does then return. Otherwise the closest point is one of the end points. Work out which. Done.

brain
  • 5,496
  • 1
  • 26
  • 29
  • @MBo identified the actual solution. The value of `t` tells you everything you need to know about where on the finite line the test point projects. – acraig5075 May 26 '12 at 09:46