Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multipolygon contains point in GeoDjango

I have a MultiPolygon field, preferences.locations, and a Point field, rental.location. When querying to check whether a rental's location is contained by preferences.locations, the query is only successful if the rental.location is contained by the first polygon in the preferences.locations MultiPolygon.

For example, with these geometries:

point1 = (81.20141954209073, -129.891357421875)
point2 = (40.70875101828792, -73.93179774284363)

preferences.locations = MultiPolygon(
    Polygon(((81.14748070499664, -163.289794921875),

              point1, # contains the first point

              (81.14748070499664, -163.289794921875),
              (81.14748070499664, -163.289794921875),)),

    Polygon(((40.70718949655447, -73.98123621940613),

              point2, # contains the second point

              (40.683762276904055, -73.99702906608582),
              (40.70718949655447, -73.98123621940613),)),
)

rental1.location = Point(*point1)

rental2.location = Point(*point2)

When querying to check which rentals' locations are contained by preferences.locations, while both rentals should be returned, only the first rental is returned.

>>> Rental.objects.filter(location__contained=preferences.locations)
[<Rental: Rental object>] # rental1

How can I successfully check which rentals' locations are contained by preferences.locations (no matter which Polygon they're contained by).

like image 691
yndolok Avatar asked Jan 09 '23 03:01

yndolok


1 Answers

The proper way to check whether a Point is contained by a MultiPolygon is to use point.intersects(multipolygon).

>>> Rental.objects.filter(location__intersects=preferences.locations)
[<Rental: Rental object>, <Rental: Rental object>]
like image 143
yndolok Avatar answered Feb 03 '23 05:02

yndolok