Use Baidu Map Weather API to Develop WeChat Mini Program

2020.11.24 update: The weather data source has been changed, and the hourly forecast and the forecast for the next 6 days have been added.
2020.11.19 update: Since Baidu's API has always been problematic, the positioning method after initial entry has been modified.
2020.11.05 update: Recently, Baidu's API has a problem. The current date always returns to September 16, and there is no life reminder data.


Take a screenshot first:

Screenshot
Screenshot
Screenshot
Screenshot

Mini Program QR Code:

Mini Program QR Code

Complete code: GItHub project address
https://github.com/MichaelLee826/weather_forecast

1. Apply for the AK of Baidu Maps

In Baidu map open platform on registered account and log in, then create an application in the "console" in.
Create application
Select "WeChat Mini Program" and fill in the APP ID obtained when creating the mini program.
Choose WeChat Mini Program
After submitting, you can see the AK of the newly created application on the previous page.

2. Download SDK

Click "WeChat Mini Program JavaScript API" in "Development Documents" and click "
Download SDK
Download All " in "Related Downloads".
Download API
The compressed package mainly includes two folders: demoand src, srcthe js file mainly used in development : bmap-wx.js(For the convenience of explanation, this article does not use it .min).

Three, configure the server domain name

Log in to the WeChat applet management background and enter the development - development settings.
Development settings
In the server domain name , fill in the request legal domain name : https://api.map.baidu.com
Configure server domain name

PS: WeChat requires all domain names to be https, so some APIs whose API is http cannot be used.

Four, write code

Open the WeChat developer tool and create a small program project, and some files will be automatically generated (the method of creating a new project, the role of each file, there are many tutorials on the Internet, so I won't repeat it).

1. Open the index.jsfile and add bmap-wx.jsa reference to the file:

//index.js
//获取应用实例
const app = getApp()
//调用百度地图天气API的js文件
var bmap = require('../../utils/bmap-wx.js'); 

2. In the onLoadmethod, create a new BMapWXobject and fill in AK:

var BMap = new bmap.BMapWX({
    
    
	ak: '你申请的百度地图AK'
});

3. In the onLoadmethod, initiate a request to query the weather:

BMap.weather({
    
    
	fail: fail,
	success: success
});

4. In the onLoadmethod, define the method of query success and failure:

var fail = function(data) {
    
    
	console.log('查询失败')
};
var success = function(data) {
    
    
	console.log('查询成功');
	var currentWeather = data;
	this.setData({
    
    
		currentWeather: currentWeather
	});
}

Note that, setDatain the currentWeatherto and Pagein the dataportion corresponding to:

data: {
    
    
        currentWeather: ''
    },

At this point, the returned weather data can be obtained, and the remaining work is to parse the returned data.

Five, parse the data

In the third step, the returned data obtained by the query successfully dataincludes the information we need to display, so the analysis work is mainly aimed at data.

dataIt mainly includes two parts: currentWeatherand originalData
data
1. The analysis data.currentWeather
structure is as follows: the
data.currentWeather
analysis method is as follows:

var currentWeather = data.currentWeather[0];
	//currentWeather.currentCity:"济南市"
	//currentWeather.date:"周四 01月17日 (实时:3℃)"
	//currentWeather.pm25:"85"
	//currentWeather.temperature:"7 ~ -2℃"
	//currentWeather.weatherDesc:"晴"
	//currentWeather.wind:"南风微风"

Note that data.currentWeatheris a JSON array of critical data exist data.currentWeather[0]in

2, parsing data.originalData
the following structure:
data.originalData
data.originalDatais JSON format, we are concerned about the presence of the data data.originalData.resultsarray, structured as follows:
data.originalData.results
As can be seen, data.originalData.results[0]the array is two key part: indexarrays and weather_dataarrays:
data.originalData.results[0].index
data.originalData.results[0].index[0]a dressing-related information
data.originalData.results[0].index[1]is information related to the car wash
data.originalData.results[0].index[2]is cold-related information
data.originalData.results[0].index[3]is information related to the movement
data.originalData.results[0].index[4]is related to the intensity of UV
data.originalData.results[0].weather_data
data.originalData.results[0].weather_data[0]is today's weather
data.originalData.results[0].weather_data[1]is tomorrow's weather
data.originalData.results[0].weather_data[2]is the weather the day after tomorrow
data.originalData.results[0].weather_data[3]is the day after tomorrow weather

At this point, the data analysis is completed, and the data setDatacan be index.wxmlbound to the variables in it. Amend successas follows:

var success = function(data) {
    
    
	console.log('查询成功');
	//实时天气
	var currentWeather = data.currentWeather[0];
	//感冒信息
	var flu = data.originalData.results[0].index[2];
	//未来三天的天气
	var forecast = new Array(3);
	for (var i = 0; i < 3; i++) {
    
    
		forecast[i] = data.originalData.results[0].weather_data[i + 1];
	}
	//配置数据
	this.setData({
    
    
		currentWeather: currentWeather,
		flu: flu,
		forecast: forecast
	});
}


index.wxmlCall in the file:

<!--当前定位的城市-->
<view class='cityName'>{
   
   {currentWeather.currentCity}}</view>

<!--未来3天的天气情况,包括日期、天气描述、温度范围、风力-->
  <view class='forecast'>
    <view class='next-day' wx:key="{
     
     {index}}" wx:for="{
     
     {forecast}}"> 
      <view class='detail date'>{
   
   {item.date}}</view>
      <view class='detail'>{
   
   {item.weather}}</view>
      <view class='detail'>{
   
   {item.temperature}}</view>
      <view class='detail'>{
   
   {item.wind}}</view>
    </view>
  </view>
  
<!--感冒信息-->
<view class='tips'>   
	<view class='index'>感冒指数:{
   
   {flu.zs}}</view>
	<view class='description'>{
   
   {flu.des}}</view>
</view>

Six, a bmap-wx.jsbrief introduction

Open the bmap-wx.jsfile and you can see that there is only one class BMapWX. This class contains four methods, and what we need to use is the weather(param)method:

/**
* 天气检索
*
* @param {Object} param 检索配置
*/
weather(param) {
    
    
	var that = this;
	param = param || {
    
    };
	let weatherparam = {
    
    
		coord_type: param["coord_type"] || 'gcj02',
        output: param["output"] || 'json',
        ak: that.ak,
        sn: param["sn"] || '',
        timestamp: param["timestamp"] || ''
	};
	let otherparam = {
    
    
		success: param["success"] || function () {
    
    },
		fail: param["fail"] || function () {
    
    }
	};
	let type = 'gcj02';
	let locationsuccess = function (result) {
    
    
		weatherparam["location"] = result["longitude"] + ',' + result["latitude"];
		wx.request({
    
    
			url: 'https://api.map.baidu.com/telematics/v3/weather',
			data: weatherparam,
			header: {
    
    "content-type": "application/json"},
			method: 'GET',
			success(data) {
    
    
				let res = data["data"];
				if (res["error"] === 0 && res["status"] === 'success') {
    
    
					let weatherArr = res["results"];
					// outputRes 包含两个对象,
					// originalData为百度接口返回的原始数据
					// wxMarkerData为小程序规范的marker格式
					let outputRes = {
    
    };
					outputRes["originalData"] = res;
					outputRes["currentWeather"] = [];    
					outputRes["currentWeather"][0] = {
    
    
			 			currentCity: weatherArr[0]["currentCity"],
						pm25: weatherArr[0]["pm25"],
						date: weatherArr[0]["weather_data"][0]["date"],
						temperature: weatherArr[0]["weather_data"][0]["temperature"],
						weatherDesc: weatherArr[0]["weather_data"][0]["weather"],
						wind: weatherArr[0]["weather_data"][0]["wind"]
					};
					otherparam.success(outputRes);
				} else {
    
    
					otherparam.fail({
    
    
						errMsg: res["message"],
						statusCode: res["status"]
					});
				}
			},
			fail(data) {
    
    
				otherparam.fail(data);
			}
		});
	}
	let locationfail = function (result) {
    
    
		otherparam.fail(result);
	}
	let locationcomplete = function (result) {
    
    
	}
	if (!param["location"]) {
    
    
		that.getWXLocation(type, locationsuccess, locationfail, locationcomplete);
	} else {
    
    
		let longitude = param.location.split(',')[0];
		let latitude = param.location.split(',')[1];
		let errMsg = 'input location';
		let res = {
    
    
			errMsg: errMsg,
			latitude: latitude,
			longitude: longitude
		};
		locationsuccess(res);
	}
}

As can be seen, the data is successfully returned data, through parsing, we get packaged in a front data.currentWeatherand data.originalDatatwo arrays.

In addition, the city queried by default in the program is the currently located city, and the parameter is the latitude and longitude coordinates.

weatherparam["location"] = result["longitude"] + ',' + result["latitude"];

If you want to query other cities, such as Beijing, you can modify it to:

weatherparam["location"] = param["北京"];

Among them paramare weather()the parameters of the function.


Welcome to follow my WeChat public account:
Insert picture description here

Guess you like

Origin blog.csdn.net/michael_f2008/article/details/86600399