把半径换成以千米为单位的距离
时间: 2024-03-04 13:49:06 浏览: 193
如果要将半径换成以千米为单位的距离,只需要在计算距离时,将计算结果除以1000即可。下面是相应的修改后的代码:
```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) / 1000;
if (distance < minDistance) {
minDistance = distance;
}
}
return minDistance;
}
// 示例数据
const pointLat = 31.2304;
const pointLon = 121.4737;
const circles = [
{ lat: 31.2165, lon: 121.4365, radius: 2000 }, // 单位为米
{ lat: 31.2460, lon: 121.4742, radius: 1000 },
{ lat: 31.2359, lon: 121.5090, radius: 3000 }
];
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 / 1000)) { // 单位为千米
isInCircle = true;
break;
}
}
console.log(`该点${isInCircle ? "在" : "不在"}圆内`);
```
在这个实现中,半径的单位是米,使用时需要除以1000得到千米。另外需要注意的是,在 `checkPointInCircle` 函数中,需要将圆的半径从米转换为千米。
阅读全文