以下方法介绍了如何使用 Open Weather Map API在 Vanilla JavaScript 中创建天气应用程序。使用这个 API,我们可以获得每个坐标的天气数据。
项目设置:
- 第 1 步:现在转到 https://openweathermap.org/ 并创建一个帐户并获取您的 API 密钥。
- 第二步:之后,您可以创建一个文件夹并添加一个文件,例如 index.html 和 script.js 文件。
- 第 3 步:我们可以使用以下方法获取地理坐标:
- 通过地理坐标-经纬度调用API
api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
- 通过城市ID调用API
api.openweathermap.org/data/2.5/weather?id={city id}&appid={API key}
- 通过地理坐标-经纬度调用API
例子:
index.html
---
-°C
----
script.js
// Declaring the variables
let lon;
let lat;
let temperature = document.querySelector(".temp");
let summary = document.querySelector(".summary");
let loc = document.querySelector(".location");
let icon = document.querySelector(".icon");
const kelvin = 273;
window.addEventListener("load", () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
console.log(position);
lon = position.coords.longitude;
lat = position.coords.latitude;
// API ID
const api = "6d055e39ee237af35ca066f35474e9df";
// API URL
const base =
`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&` +
`lon=${lon}&appid=6d055e39ee237af35ca066f35474e9df`;
// Calling the API
fetch(base)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
temperature.textContent =
Math.floor(data.main.temp - kelvin) + "°C";
summary.textContent = data.weather[0].description;
loc.textContent = data.name + "," + data.sys.country;
let icon1 = data.weather[0].icon;
icon.innerHTML =
``;
});
});
}
});
脚本.js
// Declaring the variables
let lon;
let lat;
let temperature = document.querySelector(".temp");
let summary = document.querySelector(".summary");
let loc = document.querySelector(".location");
let icon = document.querySelector(".icon");
const kelvin = 273;
window.addEventListener("load", () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
console.log(position);
lon = position.coords.longitude;
lat = position.coords.latitude;
// API ID
const api = "6d055e39ee237af35ca066f35474e9df";
// API URL
const base =
`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&` +
`lon=${lon}&appid=6d055e39ee237af35ca066f35474e9df`;
// Calling the API
fetch(base)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
temperature.textContent =
Math.floor(data.main.temp - kelvin) + "°C";
summary.textContent = data.weather[0].description;
loc.textContent = data.name + "," + data.sys.country;
let icon1 = data.weather[0].icon;
icon.innerHTML =
``;
});
});
}
});
输出:
参考: https://openweathermap.org/current