gpt4 book ai didi

javascript - django中刷新传单 map

转载 作者:行者123 更新时间:2023-12-03 01:17:03 25 4
gpt4 key购买 nike

我有以下观点:

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>

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

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

相关信息:

django-leaflet docs

SO leaflet only refresh without AJAX

Interactive Map I am trying to replicate but with refreshing

最佳答案

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

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

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

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

关于javascript - django中刷新传单 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51957928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com