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

一、常见场景

例:

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

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

  • 注意:需要在app.json开启位置授权相关
  • app.json ↓
json 复制代码
"permission": {
    "scope.userLocation": {
      "desc": "您的位置将在小程序地图上展示"
    }
  },
"requiredPrivateInfos": [
    "getLocation",
    "chooseLocation"
]
  • 获取当前位置信息Api
javascript 复制代码
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)
ini 复制代码
//根据经纬度计算距离
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 })
javascript 复制代码
  // 计算两点之间的距离  
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 , '计算');
  },
相关推荐
天下无贼!6 分钟前
2024年最新版Vue3学习笔记
前端·vue.js·笔记·学习·vue
Jiaberrr6 分钟前
JS实现树形结构数据中特定节点及其子节点显示属性设置的技巧(可用于树形节点过滤筛选)
前端·javascript·tree·树形·过滤筛选
赵啸林10 分钟前
npm发布插件超级简单版
前端·npm·node.js
罔闻_spider43 分钟前
爬虫----webpack
前端·爬虫·webpack
吱吱鼠叔1 小时前
MATLAB数据文件读写:1.格式化读写文件
前端·数据库·matlab
爱喝水的小鼠1 小时前
Vue3(一) Vite创建Vue3工程,选项式API与组合式API;setup的使用;Vue中的响应式ref,reactive
前端·javascript·vue.js
WeiShuai1 小时前
vue-cli3使用DllPlugin优化webpack打包性能
前端·javascript
Wandra1 小时前
很全但是超级易懂的border-radius讲解,让你快速回忆和上手
前端
ice___Cpu1 小时前
Linux 基本使用和 web 程序部署 ( 8000 字 Linux 入门 )
linux·运维·前端
JYbill1 小时前
nestjs使用ESM模块化
前端