2

I have to display my geometry data in my Leaflet based web map and I use GeoDjango to display it, I have loaded GeoJSON data and front map but I can't put my geometry data on my web map.

How can we solve it?

views.py:

from django.shortcuts import render
from django.views.generic import TemplateView
from django.core.serializers import serialize
from django.http import HttpResponse
from .models import jobs


class hompage(TemplateView):
    template_name='index.html'

def job_details(request):
    job=serialize('geojson',jobs.objects.all())
    return HttpResponse(job,content_type='json')

urls.py:

from django.conf.urls import include,url
from .views import hompage,job_details


urlpatterns=[
    url(r'^$',hompage.as_view(),name='home'),
    url(r'^work/$',job_details,name='works'),
    ]

Template.html:

<!DOCTYPE html>
<html>
{% load static %}
{% load leaflet_tags %}
<head>
{%leaflet_js%}
{%leaflet_css%}
    <title>HARISOHMNAATH</title>
    <style type="text/css">
        #gis{widht:80%;height:700px;}
</style>
<script type="text/javascript" src={% static 'dist/leaflet.ajax.js'%}>
</script>
<body>
<h1>harisohmnaath</h2>
<br>
<script type="text/javascript">
      function out_layers(map,options){
          var datasets = new L.GeoJSON.AJAX("{% url 'works' %}",{
           onEachFeature:function(feature, layer){
                 layer.bindPopup(feature.properties.name.toString());
}
});
          datasets.addTo(map);
}
</script>
{%leaflet_map "gis" callback="window.our_layers" %}

</body>
</html>
3
  • Please paste above any errors seen on the developer tools console. Try replacing content_type='json' with content_type='application/json'. What do you get when browsing to /work?
    – Udi
    Commented Dec 30, 2017 at 20:08
  • I'm getting my geojson data when i use 127.0.0.1:8000/work and getting my leaflet map when 127.0.0.1:8000 but I cant overlap both both the data Commented Dec 31, 2017 at 13:56
  • Did you fix the content type?
    – Udi
    Commented Dec 31, 2017 at 14:59

2 Answers 2

2

I struggled for awhile with your approach until I discovered these two packages: django-leaflet and django-geojson.

It's maintained and the docs and demos are great.

2

I have a solution. You can load the geojson files using jquery. for this you have to add jquery in your program; i.e.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

And replace your code by:

$.getJSON("{% url 'work' %}", function(data){
   var geojson = L.geoJson(data, {
   onEachFeature: function(feature, layer) {
       layer.bindPopup('pop-up content');
   }
});
geojson.addTo(map);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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