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="bubbleChart"></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
}
//データの整形
function formatWeather(weathers, keys){
let dataset = [];
let count = 0;
const colors = ['red', 'blue', 'green', 'yellow', 'black'];
for (const weather of weathers) {
const location = keys[count]
//データから週間予報を取得
const weeklyWeather = weather[1].timeSeries[0].areas[0];
const rainProps = weeklyWeather.pops;
const temps = weather[1].timeSeries[1].areas[0];
const tempsMins = temps.tempsMin;
const tempsMaxs = temps.tempsMax;
const data = {
data:[{
x:Number(tempsMins[1]),
y:Number(rainProps[1]),
r:Number(tempsMaxs[1])
//降水確率は0%になりやすいので最高気温を半径にしている
}],
backgroundColor:colors[count],
label: [location]
};
dataset.push(data);
//バブルチャートのデータは{ x: 0, y: 0, r:0 }, ...のような配列である必要がある
count++
}
return dataset
}
//ここがグラフの設定
function chartMaker (dataset) {
// 棒グラフの設定
let bubbleCtx = document.getElementById("bubbleChart");
let bubbleConfig = {
type: 'bubble',
data: {
datasets:dataset
}
};
let bubbleChart = new Chart(bubbleCtx, bubbleConfig);
}
async function fn(areaCodes) {
let codes = [];
let keys = [];
for (var key in areaCodes) {
keys.push(key);
codes.push(areaCodes[key]);
}
const weathers = await getData(codes);
const dataset = formatWeather(weathers, keys);
chartMaker (dataset);
}
fn(areaCodes);