Django FOR LOOP in JavaScript

First of all, I am new to programming. I'm trying to create a webpage on which you have a Google map embedded, and on this map you see a colored line that sets the path. For this I use Django. In my views.py, I have a variable called dots, where I have some coordinates recorded in the list as a string. For instance,

points = ('-15.4566620,28.07163320','15.7566620,29.07163320',....) 

Then on google script maps I have:

var flightPlanCoordinates = [

  new google.maps.LatLng(-15.4566620,28.07163320), new google.maps.LatLng(-15.7566620,29.07163320), ]; 

So, when I show my page, I see a line between these points.

I would like to have instead something like:

var flightPlanCoordinates = [

  {% for point in points %} new google.maps.LatLng({{point}}), {% endfor %} ]; 

But that does not work.

What am I doing wrong, and how should it be?

Thank you very much.

+4
source share
2 answers

The goal is to make the template render the array of paths just as if it were hard-coded. You must check the source code of the provided web page.

It is best to remove this trailing comma, even if it works with it. You can use forloop.last to omit it at the last point.

I follow the style as in the polls textbook. Make sure the view sends the points variable to the template:

urls.py

urlpatterns contains url(r'^map/$', 'polls.views.map'),

views.py

 def map(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 %} ] }) 
+4
source

Your point array is an array of strings '-15.4566620,28.07163320'. So you do this: new google.maps.LatLng ({{'- 15.4566620,28.07163320'}}),

The google.maps.LatLng constructor accepts two numbers, so you need to parse the numbers from this line (or pass the numbers to the LatLng constructor).

Edit: one way to do this is to populate an array like this (not tested):

 var polylineArray = []; for (var i = 0; i < points.length; i++) { // split the string at the comma var 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]))); } 
0
source

All Articles