This python code finds the intersection for lines and I have modified it for handling colinear lines so it returns the intersection of 2 lines when they are collinear.
How to handle cases when they are overlapping in that case it should not return any point of intersection.
The output for this comes
(2,0)
But it should not return an intersection as both of the 2 lines are overlapped.
Input
line1 = ((0, 0), (2, 0))
line2 = ((1, 0), (2, 0))
Code
def line_intersection(line1, line2):
x1, y1 = line1[0]
x2, y2 = line1[1]
x3, y3 = line2[0]
x4, y4 = line2[1]
# Check if the lines are collinear
if (y2 - y1) * (x4 - x3) == (y4 - y3) * (x2 - x1):
# Check if they have a common endpoint
if (x1, y1) == (x3, y3) or (x1, y1) == (x4, y4) or (x2, y2) == (x3, y3) or (x2, y2) == (x4, y4):
return (x1, y1) if (x1, y1) == (x3, y3) or (x1, y1) == (x4, y4) else (x2, y2)
else:
# Return "overlapping" if the lines overlap
if max(x1, x2) >= min(x3, x4) and min(x1, x2) <= max(x3, x4) and max(y1, y2) >= min(y3, y4) and min(y1, y2) <= max(y3, y4):
return "overlapping"
else:
return None
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
xdiff = (x1 - x3, x2 - x4)
ydiff = (y1 - y3, y2 - y4)
div = det(xdiff, ydiff)
if div == 0:
return None
d = (det((x1, y1), (x2, y2)), det((x3, y3), (x4, y4)))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
point = (x, y)
# Check if the intersection point is on both lines
if (x >= min(x1, x2) and x <= max(x1, x2)) and (y >= min(y1, y2) and y <= max(y1, y2)) and (x >= min(x3, x4) and x <= max(x3, x4)) and (y >= min(y3, y4) and y <= max(y3, y4)):
return point
else:
return None