微信小程序-根据经纬度判断范围(计算距离)的方法

该文章介绍了一种方法,用于根据用户当前的经纬度坐标和预设的打卡范围坐标,计算两者之间的距离,以判断用户是否在打卡范围内。通过getCoordinateScopeStatusData和getDistanceByCoordinate两个函数,实现了基于经纬度的距离计算并提供了判断用户是否在指定半径内的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

接着上篇, 我们已经获取到了用户当前的位置坐标, 也知道了打卡的范围, 那么我们就需要计算用户的坐标跟某个地点的坐标之间的距离, 来判断用户是否在打卡范围内.

方法封装

function getCoordinateScopeStatusData(
  referenceCoordinate,
  currentCoordinate,
  scopeNum,
  callback
) {
  var scopeNumber = scopeNum || 500;

  var checkInfo = {
    status: false,
  };

  var distanceValue = getDistanceByCoordinate(
    currentCoordinate,
    referenceCoordinate
  );

  checkInfo.status = true;
  checkInfo.scope_status = distanceValue < scopeNumber;
  checkInfo.cur_coordinte = currentCoordinate;

  callback && callback(checkInfo);

  return distanceValue
}

function getDistanceByCoordinate(location_1, location_2) {
  // longitude(经度) and latitude(纬度)
  var lon_1 = location_1.longitude;
  var lat_1 = location_1.latitude;
  var lat_2 = location_2.latitude;
  var lon_2 = location_2.longitude;
  var radEarth = 6378137;

  var radLat1 = (lat_1 * Math.PI) / 180.0;
  var radLat2 = (lat_2 * Math.PI) / 180.0;
  var radLon1 = (lon_1 * Math.PI) / 180.0;
  var radLon2 = (lon_2 * Math.PI) / 180.0;

  var difRadLat = radLat1 - radLat2;
  var difRedLon = radLon1 - radLon2;

  var distance =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(difRadLat / 2), 2) +
        Math.cos(radLat1) *
        Math.cos(radLat2) *
        Math.pow(Math.sin(difRedLon / 2), 2)
      )
    );
  distance = distance * radEarth;
  distance = Math.round(distance * 10000) / 10000;
  return distance; // 返回(m)
}

module.exports = getCoordinateScopeStatusData

如何使用?

const checkDistance = require('../scripts/tool/checkDistance');

// ...
// 判断打卡范围
checkClockRange() {
  // 需要计算距离的目标坐标
  const referenceCoordinate = {
    latitude: xxxxxx,
    longitude: xxxxxx
  }
  // 用户的坐标
  const currentCoordinate = {
    latitude: xxxxxx,
    longitude: xxxxxx
  }
  // 两点之间的距离
  const currentRange = checkDistance(referenceCoordinate, currentCoordinate);

  return currentRange <= this.data.punchRange;  // this.data.punchRange为打卡的范围(单位: m)
}

🎉🎉
欢迎大家一起讨论学习😊~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值