EspoirBao
2023-07-10 11:01:57 +08:00
function isCoordinateInsideFence(latitude1, longitude1, latitude2, longitude2) {
const earthRadius = 6371000; // 地球半径,单位为米
// 将经纬度转换为弧度
const lat1Rad = toRadians(latitude1);
const lon1Rad = toRadians(longitude1);
const lat2Rad = toRadians(latitude2);
const lon2Rad = toRadians(longitude2);
// 计算两个坐标点之间的距离
const distance = getDistance(lat1Rad, lon1Rad, lat2Rad, lon2Rad, earthRadius);
// 判断距离是否小于等于 500 米
return distance <= 500;
}
function toRadians(degrees) {
return degrees * Math.PI / 180;
}
function getDistance(lat1, lon1, lat2, lon2, radius) {
const dLat = lat2 - lat1;
const dLon = lon2 - lon1;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = radius * c;
return distance;
}
// 测试
const fenceLatitude = 40.123456; // 围栏中心点的纬度
const fenceLongitude = -74.123456; // 围栏中心点的经度
const testLatitude = 40.123; // 测试点的纬度
const testLongitude = -74.123; // 测试点的经度
const isInside = isCoordinateInsideFence(
fenceLatitude,
fenceLongitude,
testLatitude,
testLongitude
);
console.log(isInside ? '坐标在围栏内' : '坐标不在围栏内');