如何检查一个点是否靠近数组Javascript中的任何其他点



我在这里找到了一个答案,可以确定两点是否基于某个半径彼此靠近:

检查纬度和经度是否在一个圆圈内谷歌地图

这不是我想要的确切答案,因为我想重写这个函数:

function arePointsNear(checkPoint, centerPoint, km) {
var ky = 40000 / 360;
var kx = Math.cos(Math.PI * centerPoint.lat / 180.0) * ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
return Math.sqrt(dx * dx + dy * dy) <= km;
}

能够检查感兴趣的点是否在阵列中任何其他点的特定距离内。这是我迄今为止的尝试,但没有如预期的那样奏效:

function arePointsNear(checkPoint, centerPointArray, km) {
var ky = 40000 / 360;
for (var i = 0; i < centerPointArray.length; i++) {
var kx = Math.cos(Math.PI * centerPointArray[i].lat / 180.0) * ky;
var dx = Math.abs(centerPointArray[i].lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPointArray[i].lat - checkPoint.lat) * ky;
if (Math.sqrt(dx * dx + dy * dy) <= km) {
return true;
} else {
return false;
}
}
}
var centerPointArray = [
{ lat: -42.734358, lng: 147.439506, info: "T" },
{ lat: -42.735258, lng: 147.438000, info: "V" },
{ lat: -43.999792, lng: 170.463352, info: "W" }
]

以下是JS Fiddle:的链接

https://jsfiddle.net/ohb4puj2/3/

打开调试器后,当标记移动到彼此的10KM半径内时,它不会返回所需的结果

使用filter((可以将数组缩小到范围内的位置。

function arePointsNear(checkPoint, centerPoint, km) {
var ky = 40000 / 360;
var kx = Math.cos(Math.PI * centerPoint.lat / 180.0) * ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
return Math.sqrt(dx * dx + dy * dy) <= km;
}
var centerPointArray = [
{ lat: -42.734358, lng: 147.439506, info: "T" },
{ lat: -42.735258, lng: 147.438000, info: "V" },
{ lat: -43.999792, lng: 170.463352, info: "W" }
]

const checkPoint = { lat: -42.5, lng: 147.4 };
const distance = 50;
const withInRange = centerPointArray.filter( function (centerPoint) {
return arePointsNear(checkPoint, centerPoint, distance);
});
console.log(withInRange);

我认为解决方案很简单:只需从for循环中取出return false语句。这样,只有当数组中没有足够近的点时,才会返回false。(现在,如果第一个点不够近,则返回false(

function arePointsNear(checkPoint, centerPointArray, km) {
var ky = 40000 / 360;
for (var i = 0; i < centerPointArray.length; i++) {
var kx = Math.cos(Math.PI * centerPointArray[i].lat / 180.0) * ky;
var dx = Math.abs(centerPointArray[i].lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPointArray[i].lat - checkPoint.lat) * ky;
if (Math.sqrt(dx * dx + dy * dy) <= km)
return true;
}
return false;
}

相关内容

  • 没有找到相关文章

最新更新