Django For Loop In Javascript
Solution 1:
The objective is to get the template to render the path array the same as if it were hardcoded. You should check the rendered webpage's source code to be sure.
It's best to remove that trailing comma, even if it does work with it. You can use the forloop.last
to omit it in the last point.
I'm following a style as in the polls tutorial. Make sure the view is sending the points
variable to the template:
urls.py
urlpatterns
contains url(r'^map/$', 'polls.views.map'),
views.py
defmap(request):
points = ('0,0', '10,0', '10,10', '0,10')
return render_to_response('polls/map.html', { 'points': points })
template map.html
...
var mypolyline = new google.maps.Polyline({
map: map,
path: [
{% for point in points %}
new google.maps.LatLng({{ point }}) {% if not forloop.last %},{% endif %}
{% endfor %}
]
})
Solution 2:
Your points array is an array of strings of the form '-15.4566620,28.07163320'. So you are doing this: new google.maps.LatLng({{'-15.4566620,28.07163320'}}),
The google.maps.LatLng constructor takes two numbers, so you need to parse the numbers out of that string (or pass in numbers to the LatLng constructor).
Edit: One way to do it would be to populate the array like this (not tested):
var polylineArray = [];
for (var i = 0; i < points.length; i++)
{
// split the string at the commavar coords = points[i].split(",");
// change the two strings to floating point numbers, use them to create the LatLng
polylineArray.push(new google.maps.LatLng(parseFloat(coords[0]),
parseFloat(coords[1])));
}
Post a Comment for "Django For Loop In Javascript"