Reputation: 71
I'm using Python 3.4, latest Django with the leaflet django install. I'm able to display the map, and add 1 marker from my list.
The problem is adding all of the markers in the list. The code renders all of the markers but not all of them get added to the map. Maybe I'm losing the map reference via a scope issue? I'm not sure. Here is my code, I really could use the help.
{% load leaflet_tags %}
<head>
{% leaflet_js %}
{% leaflet_css %}
</head>
<body>
{% if latest_device_list %}
<script type="text/javascript">
{% for device in latest_device_list %}
function map_init_basic (map, options) {
marker = new L.marker([{{device.Device_Lat}}, {{device.Device_Lon}}])
.bindPopup("<h3>"+{{device.Device_IMEI}}+"</h3>")
.addTo(map);
}
{% endfor %}
</script>
{% else %}
<p>No Devices are available.</p>
{% endif %}
{% leaflet_map "yourmap" callback="window.map_init_basic" %}
</body>
Upvotes: 1
Views: 1729
Reputation: 28638
I'm really unfamiliar with django, so i could be wrong but doesn't your for
loop insert multiple map_init_basic
methods/callbacks? So you declaring the same callback function over and over? And only one will execute on map initialization. My guess is that you should put the for
loop in the callback function around the marker declaration:
<script type="text/javascript">
function map_init_basic (map, options) {
{% for device in latest_device_list %}
marker = new L.marker([{{device.Device_Lat}}, {{device.Device_Lon}}])
.bindPopup("<h3>"+{{device.Device_IMEI}}+"</h3>")
.addTo(map);
{% endfor %}
}
</script>
What's happening now is that when you have say three markers in your device list, it would end up like this:
<script type="text/javascript">
function map_init_basic (map, options) {
marker = new L.marker([0, 0])
.bindPopup("<h3>"+ 'ABC' +"</h3>")
.addTo(map);
}
function map_init_basic (map, options) {
marker = new L.marker([1, 1])
.bindPopup("<h3>"+ 'DEF' +"</h3>")
.addTo(map);
}
function map_init_basic (map, options) {
marker = new L.marker([2, 2])
.bindPopup("<h3>"+ 'GHI' +"</h3>")
.addTo(map);
}
</script>
The second function declaration, will overwrite the first, and the third will overwrite the second. So when map_init_basic
gets called only the third function will execute.
Upvotes: 2
Reputation: 71
Corrected code:
{% if latest_device_list %}
<script type="text/javascript">
function map_init_basic (map, options) {
var marker = null;
map.setView([51.505, -0.09], 13);
{% for device in latest_device_list %}
marker = new L.marker([{{device.Device_Lat}}, {{device.Device_Lon}}])
.bindPopup("<h3>"+{{device.Device_IMEI}}+"</h3>")
.addTo(map);
{% endfor %}
}
</script>
{% else %}
<p>No Devices are available.</p>
{% endif %}
{% leaflet_map "yourmap" callback="window.map_init_basic" %}
</body>
Upvotes: 0