john
john

Reputation: 189

Refreshing leaflet map in django

I have the following view:

class IndexView(generic.TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)

        states = models.State.objects.all()
        geojson = json.loads(GeoJSONSerializer().serialize(queryset=states)
        context['states'] = geojson

        return context

    def post(self, request, *args, **kwargs):
        states = models.State.objects.all()
        geojson = json.loads(GeoJSONSerializer().serialize(queryset=states)

        return JsonResponse(geojson)

template:

  <body>

    <style>
        #gs_map {
            height: 800px;
            width: 1200px;
            //.leaflet-container { height: 100%; }
        }

    </style>

    <script type='text/javascript'>
        function map_init (map, options, possible)
        {
            map.setView([38.255874, -85.758552], 3);

            geojson = L.geoJson( {{ states|safe }}, {style: style, onEachFeature: onEachFeature } ).addTo(map)

            function get_states()
            {
              $.ajax({url: '/',
                      type: 'POST',
                      data: {codes: states},
                      datatype: 'json',
                      beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{csrf_token}}")},
                      success: function(response)
                      {
                          /* TODO
                          How do I refresh the map here?*/

                      },
                      complete: function(){},
                      error: function(xhr, textStatus, thrownError){}})
            }

            states = ['CO']
            document.getElementById('test').onclick = get_states;
        }
    </script>

    {% leaflet_map "gs_map" callback='window.map_init' %}

    <button type='submit' value='Test button' id='test'> Click Me </button>


  </body>

I would like to refresh the existing (or replace) leaflet map data. I want the user to be able to click a button and get the latest data from the server. The ajax call works and I am able to print the data to the console, but I do not know how to actually refresh the leaflet code since the map_init function is using the states|safe context data.

How do I replace the leaflet data with my new ajax json data?

Relevant info:

django-leaflet docs

SO leaflet only refresh without AJAX

Interactive Map I am trying to replicate but with refreshing

Upvotes: 1

Views: 1305

Answers (1)

Zathras
Zathras

Reputation: 434

A Leaflet GeoJSON layer is only a FeatureGroup that has the added functionality of being able to convert GeoJSON data into different types of objects like markers, circles or polygons. It is in practice (after you have added your data) just a FeatureGroup (consisting of several different features/layers).

Leaflet doesn't provide functionality for replacing all features in a FeatureGroup. You can however remove all features using the clearLayers function. GeoJSON layers support adding new GeoJSON data to the layer using the addData function.

If you call both of those functions within your jQuery ajax success function you should be able to replace the data (NOTE: untested):

success: function(response)
{
    // Remove all current features from the  
    geojson.clearLayers();
    // Create new layers from your new geoJSON data
    geojson.addData(response); 
},

Upvotes: 2

Related Questions