在JavaScript中获取距离另一个点最近的点

5

假设我有一个点,叫做 i,它是

{
  x: 10000,
  y: 10000
}

我还有一些其他的点,以数组的形式表示,类似于:

[{
  x: 35,
  y: 10001
}, {
  x: 2478,
  y: 38
}, ...]

我的问题是如何在JavaScript中获取距离i最近的点?谢谢!


你可以编辑你的问题并提供一些例子和期望的输出。同时请提供你已经尝试过的代码。 - Ajit Kumar
你能展示一下你尝试过什么以及它为何不起作用吗?如果你这样做,StackOverflow上的人们会更愿意提供帮助。 - Khalos
怎么样,用一个循环呢? - melpomene
3个回答

7

通过计算点之间的欧几里得距离,可以减小数组大小,并取距离较小的点。

function distance(p) {
    return Math.sqrt(Math.pow(point.x - p.x, 2) + Math.pow(point.y - p.y, 2))
}

var point = { x: 10000, y: 10000 },
    points = [{ x: 35, y: 10001 }, { x: 2478, y: 38 }],
    closest = points.reduce((a, b) => distance(a) < distance(b) ? a : b);

console.log(closest);


1
你可以使用勾股定理来计算从你的点到数组内每个点的距离。

var myPoint = {
  x: 10000,
  y: 10000
};
var points = [{
  x: 35,
  y: 10001
}, {
  x: 2478,
  y: 38
}];

var minDistance = 10000000;
var closestPoint;
for (var a = 0; a < points.length; a++) {
  distance = Math.sqrt((myPoint.x - points[a].x) * (myPoint.x - points[a].x) + (myPoint.y - points[a].y) * (myPoint.y - points[a].y));
  if (distance < minDistance) {
    minDistance = distance;
    closestPoint = points[a];
  }
}
console.log("The closest point: x="+closestPoint.x+", y="+closestPoint.y);


0

你可以使用一些基本的几何知识来创建一个函数,以获取两点之间的绝对距离,然后循环遍历数组并找到给出最小距离的对象。

let p = {
  x: 10000,
  y: 10000
}

let arr = [{
  x: 35,
  y: 10001
}, {
  x: 2478,
  y: 38
}]

function getDiaDist(point){
  return Math.sqrt(Math.pow(point.x,2) + Math.pow(point.y,2))
}

function getDistance(p1,p2){
  return getDiaDist({x:p1.x - p2.x, y:p1.y - p2.y})
}

function getNearestPoint(arr,point){
  let min = Infinity;
  let result = arr[0]
  arr.forEach(a => {
    let dist = getDistance(a,point);
    if(dist > min){
      min = dist
      result = a;
    }
  })
  return result;
}



console.log(getNearestPoint(arr,p))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接