I have two points, lets say x1,y1 and x2,y2. and i have one more point x3,y3, here is the question, i need to check is x3,y3 coordinate occurs in the line between x1,y1 and x2,y2 or not occurs in javascript.
Thanks in advance.
I have two points, lets say x1,y1 and x2,y2. and i have one more point x3,y3, here is the question, i need to check is x3,y3 coordinate occurs in the line between x1,y1 and x2,y2 or not occurs in javascript.
Thanks in advance.
Try this:
var point_a = [0, 0];
var point_b = [100, 200];
var coord = [50, 100];
function checkCoordinate(coord) {
var slope = (point_b[1] - point_a[1]) / (point_b[0] - point_a[0]);
var newSlope = (point_b[1] - coord[1]) / (point_b[0] - coord[0]);
if (coord[0] > point_a[0] && coord[0] < point_b[0] && coord[1] > point_a[1] && coord[1] < point_b[1] && slope == newSlope) {
alert('Yes! they are in the same line.');
} else {
alert('No :/');
}
}
checkCoordinate(coord);
First, verify x2,y2 do not (numerically) equal either of the end points:
You can create function to check this like (pseudocode):
IsNearZero(value)
if(abs(value) < tolerance) return true
return false
So: // Assuming a false return means (x2,y2) is NOT between them.
if((IsNearZero(x2-x1) && IsNearZero(y2-y1))
return false
if(IsNearZero(x2-x3) and IsNearZero(y2-y3))
return false
Now check if (x2,y2) is between the points:
// Left Edge
if((x1 < x3) && (x2 < x1))
return false
if((x3 < x1) && (x2 < x3))
return false
// Bottom Edge
if((y1 < y3) && (y2 < y1))
return false
if((y3 < y1) && (y2 < y3))
return false
Do similar tests for the right and bottom edges...
Finally, take the cross product of the two lines:
The first segment: (x1,y1,0) -> (x2,y2,0) --> (x2-x1, y2-y1,0)
The second segment: (x1,y1,0) -> (x3,y3,0) --> (x3-x1, y3-y1, 0)
if(not IsNearZero((x2-x1)(y3-y1) - (y2-y1)(x3-x1)) return false
Now, return true...