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

这篇具有很好参考价值的文章主要介绍了【微信小程序】使用和风天气接口api(全过程)——获取天气。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

介绍

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

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

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

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


目录

前言

显示效果

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

二、获取和风天气的key

1、创建项目

 2、获取key

 三、在小程序中的使用

第一步:创建包

第二步:示例代码

workweather.wxml

workweather.wxxs

workweather.js


显示效果

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

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

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

和风天气的官网

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

二、获取和风天气的key

1、创建项目

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

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

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

 2、获取key

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

 三、在小程序中的使用

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

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

第一步:创建包

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

第二步:示例代码

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"
  ]

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

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

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

以上就是小编做的一个小案例,希望各位大佬多多指教!!!文章来源地址https://www.toymoban.com/news/detail-400015.html

到了这里,关于【微信小程序】使用和风天气接口api(全过程)——获取天气的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【微信小程序项目】——十分钟开发网络API·天气查询小程序、天气查询,美观简约,简单易上手

    【实验目的】 复习小程序项目 的 新建过程 掌握 配置https域名的方式 使用微信 网络请求能力获取天气预报 使用腾讯提供的网络通信API,调用第三方提供的API PART I 准备工作 A PI 密钥申请( 非必做 ) 本小节主要介绍如何申请获得开源API的密钥。这里选择了可以提供全球气象

    2023年04月20日
    浏览(39)
  • uni开发微信小程序引入和风天气第三方库 icon不显示问题处理(阿里等icon库同样的处理方式)

    1.首先下载和风天气字体包 2.在node_modules文件夹找 qweather-icons 下的ttf后缀的文件 3. 转换base64_______   https://transfonter.org/ ​ ​ 下载后得到如下文件: ​ 复制该文件到工程中 下一步 复制qweather-icons.css 中红框内往下所有的代码,粘贴到转换base后的文件中,如下图 最后再ma

    2024年04月26日
    浏览(30)
  • iOS开发Swift-10-位置授权, cocoapods,API,天气获取,城市获取-和风天气App首页代码

     1.获取用户当前所在的位置 在infi中点击加号,选择权限:当用户使用app的时候获取位置权限. 填写使用位置权限的目的.  2.获取用户的经纬度. ViewController:  3.通过第三方服务获取当前天气 (1)安装cocoapods https://dev.qweather.com/ 在网站中可以找到,当向 https://devapi.qweather.com/v7/weathe

    2024年02月09日
    浏览(36)
  • 【ESP8266物联网天气时钟】解决太极创客物联网天气时钟二三页出现NA的问题——新版和风天气API以及gzip数据解压

      前几天想要找一个开源项目做一下,然后一番搜索后找到了太极创客在B站发布的一个物联网小项目制作:“物联网天气时钟粉丝数显示oled小电视”。   这个项目主要用到的资源就是一块 ESP01S 和一块四脚的0.96寸 OLED 屏幕,正好手头也有,就打算复刻下这个项目,原项

    2024年02月05日
    浏览(31)
  • 微信小程序 - 调用后台api接口方法

    2024年01月16日
    浏览(38)
  • 跳转微信小程序短链接的API接口

    =\\\"ht tps://p http://ush.youlacloud.com/\\\"怎么从网页跳转一键跳转到微信小程序? 发送短信,用户点击链接,直达微信小程序? 如何抖音跳转微信小程?淘宝跳转微信小程? 等等类似的应用,都需要是借助 将微信小程序生成一般的链接,用户通过点击链接直接进入小程序。 复制发短

    2024年02月15日
    浏览(41)
  • 微信小程序 通过百度API接口实现汉译英翻译

    目录 先看一下做出来的效果: 一、微信开发平台的网址(微信开发者工具的官方使用说明) 二、百度API(文本翻译的API) 三、进入正文,微信小程序的代码部分 基础 | 微信开放文档 (qq.com) https://developers.weixin.qq.com/miniprogram/dev/api/   文本翻译_机器翻译-百度AI开放平台 (bai

    2024年02月09日
    浏览(48)
  • 微信小程序实现调用百度文心一言接口API(可直接运行代码)

    直接贴出运行结果 总共有三个步骤,过程都很简单。 先进入文心千帆大模型平台,然后点击左边一列的“应用接入”,然后点创建应用,这时你就获得了API_key了。 如下,开通是免费的,付费随时可以中止。 不过记得要换成自己的API_key和Secret_key。  (如果报错 “链接不在

    2024年02月13日
    浏览(33)
  • 【小程序】微信开发者工具+心知天气API实现天气预报

    问:为什么使用心知天气的天气数据API而不是其他产品? 答: 心知天气为我们提供了一款通过标准的Restful API接口进行数据访问的天气数据API产品; 心智天气官网为我们提供了足够详细的开发文档和用户手册,方便我们快速上手进行开发; 心知天气旗下的天气数据API针对不

    2024年01月16日
    浏览(55)
  • IIS发布.net6 api+微信小程序/H5真机调试接口的流程

    我们创建.net6 api程序,然后使用SqlSugar连接MySQL数据库,再使用iis发布,当然使用其他的也行。再开发一个微信小程序,手机运行小程序,手机运行H5,都可以看到数据库的数据,就是这么一个流程。 开始! 目录 第一,.net6api开发 第二,IIS发布.net6api 第三,开发微信小程序

    2024年02月16日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包