Reputation: 11052
I have a following extra_context
in my views.py.
extra_context = {
'user': list_user,
'time': str(list_time),
'latlng': list_latlng
}
All of the above variables are datatype of python list
. Now i want to use these variable in Gmap v3 javascript. I found a following snippet for google map: (posting the main part)
<script type="text/javascript">
var map ;
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var flightPlanCoordinates = [ {% for ip in latlng %}{{ ip }}{% endfor %}];
for(var i in flightPlanCoordinates){
var marker = add_marker(flightPlanCoordinates[i][0], flightPlanCoordinates[i][1],"Some title!","html for info box");
marker.setMap(map);
}
}
function add_marker(lat,lng,title,box_html) {
var infowindow = new google.maps.InfoWindow({
content: box_html
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
title: title
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
return marker;
}
The above code shows a marker accoriding to the latlng
list passed from the context. But the problem is occurring at that time when i also tried to pass time and user
with the same way. It shows nothing on the Map. By the way i tried with this coide:
var user = [{% for i in user %}{{ i }}{% endfor %}];
var timestamp = [{% for y in time %}{{ y }}{% endfor %}];
Is that the right way? I am new in javascript i wrote according the latlng
code.
I tried with alert(timestamp)
. Nothing happens :(
Another problem is i have to pass these three parameter to add_marker
java script method. TO do this i have to run three for loop concurrently. Posting the pseudo code:
var user = [{% for i in user %}{{ i }}{% endfor %}];
var timestamp = [{% for y in time %}{{ y }}{% endfor %}];
var flightPlanCoordinates = [ {% for ip in latlng %}{{ ip }}{% endfor %}];
for (var in flightPlanCoordinates) and for (a in timestamp) and for(b in user)
{
var marker = add_marker(flightPlanCoordinates[i][0], flightPlanCoordinates[i][1],b,a);
marker.setMap(map);
Upvotes: 3
Views: 3119
Reputation: 819
Use JSON.parse() In your template use e.g.
<script type="text/javascript">
var user = JSON.parse('{{user}}');
</script>
This work fine for me ;)
Upvotes: 0
Reputation: 133929
Use django-jsonify. In your template use e.g.
var user = {{ user|jsonify }};
Like magic.
Upvotes: 2
Reputation: 53336
You need to define your variables as:
var user = [{% for i in user %}{{ i }}{% if forloop.last %} {%else%} , {%endif%} {% endfor %}];
i.e. add comma between the values in array.
Upvotes: 3