JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<canvas id="radarChart"></canvas>
JavaScript
// 気象庁のAPIから天気予報JSONファイルを読み取る
const KYOTO = 260000;
const TOKYO = 130000;
const OSAKA = 270000;
const KANAGAWA = 140000;
const HYOGO = 280000;
const areaCodes= {"京都": KYOTO, "大阪":OSAKA, "兵庫":HYOGO, "東京":TOKYO, "神奈川": KANAGAWA};
//APIからデータを得る関数
async function getData(areaCodes) {
let result = [];
for (const areaCode of areaCodes) {
var url = `https://www.jma.go.jp/bosai/forecast/data/forecast/${areaCode}.json`
var res = await fetch(url);
var weather = await res.json();
result.push(weather);
}
return result
}
// JSONデータ取得後に呼び出す関数
function formatWeather(weathers){
let weatherSummary = {"clear": 0,"cloudy": 0, "rain": 0, "snow": 0};
for (const weather of weathers) {
//データから週間予報を取得
const weeklyWeather = weather[1].timeSeries[0].areas[0];
const weatherCodes = weeklyWeather.weatherCodes;
for (const code of weatherCodes) {
if (Number(code) < 200) {
//100台=晴れ(clear)
weatherSummary.clear += 1;
} else if (Number(code) < 300) {
//200台=曇
weatherSummary.cloudy += 1;
} else if (Number(code) <400) {
//300台=曇
weatherSummary.rain += 1;
} else{
//400台=曇
weatherSummary.snow += 1;
}
}
}
return weatherSummary
}
//ここがグラフの設定
function chartMaker (keys, data) {
// 棒グラフの設定
let radarCtx = document.getElementById("radarChart");
let radarConfig = {
type: 'radar',
data: {
labels: keys, //clearなどのラベル
datasets: [{
data: data,
label:"1週間での回数",
borderColor: "rgba(255,255,0,1)",
fill: true, //グラフの塗りつぶし
lineTension: 0 //曲線の度合い
}]
},
};
let radarChart = new Chart(radarCtx, radarConfig);
}
async function fn(areaCodes) {
let codes = [];
for (var key in areaCodes) {
codes.push(areaCodes[key]);
}
const weathers = await getData(codes);
const data = formatWeather(weathers);
let keys = []; //clearなどのラベル
let weatherCodes = []; //各ラベルの個数
...