Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return GeoJson with Django

I am trying to return a set of coordinates to draw points/rectangles over a map. Currently I'm using Polymaps, but I'm thinking about moving to openlayers, which has examples more clear for a javascript newbie like me.

I want to send a list of coordinates plus a certain value for each one of them. And I'm also looking for sending many lists of coordinates in the same json, each one with another certain value (time), so I can represent different points/polygons over the map for each time.

I have been able to return 3 separated lists with json, one for latitude, one for longitude and another one with the value for each point. But both openlayers and Polymaps use GeoJson at their examples, which looks like the smarter choice.

The problem is, I don't know hot to generate a geoJson response with Django. I found django-geojson, but there is not a clear example to do what I want, and of course not to return many sets for different times.

Any help? I can also accept how to do it with just Json.

What I have now:

#views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
import myproject.databasework as databaseWork
import json

def values(request):
    gpsTime = 1043366400
    pls = databaseWork.getValues(gpsTime)
    latitudes = []
    longitudes = []
    values = []

    for row in pls:
        pointId = row[0]
        value = row[2]
        lat, lon = databaseWork.getCoords(pointId)
        latitudes.append(lat)
        longitudes.append(lon)
        values.append(value)

    jsonObject = {'latitudeList': json.dumps(latitudes),
                  'longitudeList': json.dumps(longitudes),
                  'valuesList': json.dumps(values)}
    return render_to_response('mytemplate.html', jsonObject, context_instance=RequestContext(request))

And this is part of the html:

<script type="text/javascript">
        var po = org.polymaps;
        var map = po.map()
            .container(document.getElementById("map").appendChild(po.svg("svg")))
            .add(po.interact())
            .center({lat: 46, lon: 10})
            .zoom(4);   

        var svg = document.querySelector("svg.map");
        svg.setAttribute("width", "100%");
        svg.setAttribute("height", "100%");
        map.resize();

        map.add(po.image()
            .url(po.url("http://{S}tile.cloudmade.com"
            + "/1a1b06b230af4efdbb989ea99e9841af" // http://cloudmade.com/register
            + "/20760/256/{Z}/{X}/{Y}.png")
            .hosts(["a.", "b.", "c.", ""])));



        // Get values from django response
        var latitude = "{{ latitudeList }}";
        var longitude = "{{ longitudeList }}";
        var vpl = "{{ vplList }}";

        // Draw circles
        // Don't know how to do it with Polymaps yet. Example at http://polymaps.org/ex/cluster.html

   </script>
like image 254
Roman Rdgz Avatar asked Dec 20 '22 05:12

Roman Rdgz


1 Answers

First of all have a look at the geojson spec. That should make pretty clear how to design you data structure.

But there are several things wrong with your approach, basically coding errors. Look at your render_to_response method. You pass the variable jsonObject which is a dict. In your template you try to assign the variable latitudeList which in fact is a key of jsonObject.

Here is an example of how I create a geojson object to display some point geometries with leaflet (a library worth checking out for you).

lati = Vsoil.objects.values_list('latitude',flat=True)
longi = Vsoil.objects.values_list('longitude',flat=True)
ids = Vsoil.objects.values_list('id',flat=True)

geo_json = [ {"type": "Feature",
                    "properties": {
                        "id":  ident,
                        "popupContent":  "id=%s" % (ident,) 
                        },
                    "geometry": {
                        "type": "Point",
                        "coordinates": [lon,lat] }}
                    for ident,lon,lat in zip(ids,longi,lati) ] 


return render_to_response('map.html',
                          {'geo_json': geo_json},
                          context_instance=RequestContext(request))

In your template you can simply assign your object to a js variable like this

var geojsonFeature = {{ geo_json|safe }}
like image 169
LarsVegas Avatar answered Jan 08 '23 14:01

LarsVegas