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

背景

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

方法封装

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)
}

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


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部