9

I have a list of Shapely polygons in Python. To find out which polygon touch is easy, using the .touches() method. However, I need something that returns True only when the polygons share more than one point (in other words shares a border). Let me illustrate:

In [1]: from shapely.geometry import Polygon
In [2]: polygons = [Polygon([(0,0),(0,1),(1,1),(1,0)]), Polygon([(1,0),(1,1),(2,1),(2,0)]), Polygon([(2,1),(2,2),(3,2),(3,1)])]

In [3]: polygons[0].touches(polygons[1])
Out[3]: True

In [4]: polygons[0].touches(polygons[2])
Out[4]: False

In [5]: polygons[1].touches(polygons[2])
Out[5]: True

In this case, polygon 0 and 1 shares two points (an entire border). Polygon 1 and 2 only shares one point. What I'm looking for is a function that would give me True, False, False in the above example or just something that returns the number of touching point, then I can do the rest of the logic myself.

And of course, any solution that does not involve manually iterating through all points is optimal - if I need to do that, it kind of defeats the purpose of using Shapely :-)

Georgy
  • 12,464
  • 7
  • 65
  • 73
XerXes
  • 723
  • 1
  • 9
  • 17

2 Answers2

13

If you truly want to check if two polygons share more than x number of points you can simply do this:

p0,p1,p2 = polygons
x = 2
len(set(p1.boundary.coords).intersection(p2.boundary.coords))>=x

But I think what you may want is to determine if two edges are colinear (and overlapping).

This implementation of Andrew's suggestions is probably what you are looking for:

>>> type(p0.intersection(p1)) is geometry.LineString
True
>>> type(p1.intersection(p2)) is geometry.LineString
False
Paul
  • 42,322
  • 15
  • 106
  • 123
  • Thank you :-) I had deducted that from Andrew's post, but not been able to answer. But thanks a bunch anyway :-) – XerXes Dec 26 '09 at 18:55
  • 2
    Just for the record (it might help someone else): It should check for geometry.MultiLineString, not geometry.LineString – XerXes Dec 31 '09 at 12:30
7

i haven't used shapely, but have you tried seeing if the intersection of the two polygons is a line?

andrew cooke
  • 45,717
  • 10
  • 93
  • 143