uni-app使用高德天气api
时间: 2023-12-23 18:03:53 浏览: 206
1. 首先在高德开放平台上申请天气API的key。具体步骤可参考高德开放平台的官方文档。
2. 在uni-app项目中安装axios插件,用于发送http请求。
3. 在uni-app项目中创建一个api.js文件,用于封装调用高德天气API的逻辑。
4. 在api.js文件中编写以下代码:
```
import axios from 'axios';
const key = 'your_amap_weather_api_key'; // 替换为你的高德天气API key
const apiUrl = 'https://restapi.amap.com/v3/weather/weatherInfo';
export function getWeatherInfo(city) {
return axios.get(apiUrl, {
params: {
key,
city,
extensions: 'base',
output: 'json'
}
}).then(res => {
if (res.data.status === '1') {
return res.data.lives[0];
} else {
throw new Error(res.data.info);
}
});
}
```
5. 在需要使用天气信息的页面中引入api.js文件,并调用getWeatherInfo方法获取天气信息。
```
import { getWeatherInfo } from '@/api.js';
export default {
data() {
return {
city: '北京', // 默认城市
weather: null // 天气信息
}
},
methods: {
getWeather() {
getWeatherInfo(this.city).then(weather => {
this.weather = weather;
}).catch(error => {
console.error(error);
});
}
},
mounted() {
this.getWeather();
}
};
```
6. 在页面中展示天气信息。
```
<template>
<div>
<div>{{ city }}当前天气:{{ weather.weather }},温度:{{ weather.temperature }}℃</div>
</div>
</template>
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)