1

I'm trying to pass in a list from a database from Flask, into Javascript to make Google Maps api markers. For example, from Flask, I'm passing to home.html a list of cars and their longitude and latitude. I then want to loop over this list, and create a google map marker for each location and put it on the map.

function placeCars() {
        {% for cars in car_locations %}
        var position = {
            lat: cars.Location.Latitude,
            lng: cars.Location.Longitude
        };
        new google.maps.Marker({
        position: position,
        map: map
      });
        {% endfor %}
    }

2 Answers 2

0

Use this

{{cars.Location.longitude}}

You should wrap it in {{ }}

Sign up to request clarification or add additional context in comments.

Comments

0

I think the problem you're encountering is flask will create a function in the html that looks like this:

function placeCars() {
  var position = {
      lat: 123,
      lng: 456
  };
  new google.maps.Marker({
      position: position,
      map: map
  });
  var position = {
      lat: 789,
      lng: 123
  };
  new google.maps.Marker({
      position: position,
      map: map
  });
}

Then you would need another piece of javascript to execute that function call

Try changing your javascript to something like this

  // Load the data from Flask
  var carLocations = JSON.parse('{{ car_locations | tojson | safe }}');

  // When the page has loaded iterate through your list using javascript
  // and pass the values to your function 
  (function() {
    carLocations.forEach(car => placeCars(car));
  })();

  function placeCars(nextPosition) {
    var position = {
      lat: nextPosition.Location.Latitude,
      lng: nextPosition.Location.Longitude
    };
    new google.maps.Marker({
      position: position,
      map: map
    });
  }

See this answer for passing json data to your template: Passing a JSON object from Flask to JavaScript

1 Comment

This looked like it would work, thanks. Just getting an error "TypeError: Object of type CarLocations is not JSON serializable", will do a bit of investigating

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.