微信小程序通过经纬度计算两点之间距离

小程序中通过经纬度计算两点之间的距离km

1.拾取两地经纬度坐标 。

data:{
   //当前定位位置
    latitude: null,
    longitude: null,
    // 目的地坐标
    latitude2: 116.403119,
    longitude2: 39.913607,
    }

2.当地坐标的获取。

 onLoad: function (options) {
   if (app.globalData.address) {
     this.setData({
       address: app.globalData.address,
     })
   }
   //获取当前位置
   wx.getLocation({
     type: 'gcj02',
     success: (res) => {
       console.log("当前位置:", res)
       const distance_new = this.getDistance(res.latitude, res.longitude, this.data.latitude2,this.data.longitude2);
       console.log(distance_new);
      
       let distances = this.data.productAll.map((item)=>{
         for(let i = 0;i<item.length;i++){
           console.log(i);
           item[i].distance = distance_new;
           console.log(item[i].distance);
         }          
         return item;
       })
       this.setData({
         productAll: distances
       })
       console.log(this.data.productAll);
     }
   })
 },

// map方法的作用不难理解,即“映射”,也就是原数组被“映射”成对应新数组。
3.计算距离函数

 // 计算距离函数
  Rad(d) { 
    //根据经纬度判断距离
    return d * Math.PI / 180.0;
  },
  getDistance(lat1, lng1, lat2, lng2) {
      // lat1用户的纬度
      // lng1用户的经度
      // lat2商家的纬度
      // lng2商家的经度
      var radLat1 = this.Rad(lat1);
      var radLat2 = this.Rad(lat2);
      var a = radLat1 - radLat2;
      var b = this.Rad(lng1) - this.Rad(lng2);
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137;
      s = Math.round(s * 10000) / 10000;
      s = s.toFixed(1) + 'km' //保留两位小数
      console.log('经纬度计算的距离:' + s)
      return s
  },

4.这样就可以计算两点之间的距离了。在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44718678/article/details/107444383