I know there are shorter solutions that use dot product, but I don't know what the logic behind doing so involves so I came up with something that I understand myself (i will research the dot product later). Here is my solution, with comments to explain what I am doing at each stage. Is there anything I have missed in this? Please let know if you require the code to be 'more pseudocode' like and i will edit it. Thank you
BOOL pointLiesOnLineSegment(MKMapPoint aPoint, PMStraightMapLine aLine)
{
//1st, check if point is within triangle defined by line points
double minX = MIN(aLine.point1.x, aLine.point2.x);
double maxX = MAX(aLine.point1.x, aLine.point2.x);
double minY = MIN(aLine.point1.y, aLine.point2.y);
double maxY = MAX(aLine.point1.y, aLine.point2.y);
BOOL pointLiesInArea = ((minX<=aPoint.x<=maxX) && (minY<=aPoint.y<=maxY));
if(pointLiesInArea)
{
//2nd, check if passing in the x value into the line's equation gives the same y value, or vice versa (in other words check if point is on line)
if((aLine.point2.x - aLine.point1.x) == 0)
{
//undefined gradient for line, therefore:
double xValueAlongStraightLine = aLine.point1.x;
//since the line only has one x value throughout, the point must have the same:
if(aPoint.x == xValueAlongStraightLine)
return YES;
}
else
{
double lineGradient = gradientForLine(aLine);
//insert aPoint.x into line equation and check if y value is the same
double yValueFromLineEquation = (lineGradient*aPoint.x) - (lineGradient*aLine.point1.x) + aLine.point1.y;
if(yValueFromLineEquation == aPoint.y)
return YES;
}
}
return NO;
}
Assuming all the subroutines work as expected, this should do what you want it to. That being said, there are certainly more efficient (or, at least, concise) ways of handling this problem, even if we don't bring dot products into this.
Some potential sources for error:
aLineis defined by two identical points?aPointis identical to one of the endpoints of the line?If you're interested in a different method, say so. For one, we can get rid of the "line equation" business.