计算两点距离函数javascript
时间: 2023-03-12 20:44:45 浏览: 76
计算两点距离的 JavaScript 函数如下:function distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
相关问题
地球两点距离计算公式 js
要计算地球上两点之间的距离,我们可以使用经纬度坐标来进行计算。在JavaScript中,可以使用Haversine公式来计算地球两点之间的距离。
Haversine公式如下:
d = 2r * arcsin(√sin²((Δlat)/2) + cos(lat1) * cos(lat2) * sin²((Δlon)/2))
其中,d代表地球上两点之间的距离,r代表地球的平均半径(通常为6371公里),lat1和lat2分别为两点的纬度,lon1和lon2分别为两点的经度。
因此,可以通过编写以下的JavaScript函数来计算地球两点距离:
```javascript
function calculateDistance(lat1, lon1, lat2, lon2) {
const r = 6371; //地球的平均半径,单位公里
const dLat = toRadians(lat2 - lat1);
const dLon = toRadians(lon2 - lon1);
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.asin(Math.sqrt(a));
const distance = r * c; //地球两点间的直线距离,单位公里
return distance;
}
function toRadians(degrees) {
return degrees * (Math.PI / 180);
}
// 测试计算距离
const distance = calculateDistance(39.9, 116.4, 31.2, 121.4);
console.log(distance); // 输出406.6,单位公里
```
通过将两点的经纬度作为参数传递给`calculateDistance`函数,可以得到地球上两点之间的直线距离。这个函数先将经纬度转换为弧度,然后根据Haversine公式进行计算,最后返回距离结果。测试结果表明,北京(39.9°N, 116.4°E)和上海(31.2°N, 121.4°E)之间的距离为406.6公里。
用js计算两个点之间的垂直距离
好的,我了解了,下面是用 JavaScript 计算两个点之间的垂直距离的代码:
```javascript
function verticalDistance(x1, y1, x2, y2) {
return Math.abs(y1 - y2);
}
// Example usage
const distance = verticalDistance(0, 0, 0, 4);
console.log(distance); // Output: 4
```
这个函数接受四个参数,分别是两个点的 x 和 y 坐标。在函数内部,我们使用 `Math.abs()` 函数来计算两个点之间的垂直距离,也就是 `y1` 和 `y2` 的绝对值之差。
希望能对你有帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)