HarmonyOS/OpenHarmony应用开发ets天气预报

2024-06-25 1811阅读

使用工具:DevEco3.1.0.5,SDK9

文章目录

  • 使用ohpm下载三方库axios
  • 高德天气申请自己的key
  • 发送网络请求获取数据
  • 编写UI界面和程序

    前言:

    新版本的DevEco预览器可以使用联网功能了,这就很方便了。

    文中布局不美观,大家不要介意

    完整文件代码下载:src.rar - 蓝奏云


    一、使用ohpm下载三方库axios

    1.首先需要下载和配置ohpm

    官网链接:ohpm使用指导-命令行工具-DevEco Studio使用指南-工具-HarmonyOS应用开发

    2.查看OpenHarmony三方库中心仓

    官网链接:OpenHarmony三方库中心仓

    3.下载和安装第三方库axios

    链接:OpenHarmony三方库中心仓

    需要在项目名称目录下执行

    ohpm install @ohos/axios
    

    HarmonyOS/OpenHarmony应用开发ets天气预报

    二、高德天气申请自己的key

    1.注册账号,进入控制台,新建应用,添加Key

    HarmonyOS/OpenHarmony应用开发ets天气预报

    2.选择服务平台时需要选择Web服务

    HarmonyOS/OpenHarmony应用开发ets天气预报

    3.查看高德官方文档

    链接:天气查询-基础 API 文档-开发指南-Web服务 API | 高德地图API (amap.com)

     4.生成自己的请求网址

    例如:">https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=

    三、发送网络请求获取数据

    1.导入下载的第三方包

    import axios from '@ohos/axios'

    2.发请求,拿数据

     async getTodayData(){
       const data = await axios.get('自己申请的网址')
       console.log(data.data)
    }

     3.分析数据

    HarmonyOS/OpenHarmony应用开发ets天气预报

    四、编写UI界面和程序

    HarmonyOS/OpenHarmony应用开发ets天气预报

    1.纵向布局,分头部,中部,底部

    头部代码:
    //头部
          Column({space:20}){
            Text('阿顾天气1.0')
              .fontSize(25).fontWeight(700).width('100%').textAlign(TextAlign.Center)
            Row(){
              Image(this.posiIco)
                .width(50).height(50).objectFit(ImageFit.Contain)
              //展示获取的城市,2.0版本添加点击事件,可以自主选择地区
              Text(this.address)
                .fontSize(30).fontColor(Color.Black)
            }
          }
          .width('100%').layoutWeight(2).justifyContent(FlexAlign.SpaceAround)
     中部代码:
    Column(){
           //分割线
           Divider().width('100%')
           //今日天气
           Column(){
             Text('今日天气:')
               .fontSize(20).fontWeight(800).width('100%')
             //空占位组件
             Blank()
             Column({space:10}){
               Text('天气情况:'+this.weatherToday)
                 .fontSize(22).fontColor(Color.Brown)
               Image(this.weatherTodayPic)
                 .width(80).height(50).objectFit(ImageFit.Contain)
               Text('气温:'+this.temToday+'°C')
                 .fontSize(22).fontColor(Color.Brown)
             }.width('70%').border({width:1,color:Color.Pink}).margin({bottom:10})
             .borderRadius(30).backgroundColor("#ffbabac1").padding(10)
           }
           .width('100%').layoutWeight(1).padding(10)
           //分割线
           Divider().width('100%')
           //未来三日天气
           Column(){
             Text('未来三日天气:')
               .fontSize(20).fontWeight(800).width('100%')
              List({space:10}){
                ForEach(this.weaArr,(item:weatherTypes,index:Number)=>{
                  //如果index==0,那么根据返回的数据,会渲染今天的天气,所以要排除今日的,渲染未来3日的
                  if(index !== 0){
                    ListItem(){
                      Column({space:10}){
                        Text(item.date)
                          .fontSize(17)
                        Text('白天天气:'+item.dayweather)
                          .fontSize(20).fontColor(Color.Brown)
                        Image(this.judeWeather(item))
                          .width(80).height(50).objectFit(ImageFit.Contain)
                        Text('气温:'+((item.daytemp*1.0+item.nighttemp*1.0)/2)+'°C')//取平均值做温度
                        .fontSize(18).fontWeight(800)
                        Row(){
                          Text('风向:')
                            .fontSize(15).fontColor(Color.Brown)
                          Image(this.windImg)
                            .width(50).height(40).objectFit(ImageFit.Contain)
                            // @ts-ignore
                            .rotate(this.judeWind(item))//图标旋转的角度
                        }
                      }.border({width:1,color:Color.Pink}).padding(10).borderRadius(15).backgroundColor("#ffbabac1")
                    }.margin(20)
                  }
                })
              }.listDirection(Axis.Horizontal)//将list方向改为横向
           }
           .width('100%').layoutWeight(2).padding(10)
         }
          .width('100%').layoutWeight(8)
    底部代码:
    //底部信息区
          Row(){
            Text('信息:天气数据来自于高德天气API@2024.3.21')
              .fontSize(15).fontWeight(500).fontColor("#ffae2e2e").width('100%').textAlign(TextAlign.Center)
          }
          .width('100%').layoutWeight(1)

    2.编写今日天气和未来3日天气的网络请求数据

      //获取今日天气数据
     async getTodayData(){
       const data = await axios.get(this.todayUrl)
       this.weaList = data.data.lives
       //赋值地址,默认北京东城区
       this.address = this.weaList[0].province+'市'+this.weaList[0].city
       //将获取的今日天气情况赋值
       this.weatherToday = this.weaList[0].weather
       //执行函数,判断今日获取的天气情况,动态赋值根据天气情况展示图片
       this.getWeatherTodayPic()
       //将获取的今日温度赋值
       this.temToday = this.weaList[0].temperature
      }
      //获取未来3日的天气数据
      async getLaterData(){
        const data = await axios.get(this.laterUrl)
        //将获取到的数据存入数组中
        this.weaArr = data.data.forecasts[0].casts
      }

     3.编写根据天气情况动态展示图片函数

     //动态判断今日天气情况,根据天气情况动态展示图片
      getWeatherTodayPic(){
        if(this.weatherToday.includes('雨')){
          this.weatherTodayPic = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.xTBpOQF2baaiYA1stR_jDQHaHa?w=175&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7';
        }else if(this.weatherToday.includes('阴')){
          this.weatherTodayPic = 'https://tse2-mm.cn.bing.net/th/id/OIP-C.T4a2oN9ggyuwxQnQBY5c7wHaFi?w=264&h=197&c=7&r=0&o=5&dpr=1.5&pid=1.7';
        }else if(this.weatherToday.includes('晴')){
          this.weatherTodayPic = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.xwmwAj0dteZV-l6hutuGLAHaHa?w=198&h=199&c=7&r=0&o=5&dpr=1.5&pid=1.7'
        }else if(this.weatherToday.includes('多云')){
          this.weatherTodayPic = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.lFiZ9pHlWoMraLRTv4RMSAHaHa?w=169&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7'
        }
      }
      //动态判断未来3日天气情况,展示未来三日的每一天的图片
      judeWeather(item){
        if(item.dayweather == '晴'){
          return this.fineImg
        }else if(item.dayweather.includes('云')){
          return this.cloudImg
        }else if(item.dayweather.includes('雨')){
          return this.rainImg
        }else if(item.dayweather.includes('阴')){
          return this.yinImg
        }
        return this.fineImg
      }

    4.编写判断风向的函数

    //根据返回的数据结果,判断风向,根据东南西北,赋值角度,默认北方向
      judeWind(item){
        if(item.daywind == '东'){
          return this.wind = 90
        }else if(item.daywind == '东北'){
          return this.wind = 45
        }else if(item.daywind == '南'){
          return this.wind = 180
        }else if(item.daywind == '东南'){
          return this.wind = 135
        }else if(item.daywind == '西'){
          return this.wind = 270
        }else if(item.daywind == '西南'){
          return this.wind = 225
        }else if(item.daywind == '西北'){
          return this.wind = 315
        }
        return this.wind = 0
      }

    总结代码

    完整代码如下:

    import axios from '@ohos/axios'
    @Entry
    @Component
    struct Index {
      //请求今日数据的网络地址
      @State todayUrl:string = 'https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=ce1f551fc7d7227efd45ee58fd7887e7'
      //请求未来3日数据的网络地址
      @State laterUrl:string = 'https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=ce1f551fc7d7227efd45ee58fd7887e7&extensions=all'
      //数据显示
      @State message:string = ''
      //查询天气的地址
      @State address:string = ''
      //定位图片链接
      @State posiIco:string = 'https://tse3-mm.cn.bing.net/th/id/OIP-C.62J8FA41P_ftriSbFbw-HgHaHa?w=166&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7'
      //================今日的天气变量=================//
      //接受天气数据的数组
      @State weaList: weatherType[] = []
      //今日天气
      @State weatherToday:string = ''
      //今日天气图片(网络获取)
      @State weatherTodayPic:string = ''
      //今日温度
      @State temToday:string = ''
      //================未来3日的天气变量=================//
      //接受未来3日天气数据的数组
      @State weaArr: weatherTypes[] = []
      //晴天展示的图像
      @State fineImg:string = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.xwmwAj0dteZV-l6hutuGLAHaHa?w=198&h=199&c=7&r=0&o=5&dpr=1.5&pid=1.7'
      //多云展示的图像
      @State cloudImg:string = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.lFiZ9pHlWoMraLRTv4RMSAHaHa?w=169&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7'
      //下雨展示的图像
      @State rainImg:string = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.xTBpOQF2baaiYA1stR_jDQHaHa?w=175&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7'
      //阴天展示的图像
      @State yinImg:string = 'https://tse2-mm.cn.bing.net/th/id/OIP-C.T4a2oN9ggyuwxQnQBY5c7wHaFi?w=264&h=197&c=7&r=0&o=5&dpr=1.5&pid=1.7'
      //风向图标
      @State windImg:string = 'https://img.ixintu.com/upload/jpg/20210523/79f0359886d38d97112c4b78b9107710_26936_800_800.jpg!con'
      //风向角度
      @State wind:number = 0
      aboutToAppear(){
        this.getTodayData()
        this.getLaterData()
      }
      //获取今日天气数据
     async getTodayData(){
       const data = await axios.get(this.todayUrl)
       this.weaList = data.data.lives
       //赋值地址,默认北京东城区
       this.address = this.weaList[0].province+'市'+this.weaList[0].city
       //将获取的今日天气情况赋值
       this.weatherToday = this.weaList[0].weather
       //执行函数,判断今日获取的天气情况,动态赋值根据天气情况展示图片
       this.getWeatherTodayPic()
       //将获取的今日温度赋值
       this.temToday = this.weaList[0].temperature
      }
      //获取未来3日的天气数据
      async getLaterData(){
        const data = await axios.get(this.laterUrl)
        //将获取到的数据存入数组中
        this.weaArr = data.data.forecasts[0].casts
      }
      //动态判断今日天气情况,根据天气情况动态展示图片
      getWeatherTodayPic(){
        if(this.weatherToday.includes('雨')){
          this.weatherTodayPic = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.xTBpOQF2baaiYA1stR_jDQHaHa?w=175&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7';
        }else if(this.weatherToday.includes('阴')){
          this.weatherTodayPic = 'https://tse2-mm.cn.bing.net/th/id/OIP-C.T4a2oN9ggyuwxQnQBY5c7wHaFi?w=264&h=197&c=7&r=0&o=5&dpr=1.5&pid=1.7';
        }else if(this.weatherToday.includes('晴')){
          this.weatherTodayPic = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.xwmwAj0dteZV-l6hutuGLAHaHa?w=198&h=199&c=7&r=0&o=5&dpr=1.5&pid=1.7'
        }else if(this.weatherToday.includes('多云')){
          this.weatherTodayPic = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.lFiZ9pHlWoMraLRTv4RMSAHaHa?w=169&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7'
        }
      }
      //动态判断未来3日天气情况,展示未来三日的每一天的图片
      judeWeather(item){
        if(item.dayweather == '晴'){
          return this.fineImg
        }else if(item.dayweather.includes('云')){
          return this.cloudImg
        }else if(item.dayweather.includes('雨')){
          return this.rainImg
        }else if(item.dayweather.includes('阴')){
          return this.yinImg
        }
        return this.fineImg
      }
      //根据返回的数据结果,判断风向,根据东南西北,赋值角度,默认北方向
      judeWind(item){
        if(item.daywind == '东'){
          return this.wind = 90
        }else if(item.daywind == '东北'){
          return this.wind = 45
        }else if(item.daywind == '南'){
          return this.wind = 180
        }else if(item.daywind == '东南'){
          return this.wind = 135
        }else if(item.daywind == '西'){
          return this.wind = 270
        }else if(item.daywind == '西南'){
          return this.wind = 225
        }else if(item.daywind == '西北'){
          return this.wind = 315
        }
        return this.wind = 0
      }
      build() {
        Column({space:20}){
          //头部
          Column({space:20}){
            Text('阿顾天气1.0')
              .fontSize(25).fontWeight(700).width('100%').textAlign(TextAlign.Center)
            Row(){
              Image(this.posiIco)
                .width(50).height(50).objectFit(ImageFit.Contain)
              //展示获取的城市,2.0版本添加点击事件,可以自主选择地区
              Text(this.address)
                .fontSize(30).fontColor(Color.Black)
            }
          }
          .width('100%').layoutWeight(2).justifyContent(FlexAlign.SpaceAround)
         Column(){
           //分割线
           Divider().width('100%')
           //今日天气
           Column(){
             Text('今日天气:')
               .fontSize(20).fontWeight(800).width('100%')
             //空占位组件
             Blank()
             Column({space:10}){
               Text('天气情况:'+this.weatherToday)
                 .fontSize(22).fontColor(Color.Brown)
               Image(this.weatherTodayPic)
                 .width(80).height(50).objectFit(ImageFit.Contain)
               Text('气温:'+this.temToday+'°C')
                 .fontSize(22).fontColor(Color.Brown)
             }.width('70%').border({width:1,color:Color.Pink}).margin({bottom:10})
             .borderRadius(30).backgroundColor("#ffbabac1").padding(10)
           }
           .width('100%').layoutWeight(1).padding(10)
           //分割线
           Divider().width('100%')
           //未来三日天气
           Column(){
             Text('未来三日天气:')
               .fontSize(20).fontWeight(800).width('100%')
              List({space:10}){
                ForEach(this.weaArr,(item:weatherTypes,index:Number)=>{
                  //如果index==0,那么根据返回的数据,会渲染今天的天气,所以要排除今日的,渲染未来3日的
                  if(index !== 0){
                    ListItem(){
                      Column({space:10}){
                        Text(item.date)
                          .fontSize(17)
                        Text('白天天气:'+item.dayweather)
                          .fontSize(20).fontColor(Color.Brown)
                        Image(this.judeWeather(item))
                          .width(80).height(50).objectFit(ImageFit.Contain)
                        Text('气温:'+((item.daytemp*1.0+item.nighttemp*1.0)/2)+'°C')//取平均值做温度
                        .fontSize(18).fontWeight(800)
                        Row(){
                          Text('风向:')
                            .fontSize(15).fontColor(Color.Brown)
                          Image(this.windImg)
                            .width(50).height(40).objectFit(ImageFit.Contain)
                            // @ts-ignore
                            .rotate(this.judeWind(item))//图标旋转的角度
                        }
                      }.border({width:1,color:Color.Pink}).padding(10).borderRadius(15).backgroundColor("#ffbabac1")
                    }.margin(20)
                  }
                })
              }.listDirection(Axis.Horizontal)//将list方向改为横向
           }
           .width('100%').layoutWeight(2).padding(10)
         }
          .width('100%').layoutWeight(8)
          //底部信息区
          Row(){
            Text('信息:天气数据来自于高德天气API@2024.3.21')
              .fontSize(15).fontWeight(500).fontColor("#ffae2e2e").width('100%').textAlign(TextAlign.Center)
          }
          .width('100%').layoutWeight(1)
        }
        .width('100%').height('100%')
        .backgroundImage('https://tse1-mm.cn.bing.net/th/id/OIP-C.DvKV8H07XleMDFfcVdtoMAAAAA?w=197&h=329&c=7&r=0&o=5&dpr=1.5&pid=1.7')
        .backgroundImageSize({width:'100%',height:'100%'})
      }
    }
    //==================模拟接口类型,便于数组.出来===================//
    //今日天气
    interface weatherType{
      province: string;
      city: string;
      adcode:string;
      weather: string;
      temperature: string;
      winddirection: string;
      windpower: string;
      humidity: string;
      reporttime: string;
      temperature_float: string;
      humidity_float: string;
    }
    //未来3日天气
    interface weatherTypes{
      date: string;
      week: string;
      dayweather: string;
      nightweather: string;
      daytemp: number;
      nighttemp: number;
      daywind:string;
      nightwind: string;
      daypower: string;
      nightpower: string;
      daytemp_float: string;
      nighttemp_float: string;
    }
VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]