Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GeoDjango - Syntax for saving PointField?

Tags:

geodjango

What is the syntax for saving a PointField, if I have the longitude and latitude geocoded from Google Maps API?

The GeoDjango docs are lacking this sort of information (feels like they only wrote enough details for pros to use it efficiently), and all I've found is this with no accepted answer: How to assign to a Django PointField model attribute?

For context, this is what I'm trying to do:

class Point(models.Model):
    geography = models.PointField(geography=True)
    geometry= models.PointField(srid=3348) #Statistics Canada Lambert projection

Most of the queries from my users will be of the type "Show me all points within roughly 20km from this point, and order them from nearest to furthest". Even though the data has points all over Canada, the user is only interested in points within a small locality with any given query, so the geometry PointField would suffice for 99% of usage.

If distance measurements in meters are required (as opposed to simply ordering them from nearest to furthest), then the geography PointField will be used.

like image 569
davidtgq Avatar asked Jan 22 '16 20:01

davidtgq


1 Answers

From looking at the source code in https://github.com/django/django/blob/master/django/contrib/gis/forms/fields.py :

if not isinstance(value, GEOSGeometry):
            try:
                value = GEOSGeometry(value)
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

It shows that any input that can be converted to a GEOSGeomtery will do. So you can use any widget(for example a TextField/HiddenField) but the text value you return should have the syntax of WKT, HEX, WKB, or GeoJSON.(https://docs.djangoproject.com/ja/1.9/ref/contrib/gis/geos/#creating-a-geometry) The example you linked to (How to assign to a Django PointField model attribute?) is using the WKT format.

like image 195
seto Avatar answered Oct 31 '22 21:10

seto