uniapp小程序获取当前定位,计算出距离

1、首先获取当前位置的经纬度

// 存放当前经纬度数据
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、然后从后端接口拿到的经纬度进行计算,计算的时候穿进去就行了

      // 计算距离   
      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、在哪用到就进行调用,别忘了传参数

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

猜你喜欢

转载自blog.csdn.net/weixin_44949068/article/details/129146617