django json serializer does not implement geojson

℡╲_俬逩灬. 提交于 2019-11-29 12:01:28
ubiquitousthey

See the answer to this question.
Rendering spatial data of GeoQuerySet in a custom view on GeoDjango

You can also look at the render_to_geojson method in this project. http://geodjango-basic-apps.googlecode.com/

You need to write your own serializer. Just inherit from the DjangoJSONEncoder, here's one I created that supports the Point type:

from django.core.serializers.json import DjangoJSONEncoder
from django.contrib.gis.geos import Point

class GeoJSONEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Point):
            return obj.coords
        return super(GeoJSONEncoder, self).default(obj)

You can then use it like so:

from my_app.serializers import GeoJSONEncoder
from django.utils import simplejson

json = simplejson.dumps(data, cls=GeoJSONEncoder)

So... I have done something slightly unpretty. I hardcoded the non-geojson parts of the serializer and used the json function from GEOS to get the geojson part.

So the method in the model looks like:

def get_footprint_json(self):
    geojson=self.footprint.json
    json='{"type": "Feature","geometry": %s,"properties": {"name":"%s","url_name":"%s"}}'%(geojson,self.name,self.url_name)
    return json

And... I have a view that looks like this:

json='{ "srid":4326, "type": "FeatureCollection","features": ['+','.join([asset.get_footprint_json() for asset in assets])+'] }'
return HttpResponse(json)

I'd be curious to see if anyone else has a better way or if django has updated their serializer to include geojson.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!