javascript - 在 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 数据替换传单数据?
相关资料:
解决方案
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);
},
推荐阅读
- android - 如何使用回收站视图进行自定义抽屉布局?
- java - 异步批量插入/更新表。Spring MVC,Java 8(或更高版本,Java 12)
- php - wordpress max_user_connections 错误脚本优化
- django - 在 Django Graphene 中创建或更新更新多对多关系
- python-2.7 - TypeError:lowerb 不是 numpy 数组,也不是标量
- sql-server - 将值存储在我的数据库中的表中,并在数据网格中显示结果
- django - 如何运行我的 django 项目之外的 Object_detection_image.py?
- r - 来自 bookdown 的 render_book() 的 enc2utf8 问题
- amazon-web-services - Nodejs AWS Textract 不适用于 lambda
- python - 将天数添加到 PySpark Dataframe 中的数组内的元素