Published on December 12, 2013
I've been having a lot of fun working with django-geojson, and django-leaflet to return records from a Point dataset kept in PostGIS. The project docs are very clear but I found an additional tutorial by one of the developers Mathieu Leplatre, which makes it very simple to get a basic example up and running.
I had a slightly different data model - my gemoetry field was called 'Point' rather than 'geom'. Here I used the a Django Class Based View to change the Geomety option.
urls.py
url(r'^data.geojson$', MapLayer.as_view(model=Club), name='data2'),
views.py
from djgeojson.views import GeoJSONLayerView
class MapLayer(GeoJSONLayerView):
# Other options
geometry_field = 'point'
This returns the values of the data just fine.
One interesting thing to do with spatial data is run Django spatial lookups against it but to do so needs some parameters. I was unsure what approach to take to access the Django request object, particularly as the documentation for django-geojson appears to state that the class views should only be used for the specified options. Even so accessing the request object within views.py did work and seemed a lot cleaned than putting it in urls.py or somewhere else.
So I decided to email the developer and got a very helpful reply suggesting the following:
urls.py
url(r'^data.geojson?.*$', MapLayer.as_view(model=Club), name='data')
views.py
from django.contrib.gis.geos import *
from django.contrib.gis.measure import D # ''D'' is a shortcut for ''Distance''
class MapLayer(GeoJSONLayerView):
def get_queryset(self):
distance = self.request.GET.get('distance')
try:
distance = float(distance)
except:
distance = 100
pnt = fromstr('POINT(<lon> <lat>)', srid=4326)
return self.model.objects.filter(point__distance_lte=(pnt, distance))
# Other options
geometry_field = 'point'
Happliy this works very well (assuming you replace the <lon> <lat> values with actual values!). A working url would be as follows:
http://127.0.0.1:8000/data.geojson?distance=100000
With thanks to Mathieu Leplatre.
An entry posted on December 12, 2013.
Categories: Data and Open Source
There are no tags for this entry.