djangoleafletgeojsongeodjango

Invalid object when adding geoJSON data on a Leaflet map with Django serializer


I'm developing a Django application using Leaflet and Postgresql / PostGIS. When I'm trying to add a MultiLineString layer on a map sending a GeoJSON Feature Collection object, it raises an invalid object error. At first my views.py:

from geonode.geoloc.models import Transport
from django.template import RequestContext
from django.core.serializers import serialize

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',))

    # Render the template
    return self.render_to_response({
                              'roads_json': roads_json
                             }, content_type = '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 = "{{ 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 %}

When I tested the geoJSON object (that Django serializer sends) in http://geojsonlint.com/, I realized that the object is invalid because of the following lines:

 "crs": {
"type": "name",
"properties": {
  "name": "EPSG:4326"
}

which as I read is "an old-style crs member and is not recommended". Have I to customize the output of serializer in order not to extract the above lines or there is a more efficient way to succeed that ?


Solution

  • I solved the above issue following the following steps:

    The modified code in views.py:

    roads =  Transport.objects.all()[0:5]
    
    roads_json = serialize('geojson', roads,
               fields=('geom',))
    
    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
                          }, content_type = 'json')