Here is some Shapely code that creates three square polygons, p1
, p2
, and p3
. p2
is positioned immediately to the right of p1
, and p3
is positioned immediately underneath.
The problem is that Shapely tells me p1
and p2
don't touch, whereas p1
and p3
do. I can't see what is going wrong here.
from shapely.geometry import Polygon
DELTA = 0.2
def polygonFromPoint(p):
return Polygon([(p[0]-DELTA*0.5, p[1]-DELTA*0.5),
(p[0]-DELTA*0.5, p[1]+DELTA*0.5),
(p[0]+DELTA*0.5, p[1]+DELTA*0.5),
(p[0]+DELTA*0.5, p[1]-DELTA*0.5)])
p1 = polygonFromPoint([-118.8,35.0])
p2 = polygonFromPoint([-118.6,35.0])
p3 = polygonFromPoint([-118.8,34.8])
print(p1)
print(p2)
print(p3)
print(p1.overlaps(p2), p1.intersects(p2), p1.crosses(p2), p1.contains(p2),
p1.disjoint(p2), p1.touches(p2))
print(p1.overlaps(p3), p1.intersects(p3), p1.crosses(p3), p1.contains(p3),
p1.disjoint(p3), p1.touches(p3))
Running this produces the following output:
POLYGON ((-118.9 34.9, -118.9 35.1, -118.7 35.1, -118.7 34.9, -118.9 34.9))
POLYGON ((-118.7 34.9, -118.7 35.1, -118.5 35.1, -118.5 34.9, -118.7 34.9))
POLYGON ((-118.9 34.7, -118.9 34.9, -118.7 34.9, -118.7 34.7, -118.9 34.7))
False False False False True False
False True False False False True
Which shows that Shapely thinks p1
and p2
don't intersect or touch, whereas p1
and p3
intersect and touch.
EDIT: As Gilles-Philippe Paillé and others remarked, this is a precision problem with the polygon coordinates. Using the following tweak fixes the issue in this case:
def polygonFromPoint(p):
return Polygon( [(round(p[0]-DELTA*0.5,1), round(p[1]-DELTA*0.5,1)),
(round(p[0]-DELTA*0.5,1), round(p[1]+DELTA*0.5,1)),
(round(p[0]+DELTA*0.5,1), round(p[1]+DELTA*0.5,1)),
(round(p[0]+DELTA*0.5,1), round(p[1]-DELTA*0.5,1))] )