实现一个城市天气查询功能的小程序


前言

这是在实训中自己总结的一些经验:

通过微信开发者工具来创造一个小程序,并实现天气查询功能


一、获取API接口信息和数据

在小程序中通过引用外部API接口来获取数据,并展示于前端。我使用的聚合数据API来,在这里并不推荐使用聚合数据(因为注册后需要实名信息,比较复杂并且每日只有十次请求机会)
在这里插入图片描述进入测试后、点击发送请求获取数据
在这里插入图片描述暂时把请求到的JS数据复制到一个文本文件夹中,之后写前端后会使用

{
	"reason":"查询成功!",
	"result":{
		"city":"长沙",
		"realtime":{
			"temperature":"21",
			"humidity":"97",
			"info":"晴",
			"wid":"00",
			"direct":"东北风",
			"power":"2级",
			"aqi":"57"
		},
		"future":[
			{
				"date":"2022-05-08",
				"temperature":"20\/25℃",
				"weather":"中雨转小雨",
				"wid":{
					"day":"08",
					"night":"07"
				},
				"direct":"西北风转南风"
			},
			{
				"date":"2022-05-09",
				"temperature":"18\/25℃",
				"weather":"小雨转大雨",
				"wid":{
					"day":"07",
					"night":"09"
				},
				"direct":"东北风"
			},
			{
				"date":"2022-05-10",
				"temperature":"18\/21℃",
				"weather":"中雨转小雨",
				"wid":{
					"day":"08",
					"night":"07"
				},
				"direct":"北风"
			},
			{
				"date":"2022-05-11",
				"temperature":"19\/24℃",
				"weather":"小雨转中雨",
				"wid":{
					"day":"07",
					"night":"08"
				},
				"direct":"西风转北风"
			},
			{
				"date":"2022-05-12",
				"temperature":"20\/25℃",
				"weather":"小雨",
				"wid":{
					"day":"07",
					"night":"07"
				},
				"direct":"北风"
			}
		]
	},
	"error_code":0
}

二、设计前端CSS样式

1.效果展示图

展示图如下(图片随着数据的变化而变化):
在这里插入图片描述

2.代码部分

wxml部分:

<!-- 天气查询 -->
<view class="function" style="margin-top: 40rpx;">
  <view class="calculate">
     <!--标题-->
     <view class="list">
      <view class="img" bindtap="navigator">
        <image src="../../images/index/edit.png"></image>
      </view>
      <view class="font">
      天气查询
      </view> 
    </view> 
    <view class="splitline1"></view>
    <view class="search"> 
    <picker class="chooseCity" mode="region"  bindchange="chooseCity" value="{{city}}" >
      <image src="../../images/index/city.png" class="cityTip"/>
    </picker>
    <input class="searchInput" value="{{city[1]}}" placeholder="请输入城市名" bindinput="searchInput"/>
    <view class="searchBtnView" bindtap="search">
      <view class="searchBtn" > 搜索</view>
    </view>
    </view>
    <view class="splitline2" wx:if="{{!isGetWeather}}"></view>
    <!-- 显示天气情况 -->
    <view class="weatherView1" wx:if="{{isGetWeather}}" >
      <view class="silver" style="background-image:url('../../images/weather/{{realtime.wid}}.png'); background-repeat:no-repeat; background-size:100% 100%;-moz-background-size:100% 100%;">
              <!-- 显示城市 -->
              <view class="weather-pronvice" >{{city[0]}}</view>
        <view class="weather-city">{{city[1]}}  {{city[2]}}</view>
        <!-- 显示温度、天气质量 -->
        <view class="weather-tem">{{realtime.temperature}}°</view>
        <view class="weather-conditions">{{realtime.info}} | 空气 {{realtime.quality}}</view>
        <!-- 显示风级、相对湿度、体感温度 -->
        <view class="thingView">
          <view class="weather-windView">
            <view class="wind-direction">风级</view>
            <view class="wind-leve">{{realtime.power}}</view>
          </view>
          <view class="splitline3"></view>
          <view class="weather-humidityView">
            <view class="humidity-title">相对湿度</view>
            <view class="humidity-content">{{realtime.humidity}}%</view>
          </view>
          <view class="splitline3"></view>
          <view class="weather-apparentView">
            <view class="apparent-title">体感温度</view>
            <view class="apparent-content">{{realtime.apparent}}°</view>
          </view>
        </view>
      </view>
      <!-- 显示几天天气大致温度 -->
      <view class="weather-day">
        <view class="weather-body">
          <view class="day-title">今天</view>
          <view class="day-icon">
            <image src="{{future[0].img}}"/>
          </view>
          <view class="day-content">{{future[0].weather[0]}}</view>
          <view class="day-tem">最低{{future[0].temperature[0]}}°/最高{{future[0].temperature[1]}}°</view>
        </view>
        <view class="splitline4"></view>
        <view class="weather-body">
          <view class="day-title">明天</view>
          <view class="day-icon">
            <image src="{{future[1].img}}"/>
          </view>
          <view class="day-content">{{future[1].weather[0]}}</view>
          <view class="day-tem">最低{{future[1].temperature[0]}}°/最高{{future[1].temperature[1]}}°</view>
        </view>
        <view class="splitline4"></view>
        <view class="weather-body">
          <view class="day-title">后天</view>
          <view class="day-icon">
            <image src="{{future[2].img}}"/>
          </view>
          <view class="day-content">{{future[2].weather[0]}}</view>
          <view class="day-tem">最低{{future[2].temperature[0]}}°/最高{{future[2].temperature[1]}}°</view>
        </view>
      </view>
    </view>
    <view wx:else style="height: 480rpx;width: auto;text-align: center;">
      <image src="../../images/index/noContent.png" style="width: 350rpx; height: 350rpx;margin-top: 50rpx;"></image>
      <view style="color: gray;">暂无查询结果</view>
    </view>
  </view>
</view>

css部分:

.function{
  margin-top: -100rpx;
  margin-left: auto;
  margin-right: auto;
  width: 670rpx;
  height: auto;
  background-color: #fff;
  border-top-right-radius: 25rpx;
  border-top-left-radius: 25rpx;
  border-bottom-right-radius: 15rpx;
  border-bottom-left-radius: 15rpx;
}
.function .calculate .splitline1{
  width: 100%;
  height: 1rpx;
  background-color: #cecdcd;
  margin-top: 10rpx;
  margin-bottom: 20rpx;
  margin-left: auto;
  margin-right: auto;
}
.function .img image{
  width: 70rpx;
  height: 70rpx;
  margin-top: 15rpx;
  margin-left: 20rpx;
  margin-right: 20rpx;
}
.function .font{
  margin-top: 22rpx;
  font-size: 40rpx;
  font-weight: bold;
}
.function .list{
  display: flex;
  justify-content: left;
}
.search{
  display: flex;
  margin-bottom: 15rpx;
}
.chooseCity{
  align-items: center;
  margin-right: 25rpx;
}
.cityTip{
  margin-left: 15rpx;
  margin-top: 5rpx;
  margin-bottom: 5rpx;
  width: 35rpx;
  height: 35rpx;
}
.searchInput{
  height: 40rpx;
  border-radius: 10rpx;
  align-items: center;
}
.searchBtnView{
  width: 180rpx;
  height: 55rpx;
  background-color: #9fe49f;
  border-radius: 10rpx;
}
.searchBtn{
  margin-top: 6rpx ;
  margin-right: 2rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: 800;
  color: #fff;
}
.function .weatherView1{
  width: auto;
  height: auto;
}
.weatherView1 .silver{
  background-color:silver;
  height: auto;
  border-radius: 15rpx;
}
.weatherView1 .weather-pronvice{ 
  padding-top: 45rpx;
  padding-left: 40rpx;
  color: #fff;
  font-size: 45rpx;
  font-weight: bold;
}
.weatherView1 .weather-city{
  padding-top: 5rpx;
  padding-left: 40rpx;
  color: #fff;
  font-size: 38rpx;
}
.weatherView1 .weather-tem{
  padding-left: 40rpx;
  padding-top: 5rpx;
  color: #fff;
  font-size: 160rpx;
  font-weight: bold;
}
.weatherView1 .weather-conditions{
  padding-left: 40rpx;
  color: #fff;
  font-size: 40rpx;
}
.weatherView1 .thingView{
  padding-top: 100rpx;
  display: flex;
  padding-bottom: 50rpx;
}
.weather-windView .wind-direction{
  padding-left: 55rpx;
  color: #fff;
  font-size: 36rpx;
}
.weather-windView .wind-leve{
  padding-top: 2rpx;
  padding-left: 45rpx;
  color: #fff;
  font-size: 48rpx;
  font-weight: bold;
}
.splitline3{
  margin-left: 55rpx;
  width: 2rpx;
  height: 120rpx;
  background-color: white;
}
.weather-humidityView{
  padding-left: 50rpx;
}
.weather-humidityView .humidity-title{
  color: #fff;
  font-size: 36rpx;
}
.weather-humidityView .humidity-content{
  padding-top: 2rpx;
  padding-left: 24rpx;
  color: #fff;
  font-size: 48rpx;
  font-weight: bold;
}
.weather-apparentView{
  padding-left: 40rpx;
}
.weather-apparentView .apparent-title{
  color: #fff;
  font-size: 36rpx;
}
.weather-apparentView .apparent-content{
  padding-top: 2rpx;
  padding-left: 24rpx;
  color: #fff;
  font-size: 48rpx;
  font-weight: bold;
}
.weather-day{
  background-color: #fff;
  border-radius: 15rpx;
}
.weather-day .weather-body{
  display: flex;
  height: 120rpx;
}
.weather-body .day-title{
  display: flex;
  height: 100%;
  width: 20%;
  align-items: center;
  justify-content: center;
  font-size: 34rpx;
}
.splitline4{
  height: 1rpx;
  width: 98%;
  background-color: rgb(219, 223, 223);
  margin-left: auto;
  margin-right: auto;
}
.weather-body .day-icon{
  display: flex;
  height: 100%;
  width: 10%;
  align-items: center;
  justify-content: center;
}
.day-icon image{
  width: 55rpx;
  height: 55rpx;
}
.weather-body .day-content{
  display: flex;
  height: 100%;
  width: 25%;
  padding-left: 1%;
  padding-right: 1%;
  align-items: center;
  justify-content: center;
  font-size: 34rpx;
}
.weather-body .day-tem{
  padding-left: 4%;
  padding-right: 2%;
  display: flex;
  height: 100%;
  width: 45%;
  align-items: center;
  font-size: 32rpx;
}

前端所使用到的小图标这里就不贴上来了,需要的可以自己去阿里矢量官网下载,免费的,还有就是背景图是在百度扣的

js部分:

const utils = require('../utils/utils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    city:[],
    isGetWeather: false,
    realtime:{},
		future:[]
  },  
  // 获取定位
  chooseCity:function(e){
    this.setData({
      city:e.detail.value,
      isGetWeather:false
    })
  },
  /* 查询天气 */
  searchInput:function(e){
    let arr= this.data.city;
    arr[0]= '';
    arr[1]=e.detail.value;
    this.setData({
      city:arr,
      isGetWeather:false
    })
  },
  search:function(e){
    var that = this;
    if(Object.keys(that.data.city).length>0){
      let choose = that.data.city[1].split("市")[0];
      
      wx.request({
        url: 'http://apis.juhe.cn/simpleWeather/query?key=这里需要修改成自己的key &city=' + choose, 
        success:function(res){
          console.log(res)
          if(res.data.result !=null){
            that.setData({
              realtime:res.data.result.realtime,
              future:res.data.result.future
            })
			//数据处理部分
           if(Object.keys(that.data.realtime).length>0&&Object.keys(that.data.future).length>0){
              let arr1 = that.data.realtime;
              let arr2 = that.data.future;
              let quality;
              if(that.data.realtime.aqi>0&&that.data.realtime.aqi<=50){
                quality = "优"
              }else if(that.data.realtime.aqi>51&&that.data.realtime.aqi<=100){
                quality = "良"
              }else if(that.data.realtime.aqi>101&&that.data.realtime.aqi<=150){
                quality = "轻度污染"
              }else if(that.data.realtime.aqi>151&&that.data.realtime.aqi<=200){
                quality = "中度污染"
              }else if(that.data.realtime.aqi>201&&that.data.realtime.aqi<=300){
                quality = "重度污染"
              }else if(that.data.realtime.aqi>301){
                quality = "严重污染"
              }
              if(that.data.realtime.temperature>0){
                arr1.apparent= parseInt(that.data.realtime.temperature) + 2 
              }else{
                arr1.apparent= parseInt(that.data.realtime.temperature) - 2 
              }
              arr1.wid= utils.formatSole(new Date())
              for(let i=0;i<that.data.future.length;i++){
                let a,b,c;
                a = that.data.future[i].temperature.split("\/");
                b = a[1].split("℃");
                a[1] = b[0];
                arr2[i].temperature = a;
                c = that.data.future[i].weather.split("转")
                arr2[i].weather = c;
                arr2[i].img ="../../images/weather/" +arr2[i].weather[0] +".png";
                that.setData({
                  future:arr2
                })
              }
              arr1.quality = quality;
              that.setData({
                realtime:arr1,
                isGetWeather:true
              })
            }
          } else{
            wx.showModal({
              title:'提示',
              content:res.data.reason,
              showCancel:false
            })
          }
        },
        fail(){
          wx.showModal({
            title:'提示',
            content:'查询失败',
            showCancel:false
          })
        }
      })
     
    } else{
      wx.showModal({
        title:'提示',
        content:'请输入地区',
        showCancel:false
      })
    }
  },
})

3.需要说明的几个点:

1.在pages目录创建一个utils文件夹用于放utils.js文件(用来查询当前时间,返回时间信息)
const utils = require(‘…/utils/utils.js’)所用的文件就是下面这部分代码

const 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()
  return [year,month,day].map(formatNumber).join('-') + ' ' +[hour,minute].map(formatNumber).join(':')
}

const formatNumber = n =>{
  n = n.toString()
  return n[1] ? n: '0' + n
}
const formatDate = date =>{
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year,month,day].map(formatNumber).join('-')
}
const formatSole = date =>{
  const hours = date.getHours();
  let text ;
  if (hours >= 0 && hours <= 6) {
    text = "01";
  } else if (hours > 6 && hours <= 18) {
    text = "00";
  }else if(hours >18&& hours<=24){
    text = "01";
  }
  return text;
}
module.exports = {
  formatTime : formatTime,
  formatDate: formatDate,
  formatSole : formatSole
}

2.使用wx.request来请求外部链接接口需要在微信公众平台设置域名信息以及开发者工具勾选信息,否则将无法查询接口。
勾选如下信息:
在这里插入图片描述
在微信公众平台上,点击开发管理,找到服务器域名,点击修改,然后保存并提交
在这里插入图片描述
在这里插入图片描述在这里插入图片描述3.修改请求地址的key值,改成自己的key就可以使用接口啦
在这里插入图片描述


总结

关于这部分小程序来说,简单的实现了一个请求外部接口API来获取天气数据,并将数据处理后显示在前端界面上,再把样式做的美观一些,需要注意的地方就是图片存储位置需要更改以及图片名称需要更改不然就会报错。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值