Abstract: In the previous phase, we introduced the API and interface code compilation of "micro-weather". today we will continue to introduce the logic-Layer Code and the compilation of query code. This article is based on learning small program development from scratch. Abstract: In the previous phase, we introduced the API and interface code compilation of "micro-weather". today we will continue to introduce the logic-Layer Code and the compilation of query code. This article is based on learning small program development from scratch.
Write logic-Layer Code
The initialization data has not been set in index. js, so the specific data is not visible on the interface, which leads to the interface effect 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 relevant business logic code.
1. write data initialization code
A lot of data is written in index. wxml. Therefore, you need to initialize the data in index. js first, and then preview the result 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: 'The temperature difference between day and night is large and it is easy to catch a cold. Please increase or decrease your clothes as appropriate. If you are physically weak, pay attention to protection. ', Yesterday: {date: 'Thursday 17', type: 'Overcast ', fx: 'southwind', fl: 'breeze level', low: 'Low temperature 8℃ ', high: 'high temperature 16 ℃ '}, forecast: [{date: '18 Friday', type: 'Overcast', high: 'high temperature 16 ℃ ', low: 'Low temperature 8 ℃ ', fengxiang: 'southwind', fengli: 'breeze level'}, {date: '18 Friday', type: 'Overcast ', high: 'High temperature 16 ℃ ', low: 'Low temperature 8 ℃', fengxiang: 'southwind ', fengli: 'breeze level'}, {date: '18 Friday', type: 'Overcast ', high: 'high temperature 16 ℃', low: 'Low temperature 8 ℃ ', fengxiang: 'southwind', fengli: 'breeze level'}, {date: '18th Friday', type: 'Overcast ', high: 'high temperature 16 ℃', low: 'Low temperature 8 ℃ ', fengxiang: 'southwind', fengli: 'breeze level'}, {date: '18 Friday', type: 'Overcast ', high: 'high temperature 16 ℃', low: 'Low temperature 8 ℃ ', fengxiang: 'southwind ', fengli: 'breeze level'}]}, today: '2017-11-18 ', city: 'Beijing', // city name inputCity :'', // enter the name of the city to be queried }})
After compiling the above initialization data, save index. js and you can see the following interface effects in the preview area on the left side of the development tool.
The returned JSON format is as follows:
{"Status": 0, "result": {"location": {"lng": 104.06654099999996, "lat": 30.572268897395259}, "formatted_address ": "G4201 (Chengdu Ring Expressway), Wuhou district, Chengdu city, Sichuan province", "business": "", "addressComponent": {"country": "China", "country_code": 0, "province": "Sichuan province", "city": "Chengdu", "district": "Wuhou district", "adcode": "510107", "street ": "G4201 (Chengdu Expressway)", "street_number": "", "direction": "", "distance": ""}, "pois": [], "poiRegions": [], "sematic_description": "108 metres southwest of w6, World Center", "cityCode": 75 }}
In the preceding JSON data, you can use result. addressComponent. city to obtain the city name corresponding to the input longitude and latitude. Therefore, you can obtain the name of the current city in this case.
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] // update current date}); 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. longpolling + '& output = json & pois = 0', data: {}, header: {'content-type': 'application/json'}, success: function (res) {var city = res. data. result. addressComponent. city. replace ('city', ''); // City name self. searchWeather (city); // query weather information of the specified city }})}})},})
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 information for the specified city name:
Wthrcdn.etouch.cn/weather_mini? City = city name
In the preceding interface, the city name does not contain the word "city". for example, you only need to input "Chengdu ".
When this section describes the interface, only the JSON data returned after the interface is successfully executed is viewed. if the input city name is incorrect, the following JSON data is returned:
{ "desc": "invilad-citykey", "status": 1002}
In the program, you can use status to determine whether the data query is successful.
Because the code for querying weather forecast information by City name needs to be called repeatedly, a function is compiled separately to facilitate the query.
// Query weather forecast information by city name
SearchWeather: function (cityName) {var self = this; wx. request ({// weather forecast query interface url: 'http: // wthrcdn.etouch.cn/weather_mini? City = '+ cityName, data :{}, header: {'content-type': 'application/json'}, success: function (res) {if (res. data. status = 1002) // The city does not exist {// The error message wx is displayed. showModal ({title: 'hprompt ', content:' The entered city name is incorrect. please enter it again! ', ShowCancel: false, success: function (res) {self. setData ({inputCity: ''}) ;}} else {var weather = res. data. data; // obtain weather data for (var I = 0; I
In the above code, the obtained date is saved as a string in the format of "Saturday 19". in order to display the date and week in two lines, here we use a small trick, that is, adding two spaces in the full-angle state to the date string, so that the line is automatically broken when the string is displayed.
After writing the above code, save it. on the left side of the development tool, you can see that the current weather data has been obtained, instead of the previously initialized data.
In this way, the main code of this case is completed. However, only the weather information of the user's current location can be displayed. if you want to view the weather in other cities, you still need to write the corresponding query code.
Query weather forecasts
Writing the query code is simple. you only need to get the city name entered by the user and then input the searchWeather function. The specific code is as follows:
// Input event inputing: function (e) {this. setData ({inputCity: e. detail. value}) ;}, // search button bindSearch: function () {this. searchWeather (this. data. inputCity );}
After saving the preceding code, enter the name of the city to be queried in the simulator on the left of the development tool. for example, enter "Sanya" and click "query" to display the weather information of "Sanya.
The above is the details of the "micro-weather" tutorial (II) for mini-program development. For more information, see other related articles in the first PHP community!