Adding polygon directly to Geodjango / PostGIS
I've been messing around with Geodjango and I just want to add a simple polygon field to the database and then run an ellipsis on it to make sure everything is working fine.
Here's my code in views.py:
#adding a polygon
pe = PolygonExample.objects.create(name="uk_polygon", poly="POLYGON((58.768200159239576, -12.12890625, 58.49369382056807 1.1865234375, 49.18170338770662 -12.9638671875, 50.2612538275847 5.537109375))" )
#doing the point-in-polygon check
result = PolygonExample.objects.filter(poly__contains='POINT(52.696361078274485 -0.87890625)')
and this is what I have in models.py:
class PolygonExample(models.Model):
name = models.CharField(max_length=16, db_index=True)
poly = models.PolygonField()
objects = models.GeoManager()
But when I try to add a polygon (PolygonExample.objects.create), I get an error: "Error encountered geometry validation returned from GEOS C function" GEOSWKTReader_read ".
Is my code adding a polygon incorrectly? I'm not sure if I understand how to fold in lat / lon coordinates directly.
Or is it a bug with the GEOS installation?
Thank.
+2
Steve
source
to share
1 answer
There are several issues with your WKT :
- Coordinate sizes are separated by spaces
- Coordinate pairs (or tuples) are separated by commas
- Coordinate ordering (x, y) - i.e. (lon, lat)
Testing the landfill around the UK should look like this:
>>> wkt = "POLYGON((-12.12890625 58.768200159239576, 1.1865234375 58.49369382056807, 5.537109375 50.2612538275847, -12.9638671875 49.18170338770662, -12.12890625 58.768200159239576))"
>>> pe = PolygonExample.objects.create(name="uk_polygon", poly=wkt)
>>> result = PolygonExample.objects.filter(poly__contains='POINT(-0.87890625 52.696361078274485)') # note x,y order here, too
>>> result[0].name
u'uk_polygon'
+5
source to share