微信小程序根据两个经纬度获取距离

微信小程序根据两个经纬度获取距离

1,全局获取定位信息

// 获取定位信息
function wxGetLocation (config = {}) {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      // type: 'wgs84',
      type: 'gcj02',
      altitude: false,
      // isHighAccuracy:true,
      ...config,
      success: (res) => {
        resolve(res)
      },
      fail: (error) => {
        reject(error)
      },
    });

  })
}
module.exports = { wxGetLocation }

2,在页面中使用

import { wxGetLocation } from '../utils/util'
//计算方法
rad(d) {
        return d * Math.PI / 180.0;
    },
 // 根据经纬度计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
 getDistances(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;
     var distance = s;
     var distance_str = "";
     if (parseInt(distance) >= 1) {
         distance_str = distance.toFixed(2) + "km";
     } else {
         distance_str = (distance * 1000).toFixed(2) + "m";
     }
     let objData = {
         distance: distance,
         distance_str: distance_str
     }
     return objData
 },
//获取当前经纬度
wxGetLocation().then(
  (res) => {
    // 经纬度
    var latitude = res.latitude
    var longitude = res.longitude
    this.setData({
      latitude,
      longitude
    })
    const distance_str = this.getDistances(latitude,longitude,30.169649,120.270846).distance_str;
    distance_str为带单位的距离
        const distance = this.getDistances(latitude,longitude,30.169649,120.270846).distance_str;
    distance为不带单位的小数距离(可用来排序)
  })
  //模拟排序
list.sort((a, b) => {
        return a.sort - b.sort
    })

希望此文章能帮助到你

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cheng Lucky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值