如果使用经纬度替代这些坐标呢
时间: 2023-07-11 14:27:44 浏览: 73
经纬度转换坐标
如果使用经纬度进行计算,可以使用地球表面两点之间的Haversine公式来计算两点之间的距离。下面是相应的实现代码:
```javascript
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // 地球半径,单位为千米
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c;
return distance;
}
function checkPointInCircle(lat, lon, circleLat, circleLon, radius) { // 判断点是否在圆内
return calculateDistance(lat, lon, circleLat, circleLon) <= radius;
}
function calculateNearestCircleDistance(lat, lon, circles) { // 计算距离最近的圆的距离
let minDistance = Number.MAX_VALUE;
for (let i = 0; i < circles.length; i++) {
const circle = circles[i];
const distance = calculateDistance(lat, lon, circle.lat, circle.lon) - circle.radius;
if (distance < minDistance) {
minDistance = distance;
}
}
return minDistance;
}
// 示例数据
const pointLat = 31.2304;
const pointLon = 121.4737;
const circles = [
{ lat: 31.2165, lon: 121.4365, radius: 2 },
{ lat: 31.2460, lon: 121.4742, radius: 1 },
{ lat: 31.2359, lon: 121.5090, radius: 3 }
];
console.log(`距离最近的圆的距离为:${calculateNearestCircleDistance(pointLat, pointLon, circles)}`);
let isInCircle = false;
for (let i = 0; i < circles.length; i++) {
const circle = circles[i];
if (checkPointInCircle(pointLat, pointLon, circle.lat, circle.lon, circle.radius)) {
isInCircle = true;
break;
}
}
console.log(`该点${isInCircle ? "在" : "不在"}圆内`);
```
在这个实现中,`calculateDistance` 函数计算了两个坐标之间的距离,使用的是地球表面两点之间的Haversine公式。`calculateNearestCircleDistance` 函数计算了点到最近的圆的距离,而 `checkPointInCircle` 函数则用于判断点是否在某个圆内。
阅读全文