skeeph
skeeph

Reputation: 490

How to get overlapping objects in geodjango?

I'm creating an app using geodjango.
I have a model like so:

class WorldBorder(models.Model):
    name = models.CharField(max_length=50)
    mpoly = models.MultiPolygonField()

There can be 2 or more objects with overlapping borders in my database.

How can I determine if some objects have overlapping borders?
How can I get a queryset of objects with overlapping borders?

Thanks

Upvotes: 1

Views: 630

Answers (1)

John Moutafis
John Moutafis

Reputation: 23134

You have 2 options, depending on what you want to achieve:


Option 1: You can use the __overlaps lookup:

Example of use:

an_mpoly = WorldBorder.objects.get(name='a_name').mpoly
overlapping_mpolys = WorldBorder.objects.filter(mpoly__overlaps=an_mpoly)

Now overlapping_mpolys is a queryset, containing every WorldBorder object who's mpoly overlaps with the mpoly of a WorldBorder object with name='a_name'.


Option 2: If you need an object to object overlap check, you can utilize GEOS API overlaps method:

Example of use:

mpoly_1 = WorldBorder.objects.get(name='name_1').mpoly
mpoly_2 = WorldBorder.objects.get(name='name_2').mpoly

if mpoly_1.overlaps(mpoly_2):
    print("{} and {} are overlapping".format(mpoly_1, mpoly_2))

Upvotes: 3

Related Questions