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:
SO leaflet only refresh without AJAX
Interactive Map I am trying to replicate but with refreshing