微信小程序-计算两个坐标点之间的距离(附两种解决方案)

一、常见场景

例:
微信小程序-计算两个坐标点之间的距离(附两种解决方案)

  • 外卖距离
  • 地图距离
  • 商家距离
  • 景点距离
  • 司机距离
  • 超出距离检测
  • ···

二、获取当前位置信息(经纬度)

  • 注意:需要在app.json开启位置授权相关
  • app.json ↓
"permission": {
    "scope.userLocation": {
      "desc": "您的位置将在小程序地图上展示"
    }
  },
"requiredPrivateInfos": [
    "getLocation",
    "chooseLocation"
]
  • 获取当前位置信息Api
var that = this
wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        that.setData({
          wd: res.latitude,
          jd: res.longitude
        })
        console.log(that.data.wd);
        console.log(that.data.jd);
      }
})

三、计算方法

方法一、使用哈弗辛公式(换算弧度计算)

  • 可根据上述获取当前位置信息后的经纬度做两点中的其中一点参数,也可以取任意两个点的经纬度作为参数
  • lat1、lng1、lat2、lng2分别为经纬1与经纬2的经纬度
  • 参数-例:this.distance(119,54454, 20.45454, 120,54454, 21.45454)
//根据经纬度计算距离
distance(lat1, lng1, lat2, lng2) {
    var that = this;
    let rad1 = lat1 * Math.PI / 180.0;
    let rad2 = lat2 * Math.PI / 180.0;
    let a = rad1 - rad2;
    let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(
      rad2) * Math.pow(
      Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toString();
    s = s.substring(0, s.indexOf('.') + 2);
    console.log('距离:', s);
    return s; //返回距离
},

方法二、使用欧几里得距离公式(两点直线距离)

  • 可根据上述获取当前位置信息后的经纬度做两点中的其中一点参数,也可以取任意两个点的经纬度作为参数
  • point1、point2分别为经纬1与经纬2的对象
  • 参数-例:this.calculateDistance({x:20.45454,y:119,54454 },{x:21.45454,y:120,54454 })
  // 计算两点之间的距离  
calculateDistance(point1,point2){
    // 计算距离  
    var distance = Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2))* 100;
    // 显示结果  
    console.log(distance , '计算');
  },

原文链接:https://juejin.cn/post/7319903448458969097 作者:加油乐

(0)
上一篇 2024年1月4日 上午11:04
下一篇 2024年1月4日 下午4:05

相关推荐

发表回复

登录后才能评论