御坂主机 发表于 2024-6-19 12:02:08

微信小程序使用百度api获取天气信息

本帖最后由 御坂主机 于 2024-6-20 13:50 编辑

1. 引言

微信小程序已经成为开发移动应用的热门选择,具有轻量、便捷、跨平台的特点。获取天气信息是许多小程序的常见需求,本文将详细介绍如何在微信小程序中使用百度API获取天气信息。通过本文的指导,您将能够快速实现这一功能,为用户提供实时的天气信息。

2. 准备工作

2.1 注册百度开发者账号

首先,需要注册一个百度开发者账号,并创建一个应用以获取API Key。访问百度开发者平台(http://developer.baidu.com),完成注册并登录。

2.2 创建应用并获取API Key

登录后,导航到“控制台”->“我的应用”,点击“创建应用”。填写应用信息并选择“天气服务”API,创建应用后可以在“应用详情”中找到API Key。

3. 微信小程序项目设置

3.1 创建微信小程序项目

在微信开发者工具中创建一个新的小程序项目,并配置基本信息。

3.2 配置小程序权限

在`app.json`文件中配置小程序的网络权限,允许访问外部API。

{
"pages": [
    "pages/index/index"
],
"window": {
    "navigationBarTitleText": "天气预报"
},
"networkTimeout": {
    "request": 10000
},
"permission": {
    "scope.userLocation": {
      "desc": "获取您的位置信息用于天气查询"
    }
}
}

4. 获取用户位置

为了提供准确的天气信息,需要获取用户的地理位置。使用微信小程序的`wx.getLocation` API可以实现这一功能。

4.1 请求地理位置权限

在`index.js`中添加以下代码,获取用户的地理位置:

Page({
data: {
    latitude: '',
    longitude: '',
    weatherInfo: {}
},
onLoad: function() {
    this.getLocation();
},
getLocation: function() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
      this.setData({
          latitude: res.latitude,
          longitude: res.longitude
      });
      this.getWeather(res.latitude, res.longitude);
      },
      fail: () => {
      wx.showToast({
          title: '获取位置信息失败',
          icon: 'none'
      });
      }
    });
}
})

5. 调用百度天气API

有了用户的地理位置,就可以调用百度天气API获取天气信息。

5.1 构建API请求

在`index.js`中添加以下代码,调用百度天气API:

getWeather: function(latitude, longitude) {
const apiKey = '您的API_KEY';
const url = `<a href="http://api.map.baidu.com/telematics/v3/weather?location=" target="_blank">http://api.map.baidu.com/telematics/v3/weather?location=</a>${longitude},${latitude}&output=json&ak=${apiKey}`;
wx.request({
    url: url,
    success: (res) => {
      if (res.data.error === 0) {
      this.setData({
          weatherInfo: res.data.results
      });
      } else {
      wx.showToast({
          title: '获取天气信息失败',
          icon: 'none'
      });
      }
    },
    fail: () => {
      wx.showToast({
      title: '请求失败',
      icon: 'none'
      });
    }
});
}

6. 显示天气信息

在获取到天气信息后,需要在界面上显示。修改`index.wxml`文件,添加显示天气信息的组件:

<view class="container">
<view class="weather-info">
    <text>城市: {{weatherInfo.currentCity}}</text>
    <text>PM2.5: {{weatherInfo.pm25}}</text>
    <text>天气: {{weatherInfo.weather_data.weather}}</text>
    <text>温度: {{weatherInfo.weather_data.temperature}}</text>
    <text>风力: {{weatherInfo.weather_data.wind}}</text>
</view>
</view>

7. 完整示例代码

7.1 index.js

Page({
data: {
    latitude: '',
    longitude: '',
    weatherInfo: {}
},
onLoad: function() {
    this.getLocation();
},
getLocation: function() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
      this.setData({
          latitude: res.latitude,
          longitude: res.longitude
      });
      this.getWeather(res.latitude, res.longitude);
      },
      fail: () => {
      wx.showToast({
          title: '获取位置信息失败',
          icon: 'none'
      });
      }
    });
},
getWeather: function(latitude, longitude) {
    const apiKey = '您的API_KEY';
    const url = `<a href="http://api.map.baidu.com/telematics/v3/weather?location=" target="_blank">http://api.map.baidu.com/telematics/v3/weather?location=</a>${longitude},${latitude}&output=json&ak=${apiKey}`;
    wx.request({
      url: url,
      success: (res) => {
      if (res.data.error === 0) {
          this.setData({
            weatherInfo: res.data.results
          });
      } else {
          wx.showToast({
            title: '获取天气信息失败',
            icon: 'none'
          });
      }
      },
      fail: () => {
      wx.showToast({
          title: '请求失败',
          icon: 'none'
      });
      }
    });
}
})

7.2 index.wxml

<view class="container">
<view class="weather-info">
    <text>城市: {{weatherInfo.currentCity}}</text>
    <text>PM2.5: {{weatherInfo.pm25}}</text>
    <text>天气: {{weatherInfo.weather_data.weather}}</text>
    <text>温度: {{weatherInfo.weather_data.temperature}}</text>
    <text>风力: {{weatherInfo.weather_data.wind}}</text>
</view>
</view>

8. 结论

通过本文的介绍,您已经了解了如何在微信小程序中使用百度API获取天气信息。从注册百度开发者账号、配置微信小程序,到获取用户位置并调用API获取天气信息,这一过程涵盖了实现该功能的所有步骤。希望本文对您有所帮助,能够让您的小程序更加丰富多彩。






------------------------------------------------------------------------------------------------------------------------------------------
========御 坂 主 机========
>> VPS主机 服务器 前沿资讯 行业发布 技术杂谈 <<
>> 推广/合作/找我玩TG号 : @Misaka_Offical <<
-------------------------------------------------------------------------------------------------------------------------------------------
页: [1]
查看完整版本: 微信小程序使用百度api获取天气信息