背景
接着上篇, 我们已经获取到了用户当前的位置坐标, 也知道了打卡的范围, 那么我们就需要计算用户的坐标跟某个地点的坐标之间的距离, 来判断用户是否在打卡范围内.
方法封装
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)
}
🎉🎉
欢迎大家一起讨论学习😊~