Incorporating leaflet JS into a Django template, the aim is to display markers on a map where latitude and longitude are sourced from a queryset. Sending the queryset through views and utilizing the Django template language within <script>
tags seemed like a viable approach to assign latitudes and longitudes to specific markers. However, the challenge arises when attempting to include an image in the marker's popup window. Given that JavaScript operates on the client side while Django templates run on the server side, how can this be achieved? Is AJAX the solution?
The current setup in the views:
class MapView(ListView):
template_name = 'map.html'
model = Post
queryset = serialize('json', Post.objects.all(), fields=['lat', 'lon', 'image'])
Below is a snippet from the template showing marker1 with a hardcoded popup which functions correctly:
var map = L.map('map').setView([49.175573, 20.072700], 11);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var post_base = {{object_list|safe}}
for (let index = 0; index < post_base.length; index++) {
console.log(post_base[index]['fields']['lat']);
var image_path = post_base[index]['fields']['images']
marker = new L.marker([post_base[index]["fields"]["lat"], post_base[index]["fields"]["lon"]]).addTo(map)
.bindPopup("<img style=10%; src={% static 'images/????????????????????????'%}/>");
}
marker1 = new L.marker([49.295236, 20.413089], {opacity: 0.5}).addTo(map)
.bindPopup("<img src={% static 'images/lomnica_image.jpeg' %}/>");
</script>
If anyone could provide guidance on the most appropriate method of resolving this issue, it would be greatly appreciated. Thank you