当前位置:   article > 正文

【小程序】微信开发者工具+心知天气API实现天气预报

心知天气api

前言

问:为什么使用心知天气的天气数据API而不是其他产品?

答:

  • 心知天气为我们提供了一款通过标准的Restful API接口进行数据访问的天气数据API产品;

  • 心智天气官网为我们提供了足够详细的开发文档和用户手册,方便我们快速上手进行开发;

  • 心知天气旗下的天气数据API针对不同用户提供了四种产品套餐:免费版、试用版、开发者套餐和企业版;对于处在学习阶段的我们可以选择免费申请试用版进行测试学习;


1.效果图


2.获取心知天气API接口

2.1.获取个人API私钥

心知天气官网链接:心知天气icon-default.png?t=N7T8https://www.seniverse.com/

  • 进入心知天气官网注册账号

  • 登录成功后进入控制台页面添加产品(注:这里的试用版和免费版是我已添加过的

  • 免费申请试用版(亦可充值申请开发者套餐进行长期开发,价格也比较划算)

  • 申请成功后点击产品管理=>进入您选择的产品项,在基本信息项获取API私钥

2.2.查询开发文档获取API接口

  • 官网点击文档进入


3.开发测试

3.1.获取页面素材包


使用原因:

                   

亮色主题图标

                                                                                                           

暗色主题图标

                                                                                    

  • 本文演示代码背景使用浅色系,使用亮色主题图标如图所示,会和浅色背景混合导致图标显示不清,所以推荐使用暗色主题图标;

  • 心知天气提供的素材包命名格式采取code@1x.png格式,code是后文中使用wx.request请求API接口获得的属性,可以避免我们自定义方法切换素材从而增大系统开销;

3.2.main.json

  1. {
  2. "usingComponents": {},
  3. "navigationBarBackgroundColor": "#000000",
  4. "navigationBarTextStyle": "white",
  5. "navigationBarTitleText": "天气预报",
  6. "backgroundColor": "#eeeeee",
  7. "backgroundTextStyle": "light"
  8. }
  • usingComponents:用于引入自定义组件。这里没有引入任何自定义组件,后期可进行二次开发添加组件;

  • navigationBarBackgroundColor:设置小程序导航栏的背景颜色;

  • navigationBarTextStyle:设置小程序导航栏的文字颜色;

  • navigationBarTitleText:设置小程序导航栏中间的标题;

  • backgroundColor:设置小程序页面的背景颜色

  • backgroundTextStyle:设置小程序页面的背景文字颜色,以适应浅色背景


3.3.main.wxml

  1. <view>
  2. <view class="header-modular"><!--顶部模块的容器-->
  3. <image class="bg-wave" src="../../images/black/bg_wave.gif"></image><!--背景图片-->
  4. <view class="row" style="width: 100%;margin: auto;"><!--水平布局的容器-->
  5. <view class="tmp" id="now_tmp">{{now.temperature}}°</view><!--当前温度-->
  6. <image class="icon-weather" id="now_icon" src="../../images/black/{{now.code}}@1x.png"></image><!--当前天气图标-->
  7. </view>
  8. <view class="tips-wrap" id="now_wind"><!--风力、湿度和气压的容器-->
  9. <view class='tips'>风力:{{now.wind_scale}} 级</view>
  10. <view class='tips'>湿度:{{now.humidity}} %</view>
  11. <view class='tips'>气压:{{now.pressure}}Pa</view>
  12. </view>
  13. </view>
  14. <view class="card-modular"><!--卡片模块容器,24小时预报和7天预报-->
  15. <view class="title">24小时预报</view><!--标题-->
  16. <!-- 24小时数据 -->
  17. <view class="card-wrap" ><!--24小时预报的容器-->
  18. <view class="item hourly" wx:for="{{hourly}}" wx:key="index"><!--每个小时的预报-->
  19. <view class="text-gray">{{item.time}}</view><!--时间-->
  20. <image class="icon" src="../../images/black/{{item.code}}@1x.png"></image><!--天气图标-->
  21. <view class="text-primary mb-32">{{item.temperature}}°</view><!--温度-->
  22. <view>{{item.text}}</view><!--天气描述-->
  23. <view class="text-gray">{{item.wind_direction}}风</view><!--风向-->
  24. </view>
  25. </view>
  26. </view>
  27. <view class="card-modular">
  28. <view class="title">7天预报</view><!--7天预报的标题-->
  29. <view class="card-wrap"> <!--7天预报的容器-->
  30. <view class="item daily" wx:for="{{daily}}" wx:key="index"><!--每天的预报项-->
  31. <view>{{item.newDate}}</view><!--星期-->
  32. <view class="text-gray">{{item.date}}</view><!--日期-->
  33. <image class="icon" src="../../images/black/{{item.code_day}}@1x.png"></image><!--白天天气图标-->
  34. <view class="text-primary">{{item.low}}°~{{item.high}}°</view><!--最低温度和最高温度-->
  35. <image class="icon" src="../../images/black/{{item.code_night}}@1x.png"></image><!--夜晚天气图标-->
  36. <view>{{item.text_day}}</view><!--天气描述-->
  37. <view class="text-gray">{{item.wind_scale}}级</view><!--风力等级-->
  38. </view>
  39. </view>
  40. </view>
  41. </view>

3.3.1.header-modular:顶部模块

  • API接口返回的数据格式:

图中信息来源于:心知天气 官方文档
  • {{now.XXX}}:在模板中插入从API接口中请求的动态数据

  • src="../../images/black/{{now.code}}@1x.png":图片素材来源于本地,且使用数据绑定根据API接口返回的code获取属于这段数据的图片素材


3.3.2.二十四小时预报卡片模块

  • API接口返回的数据格式:

图中信息来源于:心知天气 官方文档
  • wx:for{hourly}:列表绑定API接口返回的hourly数据进行循环渲染


3.3.3.七天预报卡片模块

  • API接口返回的数据格式:

图中信息来源于:心知天气 官方文档

3.4.main.wxss

  1. /* pages/Weather/main.wxss */
  2. body {
  3. padding-bottom: 60rpx;
  4. }
  5. /* 工具类 */
  6. .row {
  7. display: flex;
  8. align-items: center;
  9. }
  10. .mb-32 {
  11. margin-bottom: 32rpx;
  12. }
  13. /* 页面样式 */
  14. .header-modular {
  15. height: 400rpx;
  16. background-color: #64C8FA;
  17. background: linear-gradient(to bottom, #DCEAFC, #C1CFDF);
  18. position: relative;
  19. padding: 30rpx;
  20. }
  21. .header-modular .bg-wave {
  22. width: 100vw;
  23. position: absolute;
  24. bottom: -2rpx;
  25. left: 0;
  26. right: 0;
  27. height: 120rpx;
  28. mix-blend-mode: screen;
  29. }
  30. .header-modular .location-wrap .icon {
  31. width: 40rpx;
  32. height: 40rpx;
  33. margin-right: 8rpx;
  34. }
  35. .header-modular .tmp {
  36. font-size: 200rpx;
  37. font-weight: bold;
  38. color: #fff;
  39. margin-right: auto;
  40. }
  41. .header-modular .icon-weather {
  42. width: 200rpx;
  43. height: 200rpx;
  44. }
  45. .header-modular .tips-wrap {
  46. display: flex;
  47. justify-content: space-between;
  48. }
  49. .header-modular .tips {
  50. font-size: 28rpx;
  51. opacity: 0.8;
  52. color: #da1a1a;
  53. flex: 1;
  54. }
  55. .header-modular .tips:nth-child(3) {
  56. text-align: right;
  57. }
  58. .header-modular .tips:nth-child(2) {
  59. text-align: center;
  60. }
  61. .card-modular {
  62. padding: 0 30rpx;
  63. margin-top: 30rpx;
  64. }
  65. .card-modular > .title {
  66. font-size: 40rpx;
  67. font-weight: bold;
  68. position: relative;
  69. margin-left: 14rpx;
  70. margin-bottom: 16rpx;
  71. }
  72. .card-modular > .title::before {
  73. content: "";
  74. position: absolute;
  75. left: -14rpx;
  76. top: 10rpx;
  77. bottom: 10rpx;
  78. width: 8rpx;
  79. border-radius: 10rpx;
  80. background-color: #2F80ED;
  81. }
  82. .card-modular .card-wrap {
  83. /*width: 690rpx;*/
  84. border-radius: 18rpx;
  85. background-color: #ffffff;
  86. box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.2);
  87. overflow-x: auto;
  88. white-space: nowrap;
  89. }
  90. .card-modular .card-wrap .item {
  91. display: inline-flex;
  92. flex-direction: column;
  93. align-items: center;
  94. font-size: 28rpx;
  95. padding: 18rpx 0;
  96. }
  97. .card-modular .card-wrap .item.hourly {
  98. width: 138rpx;
  99. }
  100. .card-modular .card-wrap .item.daily {
  101. width: 172.5rpx;
  102. }
  103. .card-modular .card-wrap .item .icon {
  104. width: 60rpx;
  105. height: 60rpx;
  106. margin: 64rpx 0;
  107. }
  108. .card-modular .card-wrap .item .text-gray {
  109. color: gray;
  110. }
  111. .card-modular .card-wrap .item .text-primary {
  112. color: #2F80ED;
  113. }

3.5.main.js

  1. // pages/Weather/main.js
  2. const private_key = "你的私钥";
  3. Page({
  4. /**
  5. * 页面的初始数据
  6. */
  7. data: {
  8. location: '你的城市',
  9. now: {},
  10. hourly:[],
  11. daily:[]
  12. },
  13. getWeather() {
  14. wx.showLoading({
  15. title: '加载中',
  16. })
  17. wx.request({
  18. url: `https://api.seniverse.com/v3/weather/now.json?key=${private_key}&location=${this.data.location}&language=zh-Hans&unit=c`,
  19. method: 'GET',
  20. success: (res) => {
  21. console.log("总数据", res);
  22. this.setData({
  23. now: res.data.results[0].now
  24. })
  25. }
  26. })
  27. // 24小时天气预报获取
  28. wx.request({
  29. url: `https://api.seniverse.com/v3/weather/hourly.json?key=${private_key}&location=${this.data.location}&language=zh-Hans&unit=c&start=0&hours=24`,
  30. method: 'GET',
  31. success: (res) => {
  32. let hourlys =res.data.results[0].hourly;
  33. console.log(hourlys);
  34. hourlys.forEach((item)=>{
  35. item.time = this.formatTime(new Date(item.time)).hourly
  36. })
  37. this.setData({
  38. hourly:hourlys
  39. })
  40. console.log("24小时天气",this.data.hourly);
  41. }
  42. })
  43. //七天预报获取
  44. wx.request({
  45. url: `https://api.seniverse.com/v3/weather/daily.json?key=${private_key}&location=${this.data.location}&language=zh-Hans&unit=c&start=0&days=7`,
  46. method: 'GET',
  47. success: (res) => {
  48. let dailys =res.data.results[0].daily;
  49. dailys.forEach((item)=>{
  50. item.newDate= this.formatTime(new Date(item.date)).dailyToString,
  51. item.date =this.formatTime(new Date(item.date)).daily
  52. })
  53. this.setData({
  54. daily:dailys
  55. })
  56. console.log('7天数据',this.data.daily);
  57. wx.hideLoading();//关闭等待窗口
  58. }
  59. })
  60. },
  61. /**
  62. * 生命周期函数--监听页面加载
  63. */
  64. onLoad(options) {
  65. this.getWeather();
  66. },
  67. formatTime(date) {
  68. const year = date.getFullYear()
  69. const month = date.getMonth() + 1
  70. const day = date.getDate()
  71. const hour = date.getHours()
  72. const minute = date.getMinutes()
  73. const second = date.getSeconds()
  74. const weekArray = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
  75. const isToday = date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)
  76. return {
  77. hourly: [hour, minute].map(this.formatNumber).join(":"),
  78. daily: [month, day].map(this.formatNumber).join("-"),
  79. dailyToString: isToday ? "今天" : weekArray[date.getDay()]
  80. }
  81. },
  82. formatNumber(n) {
  83. n = n.toString()
  84. return n[1] ? n : '0' + n
  85. }
  86. })
  • 声明常量private_key存储私钥,用于在getWeather()方法中向API发送请求时使用${private_key}模板字符串进行插值;
  • 在getWeather()方法中通过wx.request()方法向API发送请求,获取当天天气预报24小时天气预报七天天气预报。请求完成后调用formatTime()方法和formatNumber()方法格式化API接口返回的时间数据以及时间中的数字,将数据存储在页面data中的now、hourly和daily属性中,最后调用wx.hideLoading()方法关闭加载中的提示框;
  • 生命周期函数onLoad()在页面加载时触发,会调用getWeather()方法获取天气数据;

时贰肆年壹月拾日晌午

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号