Login

GeoJSON Serializer for GeoDjango (gis)

Author:
danielsokolowski
Posted:
May 12, 2011
Language:
Python
Version:
1.3
Tags:
GeoJson Serializer
Score:
3 (after 3 ratings)

Please use the updated version http://djangosnippets.org/snippets/2596/

Unfortunately the built in Django JSON serialzer encodes GeoDjango GeometyrField as simple text. This snippet extends django's serializer and adds support for GeoJson format.

Built in JSON serializer output:

[{"pk": 1, ... "geopoint": "POINT (-76.5060419999999937 44.2337040000000030)" ... }]

GeoJSON serializer ouput:

[{"pk": 1, ...  "geopoint": {"type": "Point", "coordinates": [-76.503296000000006, 44.230956999999997]}}]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'''
Please use the updated version located at http://djangosnippets.org/snippets/2596/

Created on 2011-05-12

@author: Daniel Sokolowski

Extends django's built in JSON serializer to support GEOJSON encoding

Requirements:
    Install and setup geodjango (django.contrib.gis)

Install:
    Add ``SERIALIZATION_MODULES = { 'geojson' : 'path.to.geojson_serializer' }`` to your 
    project's ``settings.py`` file.
    
Usage:
    from django.core import serializers
    geojson = serializers.serialize("geojson", <Model>.objects.all())

'''
from django.core.serializers.json import DjangoJSONEncoder
from django.core.serializers.json import Serializer as OverloadedSerializer
from django.utils import simplejson
from django.contrib.gis.db.models.fields import GeometryField
from django.contrib.gis.geos.geometry import GEOSGeometry
from django.utils import simplejson as json


class Serializer(OverloadedSerializer):
    def handle_field(self, obj, field):
        """
        If field is of GeometryField than encode otherwise call parent's method
        """
        value = field._get_val_from_obj(obj)
        if isinstance(field, GeometryField):
            self._current[field.name] = value
        else:
            super(Serializer, self).handle_field(obj, field)

    
    def end_serialization(self):
        simplejson.dump(self.objects, self.stream, cls=DjangoGEOJSONEncoder, **self.options)

class DjangoGEOJSONEncoder(DjangoJSONEncoder):
    """
    DjangoGEOJSONEncoder subclass that knows how to encode GEOSGeometry value
    """
    
    def default(self, o):
        """ overload the default method to process any GEOSGeometry objects otherwise call original method """ 
        print(type(o))
        if isinstance(o, GEOSGeometry):
            return json.loads(o.geojson)
        else:
            super(DjangoGEOJSONEncoder, self).default(o)

More like this

  1. Updated: GeoJSON Serializer for GeoDjango (gis) by danielsokolowski 3 years, 3 months ago
  2. SerializedObjectField by dominno 4 years, 12 months ago
  3. Custom model field to store dict object in database by rudyryk 4 years, 10 months ago
  4. CSV to JSON Fixture by briangershon 5 years, 6 months ago
  5. MarkupField by jpt 6 years ago

Comments

hutzelknecht (on November 6, 2011):

Awesome - thanks. this saves me a lot of headaches.

#

Please login first before commenting.