首页 > 解决方案 > 在 django 中刷新传单地图

问题描述

我有以下看法:

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)

模板:

  <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>

我想刷新现有(或替换)传单地图数据。我希望用户能够单击一个按钮并从服务器获取最新数据。ajax 调用有效,我可以将数据打印到控制台,但我不知道如何实际刷新传单代码,因为 map_init 函数正在使用 states|safe 上下文数据。

如何用我的新 ajax json 数据替换传单数据?

相关资料:

django 传单文档

SO传单只刷新没有AJAX

我正在尝试复制但令人耳目一新的交互式地图

标签: javascriptpythonleaflet

解决方案


Leaflet GeoJSON 层只是一个 FeatureGroup,它具有能够将 GeoJSON 数据转换为不同类型的对象(如标记、圆形或多边形)的附加功能。实际上(在您添加数据之后)只是一个 FeatureGroup(由几个不同的特征/层组成)。

Leaflet 不提供替换 FeatureGroup 中所有功能的功能。但是,您可以使用该功能删除所有clearLayers功能。GeoJSON 图层支持使用该addData函数向图层添加新的 GeoJSON 数据。

如果您在 jQuery ajax 成功函数中调用这两个函数,您应该能够替换数据(注意:未经测试):

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

推荐阅读