skip to Main Content

I want to extract the longitude and latitude coordinates of each restaurant:

<div id="map" style="height: 400px;"></div>
<script>
    var map = L.map('map').setView([37.7749, -122.4194], 12);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
        maxZoom: 18,
    }).addTo(map);

    let temp = '{{ output_info }}'; 
    console.log(temp);

    for (var i = 0; i < temp.length; i++) {
        var restaurant = temp[i];
        console.log(restaurant);
        var marker = L.marker([restaurant['latitude'], restaurant['longitude']]).addTo(map);
        marker.bindPopup("<b>" + restaurant['name'] + "</b><br>" + restaurant['address'] + "<br>" + restaurant['city'] + ", " + restaurant['state'] + " " + restaurant['postal_code']).openPopup();

        if (i === 0) {
            map.flyTo([restaurant['latitude'], restaurant['longitude']], 16);
        }
    }
</script>

in my results.html console:

[{‘name’: "McDonald’s", ‘latitude’: ‘27.8931987958’, ‘longitude’: ‘-82.3198442906’}, {‘name’: ‘Cafe Baladi’, ‘latitude’: ‘40.041639063’, ‘longitude’: ‘-75.5428394303’}, {‘name’: ‘Chick-fil-A’, ‘latitude’: ‘38.599651’, ‘longitude’: ‘-90.446909’}]

main:25 [

Why is console.log(restaurant) giving me [ and not the first dictionary?

i looked at my app.py and util.py files to see if im passing anything in wrong and it seems alright (based on what im seeing in the console). so honestly not sure what’s really happening? i just want to get the coordinates for every restaurant so i can plop them on a map

2

Answers


  1. Use the jinja filter tojson to make the list javascript compatible.

    let temp = {{ output_info | tojson }}; 
    console.log(temp);
    
    Login or Signup to reply.
  2. I think that’s because, temp variable is a string actually not an array, you can make sure by doing this:

    console.log(typeof temp); // string 
    

    so you need to extract the array from the string, you can do it quickly with eval() but it’s not recommended because it’s dangerous. Executing JavaScript from a string is an BIG security risk, so you need to parse it like this:

    let oldTemp = '{{ output_info }}';
    let temp = JSON.parse(data.replaceAll("'", '"').replace('"s', "'s"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search