root/geojson/trunk/tests/objects.txt

Revision 1063 (checked in by seang, 8 months ago)

Get in step with GeoJSON draft version 6: implement named and linked CRS, do not serialize the default crs

Line 
1 Encoding objects with __geo_interface__
2 ------------------------------------------
3   >>> import geojson
4
5   >>> class LatLon(object):
6   ...     
7   ...    def __init__(self, lat, lon):
8   ...        super(LatLon, self).__init__()
9   ...        self.lat = lat
10   ...        self.lon = lon
11   ...
12   ...    @property
13   ...    def __geo_interface__(self):
14   ...        return dict(type="Point", coordinates=(self.lon, self.lat))
15
16   >>> lat_lon = LatLon(-54.1231, 4.53242)
17  
18   Can be encoded into geojson geometry:
19
20   >>> json = geojson.dumps(lat_lon)
21   >>> json # doctest: +ELLIPSIS
22   '{"type": "Point", "coordinates": [4..., -54...]}'
23
24   Objects with a __geo_interface__ attribute or property can be nested in geojson feature:
25
26   >>> f = geojson.Feature(geometry=lat_lon)
27
28   And feature will encode:
29
30   >>> json = geojson.dumps(f)
31   >>> json # doctest: +ELLIPSIS
32   '{"geometry": {"type": "Point", "coordinates": [4..., -54...]}, "type": "Feature", "properties": {}, "id": null}'
33
34   geojson types can be used to implemented a __geo_interface__:
35
36   >>> class LatLon2(LatLon):
37   ...     @property
38   ...     def __geo_interface__(self):
39   ...             return geojson.Point((self.lon, self.lat))
40   ...
41
42
43   >>> class LatLon2(LatLon):
44   ...     @property
45   ...     def __geo_interface__(self):
46   ...         return geojson.Point((self.lon, self.lat))
47   ...     
48   ...   
49
50   >>> ll2 = LatLon2(-54.1231, 4.53242)
51   >>> json2 = geojson.dumps(ll2)
52   >>> json2 # doctest: +ELLIPSIS
53   '{"type": "Point", "coordinates": [4..., -54...]}'
54  
55
56   Decoding
57     - to a dict
58
59   >>> feature_dict = geojson.loads(json)
60   >>> feature_dict # doctest: +ELLIPSIS
61   {u'geometry': {u'type': u'Point', u'coordinates': [4..., -54...]}, u'type': u'Feature', u'properties': {}, u'id': None}
62
63   - or to an object, via a factory. Here we'll create GeoJSON object.
64
65   >>> ll2 = LatLon2(43.3,-154.1)
66   >>> json = geojson.dumps(ll2)
67   >>> json # doctest: +ELLIPSIS
68   '{"type": "Point", "coordinates": [-154..., 43...]}'
69  
70   >>> geojson.loads(json) # doctest: +ELLIPSIS
71   {u'type': u'Point', u'coordinates': [-154..., 43...]}
72  
73   >>> factory = lambda ob: geojson.GeoJSON.to_instance(ob)
74   >>> geometry = geojson.loads(json, object_hook=factory)
75   >>> geometry   # doctest: +ELLIPSIS     
76   Point(coordinates=[-154..., 43...])
77  
Note: See TracBrowser for help on using the browser.