Home > WeChat Applet > Mini Program Development > 'Micro Weather' Tutorial on WeChat Mini Program Development (2)

'Micro Weather' Tutorial on WeChat Mini Program Development (2)

Y2J
Release: 2017-04-22 17:12:51
Original
2564 people have browsed it

Abstract: In the last issue, we introduced the API and interface code writing of "Micro Weather". Today we continue to introduce the writing of logic layer code and query code. This article is selected from "Learning WeChat Mini Program Development from Scratch".

Writing logic layer code

Since the initialization data has not been set in index.js, the specific data cannot be seen in the interface , which also leads to the effect of the interface not meeting the setting requirements.
Next, write the logic layer code index.js. In order to check the interface design effect, first write the initial data, and then gradually write other related business logic codes in depth.

1 Write data initialization code

A lot of data is written in index.wxml, so it needs to be put in index.js first Initialize and then preview the results in the simulator of the development tool.
Open the index.js file, delete the original content, and rewrite the following code:

Page({  data: {    weather:{      wendu:18,      ganmao:'昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。',      yesterday:{        date:'17日星期四',        type:'阴',        fx:'南风',        fl:'微风级',        low:'低温 8℃',        high:'高温 16℃'
      },      forecast:[
        {          date:'18日星期五',          type:'阴',          high:'高温 16℃',          low:'低温 8℃',          fengxiang:'南风',          fengli:'微风级'
        },{          date:'18日星期五',          type:'阴',          high:'高温 16℃',          low:'低温 8℃',          fengxiang:'南风',          fengli:'微风级'
        },{          date:'18日星期五',          type:'阴',          high:'高温 16℃',          low:'低温 8℃',          fengxiang:'南风',          fengli:'微风级'
        },{          date:'18日星期五',          type:'阴',          high:'高温 16℃',          low:'低温 8℃',          fengxiang:'南风',          fengli:'微风级'
        },{          date:'18日星期五',          type:'阴',          high:'高温 16℃',          low:'低温 8℃',          fengxiang:'南风',          fengli:'微风级'
        }
      ]
    },    today:'2016-11-18',    city:'北京',    //城市名称
    inputCity:'', //输入查询的城市名称
  }
})
Copy after login

After writing the above initialization data, save index.js. You can see the following in the preview area on the left side of the development tool. Interface effect.
          Micro Weather Tutorial on WeChat Mini Program Development (2)   

The above code is very long, mainly because it simulates 5 days of weather data. In fact, when the applet is running, the weather data should be obtained through the API immediately after opening the applet. , so in the above initialization data code, you only need to use the following statement to initialize weather as an empty object, and the attribute data added to weather above can be deleted.

weather:{}
Copy after login

2 Get the city name of the current location

According to the requirements of this case, when the user opens this case, the user’s current location must first be obtained Weather information of the city where the user is currently located. This requires obtaining the name of the city where the user is currently located. To complete this function, several twists and turns are required.
First, you can use the WeChat applet's API to obtain the latitude and longitude of the current geographical location (that is, wx. getLocation). Through this API, you can obtain the latitude and longitude of the user's location.
With the longitude and latitude of the user, you also need to query the city name corresponding to the longitude and latitude. This can be achieved using the Baidu Map interface. The Baidu Map Geocoding API service address is as follows:
 api.map.baidu.com/geocoder/v2/
  Calling this interface requires passing the following parameters.

output: Set the data format returned by the interface to json or xml.

ak: This is a parameter that must be set. It is the key used by users to apply for registration on Baidu. Since v2, the parameter has been changed to "ak", and the parameter in previous versions was "key".

sn: This parameter must be enabled if the verification method of ak used by the user is sn verification.

callback: A callback function that returns the return value in json format through the callback function to implement the jsonp function.

For example, enter the following address in the browser:
api.map.baidu.com/geocoder/v2/ak=ASAT5N3tnHIa4APW0SNPeXN5&location=30.572269,104.066541&output=json&pois=0
Returned JSON format As shown below:

{  "status": 0,  "result": {    "location": {      "lng": 104.06654099999996,      "lat": 30.572268897395259
    },    "formatted_address": "四川省成都市武侯区G4201(成都绕城高速)",    "business": "",    "addressComponent": {      "country": "中国",      "country_code": 0,      "province": "四川省",      "city": "成都市",      "district": "武侯区",      "adcode": "510107",      "street": "G4201(成都绕城高速)",      "street_number": "",      "direction": "",      "distance": ""
    },    "pois": [],    "poiRegions": [],    "sematic_description": "环球中心w6区西南108米",    "cityCode": 75
  }
}
Copy after login

In the above JSON data, the city name corresponding to the incoming latitude and longitude can be obtained through result.addressComponent.city. Therefore, in this case, the name of the city where the user is currently located can be obtained in this way.
Based on the above analysis, write the following code in the onLoad event processing function of index.js:

var util = require('../../utils/util.js');
Page({  data: {
        ……
  },onLoad: function (options) {    this.setData({      today:util.formatTime(new Date()).split(' ')[0]  //更新当前日期
    });    var self = this;
    wx.getLocation({      type: 'wgs84',      success: function (res) {
        wx.request({          url:'http://api.map.baidu.com/geocoder/v2/' + 
             '?ak=ASAT5N3tnHIa4APW0SNPeXN5&location='+
              res.latitude+',' + res.longitude + '&output=json&pois=0',          data: {},          header: {            'Content-Type': 'application/json'
          },          success: function (res) {  var city = res.data.result.addressComponent.city.replace('市','');//城市名称
            self.searchWeather(city);  //查询指定城市的天气信息
          }
        })
      }
    })
  },
})
Copy after login

In the above code, line 1 uses the require import tool method to format the date.

3 Obtain the weather forecast based on the city name

After obtaining the city name, you can use the following interface to obtain the weather forecast for the specified city name Information:
wthrcdn.etouch.cn/weather_mini?city=city name
In the above interface, the city name does not contain the word "city". For example, "Chengdu City" only needs to be passed in "Chengdu".
When introducing this interface earlier in this section, we only looked at the JSON data returned after the interface was successfully executed. If the incoming city name is incorrect, the following JSON data will be returned:

{  "desc": "invilad-citykey",  "status": 1002}
Copy after login

In the program You can use status to determine whether the data query is successful.
Since the code for querying weather forecast information based on city names needs to be called repeatedly, it is written as a separate function to facilitate calling during query.

//Query weather forecast information based on city name

searchWeather:function(cityName){    var self = this;
    wx.request({      //天气预报查询接口
      url: 'http://wthrcdn.etouch.cn/weather_mini?city='+cityName,
      data: {},
      header: {        'Content-Type': 'application/json'
      },
      success: function (res) {        if(res.data.status == 1002) //无此城市
        {            //显示错误信息
            wx.showModal({
              title: '提示',
              content: '输入的城市名称有误,请重新输入!',
              showCancel:false,
              success: function(res) {                self.setData({inputCity:''});
              }
            })
        }else{          var weather = res.data.data;  //获取天气数据
          for(var i=0;i<weather.forecast.length;i++)
          {            var d = weather.forecast[i].date;            //处理日期信息,添加空格
            weather.forecast[i].date = &#39; &#39; + d.replace(&#39;星期&#39;,&#39; 星期&#39;); 
          }          self.setData({
            city:cityName,      //更新显示城市名称
            weather:weather,    //更新天气信息
            inputCity:&#39;&#39;        //清空查询输入框
          })
        }
      }
    })
  }
Copy after login

  在上面代码中,获取的date中保存的是“19日星期六”这种格式的字符串,为了使日期和星期分别显示在两行中,这里使用了一种小技巧,就是在日期字符串中添加了2个全角状态的空格,这样在显示这个字符串时自动断行。
  编写好以上这些代码之后,保存,在开发工具左侧可看到已经获取当前的天气数据,而不是前面初始化的数据了。
                 Micro Weather Tutorial on WeChat Mini Program Development (2)  

这样,本案例的主要代码就算编写完成了。不过,还只能显示用户当前所在地的天气信息,如果要查看其他城市的天气,还需要继续编写相应的查询代码。

查询天气预报

  查询代码的编写很简单,只需要获取用户输入的城市名称,然后传入searchWeather函数即可。具体的代码如下:

//输入事件  
inputing:function(e){    this.setData({inputCity:e.detail.value});
 },  //搜索按钮  bindSearch:function(){    this.searchWeather(this.data.inputCity);  }
Copy after login

  保存以上代码之后,在开发工具左侧模拟器中输入查询的城市名称,如输入“三亚”,单击“查询”按钮,界面中即可显示“三亚”的天气信息。

Micro Weather Tutorial on WeChat Mini Program Development (2)

如果在下方输入框输入一个不存在的城市名称,将显示下面的提示信息。
                 

Micro Weather Tutorial on WeChat Mini Program Development (2)

The above is the detailed content of 'Micro Weather' Tutorial on WeChat Mini Program Development (2). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template