コンテンツにスキップ

ジオロケーション: 天気アプリケーション

ユーザーのジオロケーションデータを使用してAPIから天気データを取得します。

export default {
async fetch(request) {
let endpoint = "https://api.waqi.info/feed/geo:";
const token = ""; //https://aqicn.org/api/からトークンを使用してください
let html_style = `body{padding:6em; font-family: sans-serif;} h1{color:#f6821f}`;
let html_content = "<h1>天気 🌦</h1>";
const latitude = request.cf.latitude;
const longitude = request.cf.longitude;
endpoint += `${latitude};${longitude}/?token=${token}`;
const init = {
headers: {
"content-type": "application/json;charset=UTF-8",
},
};
const response = await fetch(endpoint, init);
const content = await response.json();
html_content += `<p>これはWorkersのジオロケーションデータを使用したデモです。</p>`;
html_content += `あなたの位置: ${latitude},${longitude}.</p>`;
html_content += `<p><a href="${content.data.city.url}">${content.data.city.name}</a>からのセンサーデータに基づいて:</p>`;
html_content += `<p>AQIレベル: ${content.data.aqi}.</p>`;
html_content += `<p>N02レベル: ${content.data.iaqi.no2?.v}.</p>`;
html_content += `<p>O3レベル: ${content.data.iaqi.o3?.v}.</p>`;
html_content += `<p>温度: ${content.data.iaqi.t?.v}°C.</p>`;
let html = `
<!DOCTYPE html>
<head>
<title>ジオロケーション: 天気</title>
</head>
<body>
<style>${html_style}</style>
<div id="container">
${html_content}
</div>
</body>`;
return new Response(html, {
headers: {
"content-type": "text/html;charset=UTF-8",
},
});
},
};