4

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: '&copy; <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 ?

5

Finally I managed to solve the issue. The problem came from the following line:

var geojsonFeature = ["{{ new_roads_json }}"];

I put the square brackets because without them it raised invalid objects errors. Thus, I thought that it was the right syntax. Finally, I figured out that the real problem was that the system translated the quotation " as &quot. So, I added the 'safe' Django filter. The second problem was that it doesn't need quotation and square brackets. So I converted the above line to:

var geojsonFeature = {{ new_roads_json|safe }};

And the problem solved. Two very useful links that helped me to solve the issue: https://stackoverflow.com/questions/298772/django-template-variables-and-javascript https://docs.djangoproject.com/en/1.11/ref/templates/builtins/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.