What is the difference between Polygon.contains and Polygon.within?

11,046

They are inverse relationships: A contains B, and B is within A.

   >>> A.contains(B)
   True
   >>> B.within(A)
   True

   +----------------------------------+
   |                                  |
   |         +----------+             |
   |         |          |             |
   |         |          |             |
   |         |          |             |
   |         |          |             |
   |         |          |             |
   |         |    B     |             |
   |         |          |             |
   |         +----------+             |
   |                                  |
   |                                  |
   |   A                              |
   |                                  |
   +----------------------------------+
Share:
11,046

Related videos on Youtube

Sounak
Author by

Sounak

Updated on September 16, 2022

Comments

  • Sounak
    Sounak almost 2 years

    The Docstring says:

    Polygon.contains Returns True if the geometry contains the other, else False

    Polygon.within Returns True if geometry is within the other, else False

    How are they different?

  • Sounak
    Sounak about 9 years
    what happens if A overlaps B ? why there are two functions? isn't one enough?
  • chepner
    chepner about 9 years
    I think neither would be true, since neither shape is wholly within the other. If you mean A and B are essentially the same shape, both would be false. From the manual for contains (emphasis mine): "Returns True if the object’s interior contains the boundary and interior of the other object and their boundaries do not touch at all."
  • chepner
    chepner about 9 years
    One would be sufficient--you could define within(self, obj) as simply return obj.contains(self)--but it may be more readable to use one or the other, depending on the context.
  • Sounak
    Sounak about 9 years
    poly = Polygon(((0, 0), (0, 2), (2, 2), (2, 0))) po = Point((1,1)) print poly.contains(po) True print poly.within(po) False
  • Sounak
    Sounak about 9 years
    something is different here.
  • chepner
    chepner about 9 years
    po.within(poly) should be true, though. You have to switch the caller and the argument.