The uniapp applet obtains the current location and calculates the distance

1. First get the latitude and longitude of the current location

// 存放当前经纬度数据
data(){
    
    
	latitude: 0, // 纬度
	longitude: 0, // 经度
	distance: 0,  // 距离
}
    onLoad(options) {
    
    
      let that = this
      uni.getLocation({
    
    
        success(res) {
    
    
          console.log(res)
          that.latitude = res.latitude  // 将纬度存起来
          that.longitude = res.longitude  // 将经度存起来
        }
      })
    },

2. Then calculate the latitude and longitude obtained from the back-end interface, and just wear it in when calculating

      // 计算距离   
      getDistance(la1, lo1, la2, lo2) {
    
      // 当前的纬度,当前的经度,接口拿到的纬度,接口拿到的经度
        let La1 = la1 * Math.PI / 180.0;
        let La2 = la2 * Math.PI / 180.0;
        let La3 = La1 - La2;
        let Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
        let distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
        distance = distance * 6378.137;
        distance = Math.round(distance * 10000) / 10000;
        return distance;
      },

3. Call it wherever it is used, don't forget to pass parameters

// 接收计算得到的距离
this.distance = this.getDistance(la1, lo1, la2, lo2) // 当前的纬度,当前的经度,接口拿到的纬度,接口拿到的经度
this.distance = Number(this.distance).toFixed(2) // 这一步也可以在上面那行一起写

Guess you like

Origin blog.csdn.net/weixin_44949068/article/details/129146617