addeventListener not working on all elements

Hello I mam facing a problem with my script.

I am beginner in JS and I am trying to add event listener to buttons generated by a foreach but only the last button generated is responding to the addeventlistener.

I am also facing a pb of variable range with the getLocation(flight) function which is returning undefined outside the fuction while the console.log in the function is displaying the good variable value.

Can someone help?



let resultatAPIMeteo;

let long;
let lat;
let buttonId;

const URL = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
const TITREMETEO = document.querySelector('.titre-meteo');
const IMG = document.querySelector('.bloc-logo');
const temps = document.querySelector('.temps');
const temperature = document.querySelector('.temperature');
const localisation = document.querySelector('.localisation');
const tbody = document.querySelector(('#body'));

let flights = [];
let table = document.getElementById("tableau");

AppelAPI();

function AppelAPI() {
    fetch(URL)
        .then((response) => {
            return response.json()
        })
        .then((data) => {
            let i = 0;

            getFlights(data);
            console.log(data)
            console.log(flights)

            flights.forEach(flight => {
                let i = flights.indexOf(flight)
                console.log(flight);
                long = flight[5];
                lat = flight[6];

                let city = getLocation(flight);
                console.log("city: " + city);

                let meteoDepart = "test";
                let meteoArrivee = "test";

                /* let newRow = document.createElement('tr');
                let newFlightNumber = document.createElement('td');
                let newflightNumberText = flight[1];
                let newProvenance = document.createElement('td');
                let newProvenanceText = flight[2];
                let newCity = document.createElement('td');
                let newCityText = city;


                tbody.append(newRow);

                newFlightNumber.textContent = newflightNumberText;
                newRow.append(newFlightNumber);

                newProvenance.textContent = newProvenanceText;
                newRow.append(newProvenance);

                newCity.textContent = newCityText;
                newRow.append(newCity); */
                

                if(i % 2 === 0) {
                    table.innerHTML += `<tr class='pair'>n` +
                        "    <td>" + flight[1] + "</td>n" +
                        "    <td>" + flight[2] + "</td>n" +
                        `    <td>${city}</td>n` +
                        `    <td><button id="tr-${i}"  onclick="alert('Bouton cliqué')">Météo</button></td>`+
                        "</tr>n";
                } else {
                    table.innerHTML += `<tr class='pair'>n` +
                        "    <td>" + flight[1] + "</td>n" +
                        "    <td>" + flight[2] + "</td>n" +
                        `    <td>${city}</td>n` +
                        `    <td><button id="tr-${i}"  onclick="alert('Bouton cliqué')">Météo</button></td>`+
                        "</tr>n";
                }
                console.log('tr-'+i);
                let button = document.getElementById('tr-'+i);
                tbody.style.color='white';
                button.style.backgroundColor='orange';

                button.addEventListener('click', (e) => {
                    console.log('from api: click');
                    AppelApiMeteo(flight);
                });
                i++;
            })
        })
}

function AppelApiMeteo(flight) {
    console.log('from apimeteo: click');

    let lattitude = flight[6];
    let longitude = flight[5];
    let URLMeteo = `https://api.openweathermap.org/data/2.5/onecall?lat=${lattitude}&lon=${longitude}&exclude=minutely&units=metric&lang=fr&appid=${CLEAPIMETEO}`;
    console.log(URLMeteo);
    fetch(URLMeteo)
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            resultatAPIMeteo = data;

            TITREMETEO.innerHTML = `Météo du vol ${flight[1]} en provenance de ${flight[2]}`;
            IMG.innerHTML = `<img src="./ressources/jour/${resultatAPIMeteo.current.weather[0].icon}.svg" alt="logo du temps qu'il fait" className="logo-meteo">`;
            temps.innerText = resultatAPIMeteo.current.weather[0].description;
            temperature.innerText = `${Math.trunc(resultatAPIMeteo.current.temp)}°`;
            localisation.innerText = resultatAPIMeteo.timezone;

            console.log('meteo data:' + resultatAPIMeteo.current.weather[0].description);
        })
}

function getFlights(data) {
    console.log(data.states);
    data.states.forEach(element =>{
        flights.push(element)
    })
}

function getLocation(flight){
    let lattitude = flight[6];
    let longitude = flight[5];
    let geocoder;
    geocoder = new google.maps.Geocoder();
    let latlng = {
        lat: parseFloat(lattitude),
        lng: parseFloat(longitude),
    };

    geocoder
        .geocode({location: latlng})
        .then((response) => {
            console.log("pos: " + response.results[7].address_components[0].long_name);
            return response.results[7].address_components[0].long_name;
        })
        .catch((e) => window.alert("Geocoder failed due to: " + e));
}
/*
let row = document.createElement('tr')
let columnNum = document.createElement('th');
let columnLat = document.createElement('th');
let columnLong = document.createElement('th');
let columnMeteo = document.createElement('th')

for(let i = 0; i < data.length; i++) {

    columnNum.textContent = resultatsAPI[i].icao24;

    table.appendChild(row);
    row.appendChild(columnNum);
    row.appendChild(columnLat);
    row.appendChild(columnLong);
    row.appendChild(columnMeteo);


    console.log('test:' + resultatsAPI[i].icao24);
}
*/