-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyChart.js
70 lines (59 loc) · 2.47 KB
/
myChart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var currentChart;
document.getElementById('renderBtn').addEventListener('click', fetchData);
async function fetchData() {
var countryCode = document.getElementById('country').value;
const indicatorCode = 'SP.POP.TOTL';
const baseUrl = 'https://api.worldbank.org/v2/country/';
const url = baseUrl + countryCode + '/indicator/' + indicatorCode + '?format=json';
console.log('Fetching data from URL: ' + url);
var response = await fetch(url);
if (response.status == 200) {
var fetchedData = await response.json();
console.log(fetchedData);
var data = getValues(fetchedData);
var labels = getLabels(fetchedData);
var countryName = getCountryName(fetchedData);
renderChart(data, labels, countryName);
}
}
function getValues(data) {
var vals = data[1].sort((a, b) => a.date - b.date).map(item => item.value);
return vals;
}
function getLabels(data) {
var labels = data[1].sort((a, b) => a.date - b.date).map(item => item.date);
return labels;
}
function getCountryName(data) {
var countryName = data[1][0].country.value;
return countryName;
}
function renderChart(data, labels, countryName) {
var ctx = document.getElementById('myChart').getContext('2d');
if (currentChart) {
// Clear the previous chart if it exists
currentChart.destroy();
}
// Draw new chart
currentChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Population, ' + countryName,
data: data,
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}