The front end obtains the user's geographic location

foreword

Positioning is required in many h5/mini programs, especially in some chain stores, charging stations, and shared businesses. In this issue, I will explain how the front-end obtains user positioning.

1. js native geolocation

Prerequisite: HTTPS is required, otherwise the location information will not be obtained when running. Or change to the edge browser. Since the latitude and longitude obtained by this API are not accurate enough, and due to browser compatibility issues, it is rarely used.
The native way of js is actually to use the api of js: navigator. Directly upload the code here, you can run it, this api can only get longitude and latitude

if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition((position) => {
            console.log(position);
            this.$set(this.location, 0, position.coords.longitude);
            this.$set(this.location, 1, position.coords.latitude);
          });
          console.log(this.location);
        } else {
          alert('您的设备不支持定位功能');
        }

2. Third-party maps

The third-party method is mainly to use third-party sdk, such as Baidu map, Gaode map, and Tencent map. I will take Baidu map as an example here. Register Baidu map, get ak,
and introduce it in vue's index.html
image.png

 <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=kz26jZQiN4x1rkRAQhW0vTcnUet34OsD"></script>

Execute the following code on the page to get the city, longitude, latitude

 // 获取当前城市
      const geolocation = new window.BMap.Geolocation();
      geolocation.getCurrentPosition((r) => {
        console.log(r);
        const city = r.address.city; // 返回当前城市
        this.currCity = city;
        this.$set(this.Baidulocation, 0, r.longitude);
        this.$set(this.Baidulocation, 1, r.latitude);
      });

3. Wechat applet sdk positioning

The sdk of getLocation of the WeChat applet is mainly used here. This sdk can be used directly in the developer tools, but if it goes online, you need to submit an application to WeChat in the background of the applet. The application can only be used after the application is approved.
Since I am using uniapp for development, the code of uniapp is posted below.

uniapp uses:

**1.**Add authorization in manifest.json:

 /* 小程序特有相关 */
    "mp-weixin" : {
        "appid" : "wxd012ca2c1cfc762f",
        "requiredPrivateInfos": [
          "getLocation"
        ],
        "permission":{
          "scope.userLocation":{
            "desc":"授权位置信息"
          }
        },
        "setting" : {
            "urlCheck" : false
        },
        "usingComponents" : true
    },

2. Use:

const getLocation = () => {
  uni.getLocation({
    type: 'wgs84',
    success: function (res) {
      console.log(res)
      console.log('当前位置的经度:' + res.longitude)
      submitForm.latitude = res.latitude
      submitForm.longitude = res.longitude
      console.log('当前位置的纬度:' + res.latitude)
    },
  })
}

WeChat Mini Programs use:

It is also divided into two steps, 1. Add configuration to app.json 2. Use it directly without explaining too much here.
You can refer to: https://blog.csdn.net/qq_43886365/article/details/130286822
The official WeChat applet positioning reference Address: https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.getLocation.html

Replenish:

1. Map usage in the applet:

After obtaining the user's latitude and longitude, use the map component (WeChat applet and uniapp are both map components) to pass in the latitude and longitude.

2. Processing after the user refuses authorization in the applet:

Since the WeChat Mini Program adheres to the principle of putting user experience first, the user may refuse to grant you the authorization of getLocation. At this time, the user's location information cannot be obtained, and when re-entering the Mini Program, WeChat is in a certain period of time. The user's authorization status will be recorded within a certain period of time, causing the WeChat authorization page to fail to open. At this time, it is necessary to guide the user to open the settings page to allow the authorization of location information. Here we can refer to the interaction of Didi Chuxing, which is more scientific and reasonable.
When entering for the first time, invoke the location authorization getLocation of WeChat in onLoad.
image.png
If the user allows it, it can be obtained. If the user refuses, the user will be prompted again to enable location. The pop-up box here is written by ourselves.
image.png
The open location inside actually calls the setting page of WeChat, that is, the open-type of the button component is openSetting.
image.png
If the user clicks to open the location, the following is the WeChat guide page (you don’t need to write it yourself), guiding the user to open the location.
image.png
image.png
If the user still clicks cancel, it means that the user really does not want to authorize, and the location information will not be obtained. The map displays a default latitude and longitude information.
Re-entering the applet: If the user rejected the authorization twice when entering the applet last time, then when re-entering the applet, only a bullet box written by ourselves will pop up to guide the user to authorize the location information (the reason is that the authorization of getLocation If you are rejected, even if you call again next time you enter, the authorization pop-up box will not appear, but will tell you that the direct authorization failed)
image.png

Three positioning comparisons

Relatively speaking, it is not good to directly use the native navigator of js, and the accuracy is slightly worse. It is recommended that if it is in a small program or official account h5, then directly use the positioning of the WeChat small program, which has high positioning accuracy. If it is not in the applet or official account h5, then use the third-party map directly.

Map reverse analysis

After the above three positioning methods, it is found that the final results are not bad, only the longitude and latitude, the Chinese of the geographic location information is actually very vague. Therefore, we need to use the address inverse analysis of the third-party map to convert the obtained longitude and latitude into Chinese geographic coordinate information. It is worth mentioning that the WeChat applet uses Tencent Maps by default.

at last

demo address:
native and third-party acquisition: https://github.com/rui-rui-an/getlocation
uniapp acquisition: https://github.com/rui-rui-an/uniappgetlocation

Guess you like

Origin blog.csdn.net/weixin_43239880/article/details/130762172