Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersecting multipolygon layer with polygon in GeoDjango

I have a Region GeoDjango model (deriving from django.contrib.gis.db.models.Model), with a geom field, which is a django.contrib.gis.db.models.MultiPolygonField.

I'd like to compute the intersection of this model (representing a set of polygonal regions stored in PostGIS) with a GeoJSON polygonal "query":

from django.contrib.gis.geos import GEOSGeometry

query = GEOSGeometry(
    '{"type":"Polygon","coordinates":[[[-80.983786,43.929011],[-80.511513,43.778458],[-80.291852,44.079184],[-80.775108,44.232127],[-80.983786,43.929011]]]}'
)

I tried many things:

results = Region.objects.all().intersection(query) 

or

from django.contrib.gis.db.models.functions import Intersection

results = Intersection(Region.objects.all(), query)

but it seems I don't have the right approach.

Note that I do not want to simply compute the subset of regions which intersect with the query, but rather their exact intersection (in other words the resulting set of polygons should have the exact same shape as the query).

like image 429
cjauvin Avatar asked Dec 01 '25 07:12

cjauvin


1 Answers

Essentially we need to annotate the intersection (if any) of each Region's geom with the given query. Doing so with a DB query look like this:

from django.db.models import F
from django.contrib.gis.db.models.functions import Intersection
from django.contrib.gis.geos import GEOSGeometry

query = GEOSGeometry(
    '{"type":"Polygon","coordinates":[[[-80.983786,43.929011],[-80.511513,43.778458],[-80.291852,44.079184],[-80.775108,44.232127],[-80.983786,43.929011]]]}'
) 

results = Region.objects.filter(geom__intersects=query).annotate(
    intersection_geom=Intersection(F('geom'), query)
)

Query Explanation:

  1. Filter the Regions that intersect the query, using the intersects spatial lookup.
  2. Calculate the result of Intersection between a Region's geom field and the query, using the F() expression to access the geom (an explanation on F() usage can be found in my Q&A example: How to execute arithmetic operations between Model fields in django)
  3. annotate the calculated Intersection into each corresponding Region as a field named intersection_geom.

After the query execution, the results will contain each Region that intersects the query geom, with the intersection_geom field containing the exact geometry of the corresponding intersection.

like image 70
John Moutafis Avatar answered Dec 02 '25 22:12

John Moutafis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!