pythonshapely

How can I find the following vertice in a shapely polygon in a specific direction from a calculated nearest_point?


I have a polygon "poly" and a point "A". With the nearest_point function I can calculate the nearest point "p1" on the polygon to the point "A". Now I would like to determine the next vertice of the polygon to that nearest point in a specific direction. How can I do this?

from shapely.geometry import Point, Polygon
from shapely.ops import nearest_points

poly=Polygon([(0,0),(10,0),(10,11),(0,8)])
pointA=Point(11,5.5)

p1,_=nearest_points(poly,pointA)

p1.wkt
#'POINT (10 5.5)'

So, in this example I would be looking for

poly.exterior.coords[2]
#(10.0, 0.0)

Calculating the closest vertice of "poly" to "p1" doesn't help as the next vertice doesn't necessarily have to be the closest.


Solution

  • You can convert the exterior coordinates of the polygon to the a MultiPoint structure and then pass that into nearest_points. This will return just a the single closest point from list of vertices in the polygon's exterior.

    from shapely.geometry import Point, Polygon, MultiPoint
    from shapely.ops import nearest_points
    
    poly = Polygon([(0,0), (10,0), (10,11), (0,8)])
    pointA = Point(11,5.5)
    multi_pnt = MultiPoint(poly.exterior.coords)
    closest_vertex, p = nearest_points(multi_pnt, pointA)
    
    closest_vertex
    # returns:
    <POINT (10 0)>