1+ from urlparse import urlparse
2+
13from django .shortcuts import render
4+ from django .http import HttpResponse , JsonResponse
5+ from django .core .exceptions import ObjectDoesNotExist
6+
7+ from places .models import MapInstance , MapData , MapObject
28
39# Create your views here.
10+
11+ def map_instance_geojson (request , map_instance_id ):
12+
13+ '''
14+ Fetched all objects (and properties) for a given map instance,
15+ returns a GEOJSON feature collection.
16+ '''
17+
18+ # Fetch the map instance
19+
20+ try :
21+ map_instance = MapInstance .objects .get (id = map_instance_id )
22+ except ObjectDoesNotExist :
23+ return JsonResponse ({"Error" : "Map Instance with ID %s does not exist!" % map_instance_id })
24+
25+ # Deduce URL from request
26+
27+ request_url = urlparse (request .build_absolute_uri ())
28+ base_url = 'http://%s%s' % (request_url .netloc , request_url .path )
29+
30+ # Set pagination params
31+
32+ page = int (request .GET .get ('page' , 1 ))
33+ x = (page - 1 ) * 25
34+ y = page * 25
35+
36+ # Prepare GEOJSON response
37+
38+ response = {
39+ "type" : "Feature Collection" ,
40+ "count" : 25 ,
41+ "next" : "%s?page=%s" % (base_url , page + 1 ),
42+ }
43+
44+ if page <= 1 :
45+ response ['previous' ] = None
46+ else :
47+ response ['previous' ] = "%s?page=%s" % (base_url , page - 1 )
48+
49+ # Fetch and serialise map objects
50+
51+ map_objects = MapObject .objects .filter (map_instance = map_instance ).order_by ('id' )[x :y ]
52+
53+ features = []
54+ for map_object in map_objects :
55+ feature = {
56+ "type" : "Feature" ,
57+ "geometry" : {
58+ "type" : "Point" ,
59+ "coordinates" : [
60+ float (map_object .longitude ),
61+ float (map_object .latitude ),
62+ ]
63+ },
64+ "properties" : {}
65+ }
66+
67+ object_data = MapData .objects .filter (map_object = map_object )
68+
69+ for field in object_data :
70+ field_name = field .schema_field
71+ feature ["properties" ][field .schema_field .field_name ] = field .field_value
72+
73+ features .append (feature )
74+
75+ response ['features' ] = features
76+
77+ return JsonResponse (response , safe = False )
78+
79+
80+
0 commit comments