【微信小程序】使用和风天气接口api(全过程)——获取天气

介绍

这里是小编成长之路的历程,也是小编的学习之路。希望和各位大佬们一起成长!

以下为小编最喜欢的两句话:

要有最朴素的生活和最遥远的梦想,即使明天天寒地冻,山高水远,路远马亡。

一个人为什么要努力? 我见过最好的答案就是:因为我喜欢的东西都很贵,我想去的地方都很远,我爱的人超完美。因此,小编想说:共勉! 


目录

前言

显示效果

一、注册和风天气的账号(具体过程就不演示了)

二、获取和风天气的key

1、创建项目

 2、获取key

 三、在小程序中的使用

第一步:创建包

第二步:示例代码

workweather.wxml

workweather.wxxs

workweather.js


显示效果

cd004afdbf7444f1bf6c45cb3d811ae6.png

注意:如果各位大佬们,按照该博客不能出现自己想要的效果,那么可以去找其他的方法实现,可将该博客当做一个小小的参考。感谢各位大佬的观看!

一、注册和风天气的账号(具体过程就不演示了)

和风天气的官网

和风天气插件 | 和风天气插件产品,免费、跨终端。适配你的网站、APP、公众号 (qweather.com)

二、获取和风天气的key

1、创建项目

控制台===》项目管理===》创建项目 就可以看到以下页面(注意:如果页面不一样的话,可能是更新了)

0968a68110ae4f94b15e743881409070.png

这个地方注意一下,看你是做案例还是,公司使用,如果是做案例,可以和小编一样选择免费订阅。设置key的地方你可以选择Web API,如果你选择了 Android SDK / iOS SDK,那么生成的密钥只能使用官方的 SDK 进行数据访问,如果是 Web API的话,可以自己编程获取并解析数据。(当然WebAPI解析比较慢一点,可以稍微等一会)

 2、获取key

2dd6afa6aecc45d9aaca16d1e351570a.png

 三、在小程序中的使用

如果是小白的话,没有账号,建议注册一个小程序的账号,具体看小编的这篇文章。有账号跳过这个步骤

【微信小程序】注册小程序账号、做一个案例——你好我的小程序_determine ZandR的博客-CSDN博客

第一步:创建包

507e41b2ea0d45149202f9944fc66c30.png

第二步:示例代码

workweather.wxml


<view class="header-modular" wx:if="{{now}}">
	<image class="bg-wave" src="https://codermoyv.gitee.io/coder-moyv/assets/images/wechat/bg_wave.gif"></image>
	<view class="row">
		<view class="row location-wrap" bindtap="selectLocation">
			<image class="icon" src=""></image>
			<view class="title">{{City}} {{County}}</view>
		</view>
 
	</view>
	<view class="row">
		<view class="tmp">{{now.temp}}°</view>
		<image class="icon-weather" src="https://codermoyv.gitee.io/coder-moyv/assets/images/wechat/weather_custom/{{now.icon}}.png"></image>
	</view>
	<view class="tips-wrap">
		<view class="tips ">{{now.windDir}} {{now.windScale}}级</view>
		<view class="tips ">湿度 {{now.humidity}}%</view>
		<view class="tips ">气压 {{now.pressure}}Pa</view>
	</view>
</view>
 
<view class="card-modular " wx:if="{{hourly}}">
	<view class="title">24小时预报</view>
	<view class="card-wrap">
		<block wx:for="{{hourly}}" wx:key="index">
			<view class="item hourly">
				<view class="text-gray">{{item.time}}</view>
				<image class="icon" src="https://codermoyv.gitee.io/coder-moyv/assets/images/wechat/weather_custom/{{item.icon}}.png"></image>
				<view class="text-primary mb-32">{{item.temp}}°</view>
				<view>{{item.windDir}}</view>
				<view class="text-gray">{{item.windScale}}级</view>
			</view>
		</block>
	</view>
</view>
 
<view class="card-modular" wx:if="{{daily}}">
	<view class="title">7天预报</view>
	<view class="card-wrap">
		<block wx:for="{{daily}}" wx:key="index">
			<view class="item daily">
				<view>{{item.dateToString}}</view>
				<view class="text-gray">{{item.date}}</view>
				<image class="icon" src="https://codermoyv.gitee.io/coder-moyv/assets/images/wechat/weather_custom/{{item.iconDay}}.png"></image>
				<view class="text-primary ">{{item.tempMin}}°~{{item.tempMax}}°</view>
				<image class="icon" src="https://codermoyv.gitee.io/coder-moyv/assets/images/wechat/weather_custom/{{item.iconNight}}.png"></image>
				<view>{{item.windDirDay}}</view>
				<view class="text-gray">{{item.windScaleDay}}级</view>
			</view>
		</block>
	</view>
</view>

workweather.wxxs

  page {
    background-color: linear-gradient(to bottom, #ffffff,#ffffff, #F6F6F6);
    padding-bottom: 60rpx;
  }
   
  /* 工具类 */
  .row {
    display: flex;
    align-items: center;
  }
   
  .mb-32{
    margin-bottom: 32rpx;
  }
   
  /* 页面样式 */
  .header-modular {
    height: 400rpx;
    background-color: #64C8FA;
    background: linear-gradient(to bottom, #56CCF2, #2F80ED);
    position: relative;
    padding: 30rpx;
  }
   
  .header-modular .bg-wave {
    width: 100vw;
    position: absolute;
    bottom: -2px;
    left: 0;
    right: 0;
    height: 120rpx;
    mix-blend-mode: screen;
  }
   
  .header-modular .location-wrap {
    color: #ffffff;
    font-weight: bold;
    font-size: 36rpx;
  }
   
  .header-modular .location-wrap .icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 8rpx;
  }
   
  .header-modular .tmp {
    font-size: 200rpx;
    /* font-weight: bold; */
    color: #ffffff;
    margin-right: auto;
  }
   
  .header-modular .icon-weather {
    width: 200rpx;
    height: 200rpx;
  }
   
  .header-modular .tips-wrap {
    display: flex;
    justify-content: space-between;
  }
   
  .header-modular .tips {
    font-size: 28rpx;
    opacity: 0.8;
    color: #ffffff;
    flex: 1;
  }
   
  .header-modular .tips:nth-child(3) {
    text-align: right;
  }
   
  .header-modular .tips:nth-child(2) {
    text-align: center;
  }
   
  .card-modular {
    padding:0 30rpx;
    margin-top: 30rpx;
  }
   
  .card-modular>.title {
    font-size: 40rpx;
    font-weight: bold;
    position: relative;
    margin-left: 14rpx;
    margin-bottom: 16rpx;
  }
   
  .card-modular>.title::before {
    content: "";
    position: absolute;
    left: -14rpx;
    top: 10rpx;
    bottom: 10rpx;
    width: 8rpx;
    border-radius: 10rpx;
    background-color: #2F80ED;
  }
   
  .card-modular .card-wrap {
    width: 690rpx;
    border-radius: 18rpx;
    background-color: #ffffff;
    box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.2);
    overflow-x: auto;
    white-space: nowrap;
  }
   
  .card-modular .card-wrap .item {
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    font-size: 28rpx;
    padding: 18rpx 0;
  }
  .card-modular .card-wrap .item.hourly{
    width: 138rpx;
  } 
  .card-modular .card-wrap .item.daily{
    width: 172.5rpx;
  }
  .card-modular .card-wrap .item .icon {
    width: 60rpx;
    height: 60rpx;
    margin: 64rpx 0;
  }
   
  .card-modular .card-wrap .item .text-gray {
    color: gray;
  }
   
  .card-modular .card-wrap .item .text-primary {
    color: #2F80ED;
  }
  
  
  

workweather.js

const APIKEY = "";// 填入你申请的KEY
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLocation()
  },
  //选择定位
  selectLocation() {
    var that = this
    wx.chooseLocation({
      success(res) {
        //console.log(res)
        that.setData({
          location: res.longitude + "," + res.latitude
        })
        that.getWeather()
        that.getCityByLoaction()
      }
      , fail() {
        wx.getLocation({
          type: 'gcj02',
          fail() {
            wx.showModal({
              title: '获取地图位置失败',
              content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
              success(mRes) {
                if (mRes.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userLocation"] === true) {
                        that.selectLocation()
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    }, fail(err) {
                      console.log(err)
                      wx.showToast({
                        title: '唤起设置页失败,请手动打开',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  })
                }
              }
            })
          }
        })

      }
    })
  },
  /**
   * 获取定位
   */
  getLocation() {
    var that = this
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        that.setData({
          location: res.longitude + "," + res.latitude
        })
        that.getWeather()
        that.getCityByLoaction()
      }, fail(err) {
        wx.showModal({
          title: '获取定位信息失败',
          content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
          success(mRes) {
            if (mRes.confirm) {
              wx.openSetting({
                success: function (data) {
                  if (data.authSetting["scope.userLocation"] === true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    that.getLocation()
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                    that.setData({
                      location: "地理位置"
                    })
                    that.getWeather()
                    that.getCityByLoaction()
                  }
                }, fail(err) {
                  console.log(err)
                  wx.showToast({
                    title: '唤起设置页失败,请手动打开',
                    icon: 'none',
                    duration: 1000
                  })
                  that.setData({
                    location: "地理位置"
                  })
                  that.getWeather()
                  that.getCityByLoaction()
                }
              })
            } else if (mRes.cancel) {
              that.setData({
                location: "地理位置"
              })
              that.getWeather()
              that.getCityByLoaction()
            }
          }
        })
      }
    })
  },
  /**
   * 根据坐标获取城市信息
   */
  getCityByLoaction() {
    var that = this
    wx.request({
      url: 'https://geoapi.qweather.com/v2/city/lookup?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        if (res.code == "200") {
          var data = res.location[0]
          that.setData({
            City: data.adm2,
            County: data.name
          })
        } else {
          wx.showToast({
            title: '获取城市信息失败',
            icon: 'none'
          })
        }

      }
    })
  },
  /**
   * 获取天气
   */
  getWeather() {
    var that = this
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/now?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        //console.log(res)
        that.setData({
          now: res.now
        })
      }
    })
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/24h?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        //console.log(res)
        res.hourly.forEach(function (item) {
          item.time = that.formatTime(new Date(item.fxTime)).hourly
        })
        that.setData({
          hourly: res.hourly
        })
      }
    })
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/7d?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        //console.log(res)
        res.daily.forEach(function (item) {
          item.date = that.formatTime(new Date(item.fxDate)).daily
          item.dateToString = that.formatTime(new Date(item.fxDate)).dailyToString
        })
        that.setData({
          daily: res.daily
        })
        wx.hideLoading()
      }
    })
  },
  // 格式时间
  formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    const weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
    const isToday = date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)
    return {
      hourly: [hour, minute].map(this.formatNumber).join(":"),
      daily: [month, day].map(this.formatNumber).join("-"),
      dailyToString: isToday ? "今天" : weekArray[date.getDay()]
    }
  },
  // 补零
  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})


注意: 如果复制上述代码,出现wx.getLocation need to be declared in the requiredPrivateInfos field in app.json的问题,查看两个地方

一、看全局json中是否有以下代码

  "requiredPrivateInfos": [
    "getLocation"
  ]

 59eb5f0c771c43acbe519ce788ffd70a.png

 二、看版本(2.6.0以上版本无法使用)

9a0d30fd0b9d4eaa9efaf06cb7e677d9.png

以上就是小编做的一个小案例,希望各位大佬多多指教!!!

微信小程序Demo-和风天气天气API,设置城市-附完整源代码.rar 资源介绍 本资源是一个基于微信小程序的Demo项目,名为“和风天气”,主要功能是展示当前天气信息以及提供设置城市的功能。本项目采用和风天气API获取实时天气数据,方便开发者学习和实践微信小程序与第三方API的集成。同时,该项目源码完全开源,可以进行二次开发定制,满足个性化需求。 主要特点: 1. 实时天气信息展示:通过和风天气API获取用户指定城市的实时天气信息,包括气温、湿度、风向、风力等详细数据。 2. 城市设置功能:用户可以在小程序中自定义设置所需查询的城市,方便随时查看不同地区的天气状况。 3. 界面简洁美观:采用微信小程序原生组件进行界面设计,整体风格简约大方,符合用户使用习惯。 4. 数据缓存优化:为了提高用户体验,减少网络请求,本项目对天气数据进行本地缓存,避免频繁调用API。 5. 完整源码及文档:提供完整的项目源码和详细的开发文档,方便开发者快速上手并进行二次开发定制。 适用场景: 1. 学习微信小程序开发:本项目可以作为学习微信小程序开发的实践案例,帮助初学者熟悉微信小程序的基本功能和开发流程。 2. 天气预报应用:可以根据本项目源码进行二次开发,打造一个个性化的天气预报应用,满足特定用户需求。 3. 其他领域拓展:通过修改源码中的API接口和数据解析逻辑,可以将本项目应用于其他类似场景,如交通出行、旅游指南等。 总之,微信小程序Demo-和风天气天气API,设置城市-附完整源代码.rar 资源为开发者提供了一个很好的学习和实践平台,无论是初学者还是有一定经验的开发者,都可以从中受益。
<think>好的,用户想了解如何在JavaScript中使用和风天气API的方法,需要教程和示例代码。我需要先回顾一下用户提供的引用内容,看看有没有相关的信息。引用3提到了Vue中使用和风天气API的例子,其中有一个插入天气的方法,使用了script标签引入外部JS文件,并配置了WIDGET对象。这可能是一个小部件的方式,但用户可能需要的是直接通过API获取数据,而不是嵌入小部件。引用4提到Ajax通过城市名获取数据,使用全国天气预报API,但具体到和风天气可能需要不同的处理。 用户的问题集中在JavaScript的使用方法,所以需要给出具体的步骤,比如注册API key、发起请求、处理响应等。同时需要示例代码,可能包括直接使用fetch或者XMLHttpRequest的例子。另外,引用3中的代码示例可能可以作为参考,但需要调整成更通用的JavaScript代码,而不是Vue特定的方法。还要注意用户提到的调试困难,所以可能需要强调常见的错误点,比如跨域问题、API key的正确使用等。 还需要考虑用户可能需要的功能,比如获取实时天气天气预报等,可能需要不同的API端点。确保步骤清晰,分点说明,并给出代码示例。另外,用户提供的引用中有GitHub示例链接,可以建议用户参考,但可能需要补充说明。最后,生成相关问题,帮助用户进一步学习,比如处理跨域、解析数据等。</think>### JavaScript中使用和风天气API的方法 #### 1. 注册并获取API Key - 访问[和风天气开发者平台](https://dev.qweather.com/),注册账号并创建项目,获取API Key(如示例中的`82898b167593451b81c7ce87a89135d0`[^3])。 #### 2. 基础请求示例(城市实时天气使用`fetch`发起请求: ```javascript const apiKey = 'YOUR_API_KEY'; const cityId = 'CN101230101'; // 城市ID,如福州 const apiUrl = `https://devapi.qweather.com/v7/weather/now?location=${cityId}&key=${apiKey}`; fetch(apiUrl) .then(response => response.json()) .then(data => { if (data.code === '200') { const temp = data.now.temp; const text = data.now.text; console.log(`当前温度:${temp}℃,天气:${text}`); } else { console.error('请求失败:', data); } }) .catch(error => console.error('请求错误:', error)); ``` #### 3. 使用城市名称查询(需先获取城市ID) ```javascript const citySearchUrl = `https://geoapi.qweather.com/v2/city/lookup?location=福州&key=${apiKey}`; fetch(citySearchUrl) .then(response => response.json()) .then(data => { if (data.code === '200') { const cityId = data.location[0].id; // 使用cityId继续请求天气数据 } }); ``` #### 4. 嵌入天气小部件(参考官方组件) 引用Vue示例中的实现方式[^3]: ```javascript function loadWeatherWidget() { window.WIDGET = { CONFIG: { layout: '2', width: 300, key: 'YOUR_API_KEY', city: 'CN101230101' } }; const script = document.createElement('script'); script.src = 'https://widget.qweather.net/standard/static/js/he-standard-common.js'; document.body.appendChild(script); } ``` #### 注意事项 - **跨域问题**:建议在服务端代理请求或使用JSONP(部分API支持) - **频率限制**:免费版每日有调用次数限制 - **数据解析**:响应数据包含`obsTime`(数据观测时间)、`feelsLike`(体感温度)等字段 更多完整示例可参考GitHub仓库[^2]。
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值