Search code examples
djangogeodjango

Slicing geometry with geodjango based on another geometry


I have a PostgreSQL database set up and am using Geodjango to interact with the geometry saved in this database. My use case is as follows:

  • In the database, I have a complicated, large multi-polygon containing all the parks in the country. This is contained in a single geometry field.
  • I have another record that contains the boundaries of my region.
  • What I want to do is somehow truncate/slice the multi-polygon so that it removes those that are not within the boundaries.

Sample code:

region = Shapefile.objects.get(pk=1)
region_boundaries = region.geometry # this contains the boundaries for the region

all_parks_in_country = Shapefile.objects.get(pk=2)
parks = all_parks_in_country.geometry # and this one now has all the national parks

sliced_geometry = ...
# .... And here is where I am stuck! 

I am providing visuals below. Note that I am trying to get the sliced geometry in the views, in Python -- once I have it there I will then use it as needed (show it in the HTML files or whatever is needed).

The first map shows the entire country and in green the national parks.

First map

The second map shows, in purple outline, the boundaries of my region.

Second map, outline of region

Third map showing in red those (parts of!) the national parks multi-polygon that should ideally be 'cut out' of the national geometry.

Third map, in red the cutouts


Solution

  • Since you have isolated the geometries you can use the GEOS API intersection method on them.

    The method:

    Returns a GEOSGeometry representing the points shared by this geometry and "other".

    So you can take the "sliced" geom as follows:

    sliced_geometry = parks.intersection(region_boundaries)