views:

524

answers:

1

I'm messing around with Geodjango, and I just want to add a simple polygon field to a database and then run a point-in-polygon on it to to make sure everything is working okay.

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 here's 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 adding the polygon (PolygonExample.objects.create), I get an error: "Error encountered checking Geometry returned from GEOS C function "GEOSWKTReader_read".

Is my code for adding the polygon wrong? I'm not sure I understand how to slot in lat/lon coordinates directly.

Or is this a GEOS installation error?

Thanks.

A: 

Your WKT has a few problems:

  1. Coordinate dimensions are separated by spaces
  2. Coordinate pairs (or tuples) are separated by commas
  3. Coordinate ordering is (x, y) -- that is (lon, lat)

Testing a polygon 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'
tcarobruce