Applet ----------- call Gaode map weather api to get weather

Keywords: Javascript Mini Program wechat

1, Use the Gaud weather interface:
The URL link is:

https://lbs.amap.com/api/webservice/guide/api/weatherinfo

(1) Register and get Key
When you use, you need to register for Key, because it is Ali's company, you can use Alipay scan code registration. After registration, click apply key on the page shown in the figure:


Click "create new application" in the upper right corner of the open page and fill in the application name and type. Here, I randomly set the application name as Weather, and click "add" after creation

You can add a name to the Key. The service platform should select Web service to use the weather query API (there is no need to click it here)

After submitting, you can find the Key of the application, and then you can use the API.

 

(2) Call API interface
The interface address, request method, and request parameters are introduced on this page, which should be understood better.
Note that when using wechat developer tool for development, you need to add the website address to the legal domain name of the request. If you only debug without publishing, you can check do not verify the legal domain name, web view (business domain name), TLS version and HTTPS Certificate in the local settings of the developer tool, but such settings cannot be published, Finally, the website address needs to be added to the legal domain name of the request.
According to the request parameters, we need to add Key and city codes. We can test the following first:

After creating a new project, add the following code in index.js (or create a new page):

//index.js
//Get application instance
const app = getApp()

Page({
  data: {
  },
  onLoad:function(){
    var self = this;
    wx.request({
      url: 'https://restapi.amap.com/v3/weather/weatherInfo',
      data:{
        'key': '***************************',//Fill in the Key you applied for
        'city': '120102',
      },
      header:{
        'content-type': 'application/json'
      },
      success:function(res){
        console.log(res.data);
      }
    })
  }
})


The above code will request data from the network after the page is loaded. You can see the returned information in the console:

 

The returned data is described in the api introduction page. The default is the live weather. You can also set the extensions option to all in the request to get the weather information of the current day and the next three days, as shown in the figure:

  Use in the project as shown in the figure:   

  Implementation process:

          First obtain the geographic location authorization, and obtain the weather of the current city according to the city code of the current location

The code is as follows:

 <view class="head">
    <view class="dw" >
      <!-- <image src="../../images/map.png" class="icon-map"></image> -->
      <text>{{city}}</text>
      <image src="../../images/indexdown.png" class="icon-arrow"></image>
    </view>
    <view class="weather">
      <image src="../../images/weather1.png" wx:if="{{weather=='Sunny'}}"></image>
      <image src="../../images/weather2.png" wx:if="{{weather=='Yin'}}"></image>
      <image src="../../images/weather3.png" wx:if="{{weather=='rain'}}"></image>
      <text>{{temperature}}°C Air excellent</text>
    </view>
    <view class="search" bindtap="search">
      <input type="text" placeholder="Search for the items you need" value="" />
      <image src="../../images/search.png" class="icon-search"></image>
    </view>
 </view>

 

/* Top */
  .head{
    display: flex;
    align-items: center;
    /* justify-content: space-between; */
    margin: 30rpx 30rpx 0;
  }
  .head .dw{
    max-width: 133rpx;
    font-size: 26rpx;
    height: 68rpx;
    line-height: 68rpx;
  }
  .head .icon-map{
    width: 29rpx;
    height: 39rpx;
    vertical-align: middle;
    margin-right: 10rpx;
  }
  .head .icon-arrow{
    width: 14rpx;
    height: 8rpx;
    margin-left: 10rpx;
    vertical-align: middle;
  }
  .head .icon-search{
    position: absolute;
    left: 35rpx;
    top: 24rpx;
    width: 24rpx;
    height: 24rpx;
  }
  .head .weather{
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #999999;
    margin: 0 15rpx;
  }
  .head .weather image{
    width: 28rpx;
    height: 28rpx;
    margin-right: 8rpx;
  }
  .head .search{
    position: relative;
    margin-left: auto;
  }
  .head .search input{
    width: 360rpx;
    height: 68rpx;
    line-height: 68rpx;
    background: #F5F5F5;
    border-radius: 50rpx;
    font-size: 24rpx;
    color: #999;
    padding-left: 69rpx;
    box-sizing: border-box;
  }
   
// index.js
// Get application instance
const app = getApp()
var QQMapWX = require('../../utils/qqmap.js');
var qqmapsdk;
Page({
  data: {
    city:'',
    adcode:'',
    weather:'',
    temperature:''
  },
  
  onLoad() {
    
    if(wx.getStorageSync('adcode')){
      this.setData({
        adcode: wx.getStorageSync('adcode')
      })
      this.getWeather();
   
  },
  getWeather() {
    var that = this;
    wx.request({
      url: 'https://restapi.amap.com/v3/weather/weatherInfo',
      data:{
        'key': '***************************',//Fill in the Key you applied for
        'city': that.data.adcode,
      },
      header:{
        'content-type': 'application/json'
      },
      success:function(res){
        that.setData({
          weather: res.data.lives[0].weather,
          temperature: res.data.lives[0].temperature
        })
        console.log(res.data);
      }
    })
  },
  onHide: function()
  {
   
  },
  
  onShow(){
    this.getWeizhi(); 
  },
  //Get location
  getWeizhi() {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: '************************'
    });
    if(!wx.getStorageSync('city')){   //Judge whether there is a city in the cache, No
      
      wx.getSetting({  //Check the authorization first
        success:function(res){
          // var statu = res.authSetting;
          if(res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true){
            wx.showModal({
              title: 'Request authorization current location',
              content: 'You need to obtain your geographic location, please confirm the authorization',
              success: function (res) {
                if (res.cancel) {
                  wx.showToast({
                    title: 'Denial of authorization',
                    icon: 'none',
                    duration: 1000
                  })
                } else if (res.confirm) {
                  wx.openSetting({
                    success: function (dataAu) {
                      if (dataAu.authSetting["scope.userLocation"] == true) {
                        wx.showToast({
                          title: 'Authorization succeeded',
                          icon: 'success',
                          duration: 1000
                        })
                        //Authorize again and call the API of wx.getLocation
                        that.getToLocation()
                      } else {
                        wx.showToast({
                          title: 'privilege grant failed',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    }
                  })
                }
              }
            })
           
          }else{
            that.getToLocation()
          }
        }
      })
      
    }else{   //yes
      that.setData({
        city:wx.getStorageSync('city')
      })
    }
  },
  
  // Get latitude and longitude through wechat
  getToLocation: function () {
    
    let _this = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        // _this.setData({
        //   latitude: res.latitude,
        //   longitude: res.longitude
        // })
        _this.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // Get current geographic location
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res.result);
        let city = res.result.ad_info.city;
        let adcode = res.result.ad_info.adcode;
        console.log(adcode)
        wx.setStorageSync('city', res.result.ad_info.city);
        wx.setStorageSync('adcode', res.result.ad_info.adcode);
        vm.setData({
          city: city,
          adcode: adcode
        })
        vm.getWeather()
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  
  search() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  
  onReady(){
    
  },
})

This article partially cites No negative today Thank you for your article.

That's it!

Posted by madcrazy1 on Thu, 09 Sep 2021 21:07:40 -0700