Call the current latitude and longitude position of the applet and calculate the distance between two points

Call the public getLocation interface of the applet. This interface can enable high-precision mode, but the returned data may be slower, and this interface can only be called once within about 20 seconds, and cannot be called repeatedly. The calling method is as shown in the figure:

    wx . getLocation ( // get the current latitude and longitude of the applet  

      type: 'gcj02',

      isHighAccuracy: true,

      success(res) {

        that . setData ( // Assign a value to the latitude and longitude

          curLat: res.latitude,

          curLon: res.longitude

        })

As shown in the figure, curLat and curLon are the returned latitude and longitude, and isHighAccuracy means to enable high precision.

If it is required to obtain the latitude and longitude with a high calling frequency, the above API cannot be used, and the other two APIs should be combined to call, namely startLocationUpdate and onLocationChange. Through these two APIs, the API of the current location can be continuously obtained. But this power consumption is higher. After obtaining the latitude and longitude twice, calculate the distance between the two points, and use the method as shown in the figure.

    wx.startLocationUpdate({

      success: (res=> {

        wx.onLocationChange((data=> {

          // Get the current time

          var currentTime = new Date().getTime();

          // Get the last saved location information

          var oldLocation = wx.getStorageSync('oldLocation');

          // Get the time of the last execution

          var oldTime = wx.getStorageSync('oldTime');

          // concatenate latitude and longitude

          var newLocation = data.latitude + "" + data.longitude;

          console . log ( " Updated the calculated distance " ,  newLocation,

            " Accuracy: " ,  data .horizontalAccuracy,  " Distance: " ,  that .data .distance )

          if (currentTime - oldTime > 1000) {

            that . setData ( // Assign a value to the latitude and longitude

              chooseLat: data.latitude,

              chooseLon: data.longitude

            })

            // Calculate the distance

            that.getDistance(

              that.data.chooseLat,

              that.data.chooseLon,

              that.data.curLat,

              that.data.curLon)

            // Cache the current latest position

            wx.setStorageSync('oldLocation', newLocation);

            // Cache the current execution time

            wx.setStorageSync('oldTime', currentTime);

            // Upload the location information to your own code in the background

            // uploadLocation(newLocation);

          }

        });

      },

      fail: (err=> {

        console.log(err);

      }

    })

In the final stage of code execution, the comparison can be made according to whether the locations before and after the cache are the same location and time. Although both are stored in the code, only time is used to control the comparison. After entering the time 1S, call to calculate the latitude and longitude distance method to calculate the actual distance between two points.

  getDistance: function (lat1, lng1, lat2, lng2) {

    var that = this;

    lat1 = lat1 || 0;

    lng1  =  lng1  ||  0 ;

    lat2  =  lat2  ||  0 ;

    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;

    var rad2 = lat2 * Math.PI / 180.0;

    var  a  =  row1  -  row2 ;

    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

    var  r  =  6378137 ;

    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

    that.setData({

      long: distance,

    })

  },

The accuracy of the latter calling method will be affected by indoors and outdoors. Under normal circumstances, the error of obtaining longitude and latitude is 5-15 meters. The above-mentioned method has an accuracy of 35-30 meters indoors, but it is 3-5 meters outdoors, which is very different. Large and not recommended for indoor use.

Finally, attach the address of the file: (the file is also connected to the Tencent map to obtain the current location)

var tools = require('../../utils/tool').default
// 引入SDK核心类,js文件根据自己业务,位置可自行放置
var QQMapWX = require("../../libs/qqmap-wx-jssdk1.2/qqmap-wx-jssdk"); //引入插件
var qqmapsdk; //定义变量(文档那的)
const app = getApp()
Page({
  data: {
    choose: true,
    curLat: 100, // 存纬度的 (手动选择地址后 经纬度重新赋值, 打开地图 要用)
    curLon: 100, //存经度的,
    curCityAddress: '', //当前位置
    long: 10, //距离范围
    chooseLat: 0, //纬度
    chooseLon: 0, //经度
    chazhi: "", //差值
    // ---------------
    bgJigsaw: '',
  },
  onLoad() {},
  onShow() {
    tools.getImageBase64('/static/beijing.png').then(res => {
      this.setData({
        bg: res
      })
    })
    tools.getImageBase64('/static/beijing.png').then(res => {
      this.setData({
        bgJigsaw: res
      })
    })
  },
  chooseMap() {
    var that = this;
    // -------------------------
    wx.startLocationUpdate({
      success: (res) => {
        wx.onLocationChange((data) => {
          //获取当前时间
          var currentTime = new Date().getTime();
          //获取上次保存的位置信息
          var oldLocation = wx.getStorageSync('oldLocation');
          //获取上次执行的时间
          var oldTime = wx.getStorageSync('oldTime');
          //将经纬度拼接
          var newLocation = data.latitude + "" + data.longitude;
          console.log("更新了计算距离", newLocation,
            "精度:", data.horizontalAccuracy, "距离:", that.data.distance)
          if (currentTime - oldTime > 1000) {
            that.setData({ //给经纬度赋个值吧
              chooseLat: data.latitude,
              chooseLon: data.longitude
            })
            //计算距离
            that.getDistance(
              that.data.chooseLat,
              that.data.chooseLon,
              that.data.curLat,
              that.data.curLon)
            //缓存当前最新位置
            wx.setStorageSync('oldLocation', newLocation);
            //缓存当前执行的时间
            wx.setStorageSync('oldTime', currentTime);
          }
        });
      },
      fail: (err) => {
        console.log(err);
      }
    })

    // ------------------------
  },
  getDistance: function (lat1, lng1, lat2, lng2) {
    var that = this;
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
    that.setData({
      long: distance,
    })
  },
  // 点击打开
  checkStart: function () {
    // this.setData({
    //   choose: false
    // })
    // this.chooseMap()
    // var that = this;
    // app.getPermission(that);
    var that = this;
    var locations;
    qqmapsdk = new QQMapWX({
      key: '你的KEY'
    }); //新建实例
    wx.getLocation({ //小程序 的获取当前的位置经纬度 
      type: 'gcj02',
      isHighAccuracy: true,
      success(res) {
        that.setData({ //给经纬度赋个值吧
          curLat: res.latitude,
          curLon: res.longitude
        })
        qqmapsdk.reverseGeocoder({ //腾讯的地图的接口 经纬度查位置 //并没有很精确
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            // 可看文档取自己需要信息  这只取了address
            // that.weather()
            that.setData({
              curCityAddress: addressRes.result.address,
            })
          },
          fail: function (error) {
            console.error(error);
          },
        })
      },
      fail: function (err) {
        console.log(err);
        //失败的时候 可以查查 用户授权情况 
        wx.getSetting();
        //获取用户的当前设置, 返回值中只会出现小程序已经向用户请求过的权限
        wx.getSetting({
          success: function (res) {
            console.log(res);
            // console.log(res.authSetting.scope.userLocation); //可以判断用户是否 取消授权了 以便后续可以再次提醒他授权
            //授权在这不多做讨论
          }
        })
      }
    })
  }
})

What this demo does is to obtain the current location first, and then use the monitoring method to judge the dynamic distance between two points. The key needs to be applied for on the official website, and the whitelist configuration is performed on the enterprise WeChat official website platform.

Tencent location service - based on ecology, connecting to the future (qq.com)

Mini Program (qq.com)

Server domain name settings in development settings

 

APPID applies for its own applet ID, and also imports the address of the file 

 

Guess you like

Origin blog.csdn.net/weixin_51263829/article/details/128946585