微信小程序计算地球经纬度两点之间的距离
发布于 1 年前 作者 xia26 4677 次浏览 来自 分享

在微信小程序中,如何计算地球经纬度两点之间的距离,不啰七八嗦,直接上代码:

Page({
  data: {
   targetLatitude: xxx,
   targetLongitude: xxx,
  },
  onLoad: function (options) {
    getCurrentLocation();
  },
  getCurrentLocation: function() {
    const { targetLatitude, targetLongitude } = this.data;
    const that = this;
    
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const currentLatitude = res.latitude;
        const currentLongitude = res.longitude;
        const distance = that.calDistance(latitude, longitude, targetLatitude, targetLongitude);
        
        that.setData({
          latitude,
          longitude,
          distance
        });
      }
    });
  },
  calDistance: function (latitude1, longitude1, latitude2, longitude2) {
    var iLatitude1 = latitude1 * Math.PI / 180.0;
    var iLatitude2 = latitude2 * Math.PI / 180.0;
    var xLatitude = iLatitude1 - iLatitude2;
    var xLongitude = longitude1 * Math.PI / 180.0 - longitude2 * Math.PI / 180.0;

    //求地球上两点之间的距离
    var iDistance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(xLatitude / 2), 2) + Math.cos(iLatitude1) * Math.cos(iLatitude2) * Math.pow(Math.sin(xLongitude / 2), 2)));

    //地球半径
    iDistance = iDistance * 6378.137; 
    iDistance = Math.round(iDistance * 10000) / 10000;
    iDistance = iDistance.toFixed(2);
    
    return iDistance;
  },
})

请,大家参考,原文发布在码嗨路书,点击 这里 查看详情,希望此文对您有帮助。

回到顶部