36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
import axios from 'axios';
|
|
|
|
interface WeatherData {
|
|
temp: string;
|
|
weather: string;
|
|
city: string;
|
|
}
|
|
|
|
// 使用高德地图 API 获取天气
|
|
export const getWeather = async (): Promise<WeatherData> => {
|
|
try {
|
|
// 先获取 IP 定位
|
|
const ipUrl = 'https://restapi.amap.com/v3/ip';
|
|
const weatherUrl = 'https://restapi.amap.com/v3/weather/weatherInfo';
|
|
const key = '46a02c7d20534596f7386caf02204caa'; // 需要替换成你自己的 key
|
|
|
|
const ipResponse = await axios.get(`${ipUrl}?key=${key}`);
|
|
const {adcode} = ipResponse.data;
|
|
|
|
const weatherResponse = await axios.get(`${weatherUrl}?key=${key}&city=${adcode}`);
|
|
const weatherData = weatherResponse.data.lives[0];
|
|
|
|
return {
|
|
temp: weatherData.temperature,
|
|
weather: weatherData.weather,
|
|
city: weatherData.city
|
|
};
|
|
} catch (error) {
|
|
console.error('获取天气信息失败:', error);
|
|
return {
|
|
temp: '--',
|
|
weather: '未知',
|
|
city: '未知'
|
|
};
|
|
}
|
|
};
|