Matthias La
Matthias La

Reputation: 295

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.

Upvotes: 0

Views: 40

Answers (2)

James
James

Reputation: 36746

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)>

Upvotes: 0

Matthias La
Matthias La

Reputation: 295

It seems I have found an answer by iterating over the points of the polygon and by calculating every line of the polygon and checking whether the point "p1" is on that line or not:

from shapely.geometry import Point, Polygon, LineString

for i in range(1,len(polygon.exterior.coords)-1):
    line = LineString([polygon.exterior.coords[i-1],polygon.exterior.coords[i]])
    if line.distance(p1) < 1e-8:  # True
        print(polygon.exterior.coords[i])
    break

#(10.0, 11.0)

However I am also interested in other approaches.

Upvotes: 0

Related Questions