uniapp development applet obtains the name of the positioning city according to the longitude and latitude

Posted by wittanthony on Thu, 03 Mar 2022 09:02:13 +0100

1. Preface

If you have been in contact with wechat applets, you know that operations involving some user sensitive information (such as positioning, accessing personal information, etc.) require user authorization. When we use applets, we may also see the scene that the authorization box pops up before an operation, which requires the user's manual authorization before the next operation. Next, the article briefly introduces the authorization mechanism in wechat applet, which is basically self reference Official documents , you can also directly read the official documents for more detailed introduction.

2. General idea

1) Send authorization request to user in advance Uni Authorize: if the user has previously agreed to authorize, a pop-up window will not appear and success will be returned directly; If the user has previously rejected the authorization, this interface will directly enter the failure callback, which is generally combined with Uni Getsetting and uni Opensetting using
2) After authorization, request to obtain the user's geographical location api Uni Getlocation, but for the wechat applet platform, the api does not return the detailed address Chinese description by default, and can only get the longitude and latitude About Uni getLocation
3) Using the key generated by the web service of Gaode map, the specific city name is further generated by longitude, latitude and key value
Get key from Gaode map

3. On the manifest JSON configure permission

uni.authorize's scope The permission of userlocation needs to be in manifest JSON configure permission, otherwise the following prompt will pop up

The pop-up prompt above needs to be in manifest Add the following code to JSON

    /* Applet specific correlation */
    "mp-weixin" : {
        "permission" : {
          "scope.userLocation": {
            "desc": "Your location information will be used for positioning"
           }         
        }
    },

4. Specific code

 onLoad() {
 // When the page is loaded, judge whether the user has authorized the geographical location. If not, guide the user to set the page for manual authorization
   this.getAuthorize()
 }
 methods: {
  // User authorization
    getAuthorize() {
      const _this = this
      uni.authorize({
        scope: 'scope.userLocation', // Get the required parameters of geographic information. See the document for other parameters
        success(res) {
          _this.getLocation()
        },
        // privilege grant failed
        fail(err) {
          uni.showModal({
            title: 'reminder',
            content: 'Unable to get the current location, please turn on the authorization manually',
            success: function (res) {
              if (res.confirm) {
                console.log('The user clicks OK')
                uni.openSetting({
                  success(res) {
                    if (res.authSetting['scope.userLocation']) {
                      console.log('Open authorization settings location')
                      _this.getLocation()
                    }
                  },
                })
              } else if (res.cancel) {
                console.log('The user clicks cancel')
              }
            },
          })
        },
      })
    },
    // Get the geographical location of the user,
    getLocation() {
      const _this = this
      uni.getLocation({
        type: 'wgs84',
        altitude: true,
        success(res) {
         //The applet can only obtain the longitude and latitude of the location. It needs to use the inverse analytical address of Gaode map to display the specific Chinese city name
          _this.loadCity(res.longitude, res.latitude)
        },
      })
    },
    // Longitude and latitude to specific city
    // 1) Need to use the reverse geocoding of Gaode map
    // 2) The latitude and longitude of the current geographic location is required
    // 3) key value of applet
    loadCity(longitude, latitude) {
      const _this = this
      uni.request({
        header: {
          'Content-Type': 'application/text',
        },
        //Note: the key value here needs the key generated by the web service of Gaode map. Only the web service has inverse geocoding
        url:
          'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' +
          longitude +
          ',' +
          latitude +
          '&key=' +
          _this.key +
          '&radius=1000&extensions=all',
        success(res) {
          if (res.statusCode === 200) {
            _this.cityName = res.data.regeocode.addressComponent.city
            console.log('Get Chinese Street location successfully', _this.cityName)
          } else {
            console.log('Failed to get information, please try again!')
          }
        },
      })
    }
 }
   


5. Summary

Since wechat applet will only apply for authorization from the user once, the subsequent authorization records will be kept, and the user's refusal of authorization will lead to the failure of relevant API calls, we need to consider the user's refusal of authorization. Taking the API for obtaining location information as an example, this paper introduces how to deal with this situation in wechat applet. For other permissions, the logic is similar, mainly including two steps:
1. Judge whether the user has refused the authorization.
2. If the user refuses authorization, jump to the applet setting page to guide the user to authorize manually.
In addition, the onLoad function is used to judge whether the user has authorized the geographical location. The purpose is that the user has not set the manual authorization according to the guidance. The demand behind the page depends on the location positioning. In order to obtain the geographical location, the user guides the authorization in the life cycle onLoad

Just some of my own understanding. If there is a more elegant method, you are welcome to give advice and make common progress~

Reference article:
Processing method of user refusing authorization in wechat applet
After the user of uni app wechat applet refuses the authorization, the authorization page is restarted
The uniapp wechat applet obtains the current location and obtains the provincial and urban areas according to the longitude and latitude

Topics: Front-end Vue.js Mini Program uni-app