iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >微信小程序天气预报功能实现(支持自动定位,附源码)
  • 471
分享到

微信小程序天气预报功能实现(支持自动定位,附源码)

2024-04-02 19:04:59 471人浏览 八月长安
摘要

目录前言天气api获取微信小程序后台域名配置页面代码注意问题(必看)源码总结前言 由于和风天气API的更新,之前写的那篇文章 可能会出现版本不兼容的 情况。所以 更新了 这个 使用新

前言

由于和风天气API的更新,之前写的那篇文章 可能会出现版本不兼容的 情况。所以 更新了 这个 使用新版API的 小程序

效果图

天气API获取

这里我用的是和风天气的API,打开官网注册或者登陆你的账号

进入控制台,选择应用管理,新建应用(应用版本 选择 免费开发版,key的类型 选择 WEB API)

创建成功后就可以看到 待会要用到的 key了

微信小程序后台域名配置

登陆小程序后台,分别点击开发和开发设置

点击修改,将我们要用到的 API的域名添加到request合法域名里面,https://devapi.qweather.comHttps://geoapi.qweather.com

页面代码

.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="/images/icon_location.png"></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>

.wxss

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;
  
  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;
}

.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: "116.41,39.92"
                    })
                    that.getWeather()
                    that.getCityByLoaction()
                  }
                }, fail(err) {
                  console.log(err)
                  wx.showToast({
                    title: '唤起设置页失败,请手动打开',
                    icon: 'none',
                    duration: 1000
                  })
                  that.setData({
                    location: "116.41,39.92"
                  })
                  that.getWeather()
                  that.getCityByLoaction()
                }
              })
            } else if (mRes.cancel) {
              that.setData({
                location: "116.41,39.92"
              })
              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 () {

  }
})

app.JSON

{
  "pages": [
    "pages/index/index"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "天气预报",
    "navigationBarTextStyle": "black"
  },
  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于天气预报定位" 
    }
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

注意问题(必看)

为了确保 小程序 可以 正常使用,请先在和风天气 控制台 升级为 个人开发者(ps:该升级需要上传实名信息)。

在js代码中,请将刚刚申请的key 填写进 APIKEY 里面

源码

Gitee源码 (欢迎Start)

总结

到此这篇关于微信小程序天气预报功能实现的文章就介绍到这了,更多相关微信小程序天气预报功能内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 微信小程序天气预报功能实现(支持自动定位,附源码)

本文链接: https://www.lsjlt.com/news/147778.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 微信小程序天气预报功能实现(支持自动定位,附源码)
    目录前言天气API获取微信小程序后台域名配置页面代码注意问题(必看)源码总结前言 由于和风天气API的更新,之前写的那篇文章 可能会出现版本不兼容的 情况。所以 更新了 这个 使用新...
    99+
    2024-04-02
  • 微信小程序天气预报功能怎么实现
    这篇文章主要讲解了“微信小程序天气预报功能怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“微信小程序天气预报功能怎么实现”吧!这里我用的是和风天气的API,打开官网注册或者登陆你的账号...
    99+
    2023-06-30
  • 如何用PHP实现微信小程序的天气预报功能?
    如何用PHP实现微信小程序的天气预报功能?随着微信小程序的流行,越来越多的开发者开始尝试在小程序中添加实用的功能,比如天气预报。在本文中,我们将学习如何使用PHP来实现微信小程序的天气预报功能,并提供代码示例。在开始之前,我们需要确保已经申...
    99+
    2023-10-27
    天气预报 PHP 微信小程序
  • 微信小程序如何实现实时聊天并支持图片预览
    这篇文章给大家分享的是有关微信小程序如何实现实时聊天并支持图片预览的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。首先看一下界面,界面很简单,就是首页刚进来获取了用户信息头像,昵称...
    99+
    2024-04-02
  • 微信小程序怎么实现锚点定位功能
    这篇“微信小程序怎么实现锚点定位功能”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“微信小程序怎么实现锚点定位功能”文章吧。实...
    99+
    2023-06-08
  • 微信小程序地图定位功能怎么实现
    本篇内容主要讲解“微信小程序地图定位功能怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“微信小程序地图定位功能怎么实现”吧!方法如下首先呢你要有一个方法去触发这个点击事件,下面已经写好啦,...
    99+
    2023-06-30
  • 使用微信小程序实现地图定位功能
    使用微信小程序实现地图定位功能微信小程序作为一种轻量级的应用程序,提供了丰富的能力,其中地图定位功能是许多小程序开发者常常需要使用的。本文将介绍如何使用微信小程序来实现地图定位功能,并给出具体的代码示例。一、准备工作在开始编写代码之前,我们...
    99+
    2023-11-21
    微信小程序 实现功能 地图定位
  • 微信小程序如何实现锚点定位功能
    这篇文章将为大家详细讲解有关微信小程序如何实现锚点定位功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。前言在小程序开发中,我们经常会遇到滚动列表查看的需求,那么使用锚点定位来实现可以达到交互体验更加友好...
    99+
    2023-06-20
  • 微信小程序中如何实现导航栏滑动定位功能
    这篇文章给大家分享的是有关微信小程序中如何实现导航栏滑动定位功能的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。实现的效果实现的原理1. 通过对scroll的监听获取滚动条的scr...
    99+
    2024-04-02
  • 微信小程序如何实现自动客服功能
    这篇文章主要为大家展示了“微信小程序如何实现自动客服功能”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“微信小程序如何实现自动客服功能”这篇文章吧。微信小程序最近...
    99+
    2024-04-02
  • 微信小程序实现表单自动填充功能
    微信小程序实现表单自动填充功能随着互联网技术的不断发展,移动应用也变得越来越普及。微信小程序作为一种轻量级的应用形式,已经成为人们生活中的重要组成部分。在微信小程序中,表单是用户与小程序进行信息交互的重要方式之一。为了提高用户体验,可以考虑...
    99+
    2023-11-21
  • 微信小程序实现活动报名登记功能(实例代码)
    目录01、实现目标02、案例分析03、代码实现1. 时间合法性检测2. 从地图中选点获取地理位置信息3. 上传微信收款二维码4. 提交表单 自2020年以来,在疫情的影响下...
    99+
    2024-04-02
  • 微信小程序实现锚点定位功能的方法实例
    前言 在小程序开发中,我们经常会遇到滚动列表查看的需求,那么使用锚点定位来实现可以达到交互体验更加友好的效果,我们看下项目中实现的效果:    &nbs...
    99+
    2024-04-02
  • 微信小程序自定义组件实现多选功能
    本文实例为大家分享了微信小程序自定义组件实现多选的具体代码,供大家参考,具体内容如下 效果图: 调用部分(例如在index页面) index.wxml <view catch...
    99+
    2024-04-02
  • 微信小程序自定义组件实现单选功能
    本文实例为大家分享了微信小程序自定义组件实现单选的具体代码,供大家参考,具体内容如下 效果图: 调用部分(例如在index页面) index.wxml <view catch...
    99+
    2024-04-02
  • 微信小程序如何实现定位到当前城市功能
    这篇文章给大家分享的是有关微信小程序如何实现定位到当前城市功能的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。微信小程序 定位到当前城市首先需要申请百度地图Geocoding AP...
    99+
    2024-04-02
  • 微信小程序实现发动态功能的示例代码
    目录一、设计所需要的表1、文章表2、评论表3、点赞表二、发布动态1、文本区2、最终发表动态效果3、发布动态代码最近做了一个校园拍卖小程序,想在里面添加一个类似校园圈功能,现在来一步一...
    99+
    2022-11-13
    小程序发动态 微信小程序发动态
  • PHP开发微信小程序:如何实现自动回复功能?
    PHP开发微信小程序:如何实现自动回复功能?微信小程序是一种轻量级的应用程序,非常适用于移动设备。在开发微信小程序时,自动回复功能是一个非常重要的功能,可以提供更好的用户体验。本文将介绍如何使用PHP语言开发微信小程序的自动回复功能,并提供...
    99+
    2023-10-27
    PHP 微信小程序 自动回复
  • 使用微信小程序实现搜索框自动补全功能
    使用微信小程序实现搜索框自动补全功能 随着移动互联网的发展,微信小程序成为了人们生活中不可或缺的一部分。在小程序中,搜索功能是非常常见的需求之一。为了提升用户体验,搜索框的自动补全功能是一个很好的加分项。本文将介绍如何使用微信小程序实现搜索...
    99+
    2023-11-21
    搜索框 微信小程序 自动补全功能
  • 微信小程序实现图片上传功能的思路与源码
    目录前言实现思路:源码文件总结前言 手机上传图片的功能大家一定都用过吧,今天教你用微信小程序实现这个小功能。 实现效果如下: 实现思路: 首先我们需要定义一个存放图片的数组,通过方...
    99+
    2022-11-16
    微信小程序图片上传功能 微信小程序 图片上传 微信小程序如何上传图片
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作