8

If I can do this:

>>> from django.contrib.gis.geos import GEOSGeometry
>>> from django.contrib.gis.geos import Point
>>> point = GEOSGeometry('POINT(1 5)')
>>> print point
POINT (1.0000000000000000 5.0000000000000000)

Why can I not do this:

>>> lat = 1
>>> lon = 5
>>> point = GEOSGeometry('POINT(lat lon)')

GEOS_ERROR: ParseException: Expected number but encountered word: 'lat'
GEOSException: Error encountered checking Geometry returned from GEOS C function "GEOSWKTReader_read_r".

How can I use a variable to create a GEOSGeometry object?

Nick B
  • 9,267
  • 17
  • 64
  • 105
  • 3
    LAT and LONG appear backwards according to gis stackexchange post http://gis.stackexchange.com/questions/11626/does-y-mean-latitude-and-x-mean-longitude-in-every-gis-software – dan gleebits May 01 '15 at 20:33

2 Answers2

19

The accepted answer is incorrect. Points take the form of "POINT(longitude latitude)". You've reversed them.

Shroud
  • 400
  • 4
  • 7
8

You can surely do that, but with a slight modification

point = GEOSGeometry('POINT(%s %s)' % (lon, lat))

OR

point = GEOSGeometry('POINT(%d %d)' % (lon, lat))

When you do

`'POINT(lat lon)'`

you are not replacing the local variables lat and lon with their appropriate local variable values, and they are being evaluated literally. So, you would need to use substitution.

EDIT: Changed order of (lat, lon) to (lon, lat) to match the order GEOSGeometry is expecting. Although not explicitly stated in the documentation, it is evident from their examples.

Evan
  • 1,960
  • 4
  • 26
  • 54
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 2
    As mentioned in https://stackoverflow.com/a/26472089/1405577 the POINT should be POINT(longitude, latitude). Please correct this comment. – mjabadilla Jul 12 '18 at 22:57