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?
HTML:
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Airbus Max</title>
<link rel="stylesheet" href="includes/css/style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Hind:wght@300;400;500;600;700&family=PT+Sans+Narrow:wght@400;700&family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
</head>
<body>
<header>
<h1>Info-vols : Le site de l'info des vols !</h1>
<h2>Besoin d'informations au sujet d'un vol? Vous êtes au bon endroit!</h2>
</header>
<main>
<div id="flex-content">
<div id="pretty-line">
</div>
<div id="tableau-des-vols-container">
<div id="tableau-des-vols">
<div id="flex-display">
<div id="liste-vols-container">
<h2>Liste des vols</h2>
<div id="formulaire">
<form>
<label>Chercher par numéro de vol: </label><input>
</form>
</div>
<table id="tableau">
<thead>
<tr>
<th id="num">Numéro de vol</th>
<th id="lat">Provenance</th>
<th id="long">Ville de départ</th>
<th id="meteo"></th>
</tr>
</thead>
<tbody id="body">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div id="meteo">
<h2 class="titre-meteo">Météo du vol sélectionné</h2>
<div class="bloc-logo-info">
<div class="bloc-logo">
<img src="./ressources/jour/04d.svg" alt="logo du temps qu'il fait" class="logo-meteo">
</div>
<div class="bloc-info">
<p class="temps"></p>
<p class="temperature"></p>
<p class="localisation"></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<footer>
</footer>
<script type="module" src="includes/scripts/main.js"></script>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCOK0Q1fbQOWFCuumTw9uc3G05WKFD9zdY"></script>
</body>
</html>
Javascript:
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);
}
*/