Python – Finding Vertices of Edge of Polygon Where Line Intersects Using Shapely

pythonshapely

I have this function to get the intersection point of line and a polygon.
How to find the vertices of the polygon(red dots marked in the image) edge where the line intersects using shapely?
I have managed to find the nearest point using shapely nearestPoint function.

enter image description here

# get the intersection point.
def checkIntersection2(polyX, polyY, linePtX, linePtY):
    poly = LineString([(x, y) for x, y in zip(polyX, polyY)])
    line = LineString([(x, y) for x, y in zip(linePtX, linePtY)])
    intPoints = poly.intersection(line)
    return intPoints

Best Answer

You need to iterate through the edges of the LinearRing of the polygon

from shapely.wkt import loads
lin = loads('LineString (289.63171806167395061 -200.22555066079294761, 380.69030837004402201 -65.28898678414094547)')
pol = loads('Polygon ((112.23259911894263041 -229.94933920704846742, 178.75726872246687549 -113.4132158590308137, 309.44757709251092592 -114.35682819383258391, 376.44405286343607031 -230.42114537444933831, 305.67312775330390195 -344.59823788546259493, 176.39823788546246419 -345.07004405286346582, 112.23259911894263041 -229.94933920704846742))')
# the LinearRing
from shapely.geometry import LineString
polin = LineString(list(pol.exterior.coords))
# intersection 
pt = polin.intersection(lin)
print(pt.wkt)
POINT (327.0268317294637 -144.8110298888352)

Now using Determine if Shapely point is within a LineString/MultiLineString (using the answer of Mike T using the distance with an appropriate threshold because there are floating point precision errors when finding a point on a line)

# iterate through the edges to determine if Shapely point is within
points = list(polin.coords)
for i,j in zip(points, points[1:]):
   if LineString((i,j)).distance(pt) < 1e-8:
       print(i,j)
(309.4475770925109, -114.35682819383258) (376.44405286343607, -230.42114537444934)

Control

enter image description here