I’m working on university project, in this part I’m trying to show in graph with bars the origin of electricity production of a country after clicking in a country from the map but my graph is always empty
PS: there is no problem with the apis
let map, view;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 48.864, lng: 2.349 },
zoom: 8,
});
map.addListener('click', (event) => {
const clickedLocation = event.latLng;
const latitude = clickedLocation.lat();
const longitude = clickedLocation.lng();
fetchCountryName(latitude, longitude)
.then(countryName => {
fetchPowerBreakdown(latitude, longitude, countryName)
.then((data) => {
console.log('Données de production d'électricité pour l'endroit cliqué :', data);
updatePowerBreakdownChart(data);
})
.catch((error) => {
console.error('Erreur lors de la récupération des données de production d'électricité :', error);
// Affichez une erreur à l'utilisateur si nécessaire
});
})
.catch((error) => {
console.error('Erreur lors de la récupération du nom du pays :', error);
// Affichez une erreur à l'utilisateur si nécessaire
});
});
}
function loadGoogleMapsScript() {
const script = document.createElement("script");
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyDp3lN5JZUagNgu8cavU5S9rflGRS31iLI&callback=initMap";
script.defer = true;
document.body.appendChild(script);
}
loadGoogleMapsScript();
// Spécification Vega-Lite initiale
const spec = {
$schema: 'https://vega.github.io/schema/vega-lite/v5.json',
data: { name: 'powerData' },
mark: 'bar',
encoding: {
x: { field: 'source', type: 'nominal', title: 'Source d'électricité' },
y: { field: 'value', type: 'quantitative', title: 'Production (MW)' }
},
width: "container",
height: 600,
autosize: {
type: 'fit',
contains: 'padding'
}
};
// Initialiser le graphique Vega-Lite avec la spécification vide
vegaEmbed('#powerBreakdownChart', spec).then(result => {
view = result.view;
}).catch(error => {
console.error('Erreur lors de l'intégration du graphique Vega-Lite :', error);
});
function fetchCountryName(latitude, longitude) {
const apiKey = 'AIzaSyDp3lN5JZUagNgu8cavU5S9rflGRS31iLI';
const apiUrl = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${apiKey}`;
return fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error('Erreur lors de la récupération du nom du pays');
}
return response.json();
})
.then(data => {
const results = data.results;
if (results.length > 0) {
const countryComponent = results.find(component => component.types.includes('country'));
return countryComponent ? countryComponent.formatted_address : 'Unknown Location';
}
return 'Unknown Location';
})
.catch(error => {
console.error('Erreur lors de la récupération du nom du pays :', error);
return 'Unknown Location';
});
}
function fetchPowerBreakdown(latitude, longitude, countryName) {
const authToken = 'sobUgIs9qEzLO';
const apiUrl = `https://api.electricitymap.org/v3/power-breakdown/latest?lat=${latitude}&lon=${longitude}`;
const headers = {
'auth-token': authToken
};
return fetch(apiUrl, { headers })
.then(response => {
if (!response.ok) {
throw new Error('Erreur lors de la récupération des données de production d'électricité');
}
return response.json();
})
.then(data => {
if (!data.powerProductionBreakdown) {
throw new Error('Aucune donnée de production d'électricité disponible pour cet endroit');
}
const breakdown = data.powerProductionBreakdown;
const chartData = Object.keys(breakdown).map(source => ({
source,
value: breakdown[source] || 0
}));
return chartData;
})
.catch(error => {
console.error('Erreur lors de la récupération des données de production d'électricité :', error);
return [];
});
}
function updatePowerBreakdownChart(data) {
// Mettre à jour les données du graphique Vega-Lite avec les nouvelles données
if (view) {
view.change('powerData', vega.changeset().remove(() => true).insert(data)).run();
} else {
console.error('La vue Vega-Lite n'est pas encore prête');
}
}
Can anyone help me to fix this problem cause I don’t have any idea where the problem is.