-2

Say I have a polygon with points a, b, c, d

sample = Polygon(((10, 10), (10, 20), (20, 10), (20, 20)))

Can someone tell me how to find only its neighbours and not the point diagonally opposite. In the example say if I'm in (10,10), I need to get (10,20) and (20,10) not (20,20). Any help will be much appreciated.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Nitish
  • 11
  • 2

1 Answers1

2

From shapely documentation:

The Polygon constructor takes two positional parameters. The first is an ordered sequence of (x, y[, z]) point tuples and is treated, exactly as in the LinearRing case.

Further, polygons border cannot intersect itself.
Therefore, the neighbors of a point are the points just before and just after in the polygon definition.

Component rings are accessed via exterior and interiors properties.

list(polygon.exterior.coords)

returns:

[(10, 10), (10, 20), (20, 10), (20, 20)]

The neighbors of a corner point are the points just before and just after it; we need to treat this list of points in a circular fashion:

def get_two_neighbors(point, polygon):
    """retrieve the two neighboring points of point in the polygon
    :point: a tuple representing a point of the polygon
    :polygon: a shapely Polygon
    return: a tuple of the two points immediately neighbors of point 
    """
    points = list(polygon.exterior.coords)
    ndx = points.index(point)
    two_neighbors = points[(ndx-1)%len(points)], points[(ndx+1)%len(points)]
    return two_neighbors

In the example in reference:

sample = Polygon(((10, 10), (10, 20), (20, 10), (20, 20)))
get_neighbors((10, 10), polygon)

returns:

((20, 20), (10, 20))
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80