I'm developing a Django application using Django-leaflet and Postgresql / PostGIS. I retrieve the data in views.py and I convert them in GeoJSON format using Django's serializer. My views.py:
from geonode.geoloc.models import Transport
from django.template import RequestContext
from django.core.serializers import serialize
import json, ast
class LookupView(FormView):
template_name = 'geoloc/lookupresults.html'
form_class = LookupForm
def get(self, request):
return render_to_response('geoloc/lookup.html', RequestContext(request))
def form_valid(self, form):
# Get data
latitude = form.cleaned_data['latitude']
longitude = form.cleaned_data['longitude']
# Look up roads
roads = Transport.objects.all()[0:5]
roads_json = serialize('geojson', roads,
fields=('geom',))
# I remove crs key because it is not recommended by http://geojsonlint.com/
new_roads_json = json.loads(roads_json)
new_roads_json.pop('crs', None)
new_roads_json = json.dumps(new_roads_json)
# Render the template
return self.render_to_response({
'new_roads_json': new_roads_json
})
My template when the form is valid:
{% extends "geoloc/geoloc_base.html" %}
{% block content %}
{% load leaflet_tags %}
{% leaflet_js %}
{% leaflet_css %}
<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>
var geojsonFeature = ["{{ new_roads_json }}"];
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'}).addTo(mymap);
var myroads = L.geoJSON().addTo(mymap);
myroads.addData(geojsonFeature);
</script>
{% endblock %}
And my models.py:
from django.contrib.gis.db import models
class Transport(models.Model):
gid = models.AutoField(primary_key=True)
aa = models.SmallIntegerField(blank=True, null=True)
name = models.CharField(max_length=100, blank=True, null=True)
geom = models.MultiLineStringField(srid=2100, blank=True, null=True)
objects = models.GeoManager()
class Meta:
managed = False
db_table = 'transport'
def __str__(self):
return self.name
def __unicode__(self):
return self.name or u''
When I send the data while geojson content is valid, nothing is displayed on the leaflet map. Also, no errors in browser's developer tools / firebug or in my django development server. To test if geojson object that serializer creates is valid, I sended the data as a text with:
document.getElementById("id").innerHTML = geojsonFeature
That geojson text, I posted in http://geojsonlint.com/ and the geometry was displayed on the map with no errors.
Any suggestions ?