我尝试从天气 API 获取数据,但有些东西不起作用。
如果我正确理解了说明(https://openweathermap.org/current),我首先需要坐标,我已将其保存在变量中。但是,当我尝试使用坐标查找天气时,控制台中出现以下错误: 错误请求 400。
纬度“lon”和 lat 设置为未定义:
https://api.openweathermap.org/data/2.5/weather?lat=undefined&lon=undefined&appid=MyKey
(MyKey 是一个占位符,因为我不想让任何人知道我的真实密钥)
这是我的JS代码:
"use strict";
let API_KEY = "myKey";
let LINK_API = "http://api.openweathermap.org/geo/1.0/direct?q=berlin";
let NEW_API_LINK = "https://api.openweathermap.org/data/2.5/weather";
let lat;
let lon;
let fetchFunc = async function () {
let fetch_begin_for_LINK_API= await fetch(LINK_API+"&appid="+API_KEY);
let data_for_LINK_API = fetch_begin_for_LINK_API.json();
data_for_LINK_API.then(result => {
lat = result[0].lat;
lon = result[0].lon;
});
let fetch_begin_for_NEW_API_LINK = await fetch(NEW_API_LINK+"?lat="+
lat+"&lon="+lon+
"&appid="+API_KEY);
let data_for_NEW_API_LINK = fetch_begin_for_NEW_API_LINK.json();
console.log(data_for_NEW_API_LINK);
}
fetchFunc();
以下是如何获取城市(即英国伦敦)的纬度和经度。您可以使用它们来获取天气预报值,如下所示。我制作的这段代码只是替换您的 API 密钥以查看值
const weathercoordinateBtn = document.getElementById('weather_coordinate_btn')
const weatherForecastBtn2 = document.getElementById('weather_forecast_btn')
async function forecastweatherFetchgetLatLon(){
let apiKey = "yourAPI"
const url = `http://api.openweathermap.org/geo/1.0/direct?q=London&limit=5&appid=${apiKey}`
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
try {
const response = await fetch(`${url}`, options);
const result = await response.json();
let lattitude = result[1].lat
let longitude = result[1].lon
console.log(result)
console.log({lattitude})
console.log({longitude})
} catch (error) {
console.error(error);
}
}
async function weatherFetch(){
const url = `https://api.openweathermap.org/data/2.5/weather`
let apiKey = "YourAPI"
let lattitude = 51.5156177
let longitude = -0.0919983
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
try {
const response = await fetch(`${url}?lat=${lattitude}&lon=${longitude}&appid=${apiKey}&units=metric`, options);
const result = await response.json();
console.log(result)
let description = result.weather[0].description
let icon = result.weather[0].icon
let Temperature = Math.floor(result.main.temp)
console.log({description})
console.log({icon})
console.log({Temperature})
} catch (error) {
console.error(error);
}
}
weathercoordinateBtn.addEventListener('click',forecastweatherFetchgetLatLon)
weatherForecastBtn2.addEventListener('click',weatherFetch)
<div class="div1"><div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div6"></div>
<button id="weather_coordinate_btn">getcoordinate</button>
<button id="weather_forecast_btn">getforecast</button>