微信小程序计算两点间距离(经伟度距离)

获取用户位置信息并计算距离

获取用户位置信息使用wx.getLocation函数,求两点间距离:

Page({
 data:{
    },
 onLoad: function() {
        var _this = this;
        _this.findXy() //查询用户与商家的距离
        },
        
   findXy() { //获取用户的经纬度
        var _this = this
        wx.getLocation({
            type: 'wgs84',
            success(res) {
                _this.getDistance(res.latitude, res.longitude, 39.924091,116.403414)
            }
        })
    },
    
     Rad: function(d) { //根据经纬度判断距离
        return d * Math.PI / 180.0;
    },
    getDistance: function(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(2) + '公里' //保留两位小数
        console.log('经纬度计算的距离:' + s)
        return s
    }
    )}

计算一个点到多点的步行、驾车距离

// 引入SDK核心类
var QQMapWX = require('xxx/qqmap-wx.js');
 
// 实例化API核心类
var qqmapsdk = new QQMapWX({
    key: '开发密钥(key)' // 必填
});
 
//在Page({})中使用下列代码
//事件触发,调用接口
formSubmit(e){
    var _this = this;
    //调用距离计算接口
    qqmapsdk.calculateDistance({
        //mode: 'driving',//可选值:'driving'(驾车)、'walking'(步行),不填默认:'walking',可不填
        //from参数不填默认当前地址
        //获取表单提交的经纬度并设置from和to参数(示例为string格式)
        from: e.detail.value.start || '', //若起点有数据则采用起点坐标,若为空默认当前地址
        to: e.detail.value.dest, //终点坐标
        success: function(res) {//成功后的回调
          console.log(res);
          var res = res.result;
          var dis = [];
          for (var i = 0; i < res.elements.length; i++) {
            dis.push(res.elements[i].distance); //将返回数据存入dis数组,
          }
          _this.setData({ //设置并更新distance数据
            distance: dis
          });
        },
        fail: function(error) {
          console.error(error);
        },
        complete: function(res) {
          console.log(res);
        }
    });
}

扩展距离

/**
 * 距离格式化
 * <1000m时 取整,没有小数点
 * >1000m时 单位取km,一位小数点
 */
function formatDistance(num) {
  if (num < 1000) {
    return num.toFixed(0) + '米';
  } else if (num > 1000) {
    return (num / 1000).toFixed(1) + '公里';
  }
}

参考