在递归的两点之间获得多个中点

时间:2018-01-19 10:53:22

标签: javascript node.js google-maps express

我有两个坐标,我想找到两个坐标之间的所有中间点。例如
 (x1,y1) = (5,4) and (x2,y2)=(8,7)

我可以找到中间点(x1+x2)/2 = (5+8)/2 = 6.5 and (y1+y2)/2 = (4+7)/2 = 5.5

所以现在我的坐标是

(5, 4)  
(6.5, 5.5)
(8, 7)

预期输出

(5, 4)
(5.75, 4.75)
(6.125, 5.125)
(6.5, 5.5)
(6.875, 5.875)
(7.25, 6.25)
(8, 7)

但我希望在两点之间得到更多的中间点。有没有办法实现它?

修改

var latLong = [];
latLongRes = midpoint(x1, x2, y1, y2, latLong);                              

console.log("latLongRes",latLongRes)  //Get here undefined

function midpoint(x1, x2, y1, y2, latLong) {
    var stepx = (x2-x1)*(x2-x1);
    var stepy = (y2-y1)*(y2-y1);
    var distance = Math.sqrt(stepx + stepy);

    if(distance>0.1){
      mid = computeMidpoint(x1, x2, y1, y2);
      midpoint(x1, mid[0], y1, mid[1], latLong);
      midpoint(mid[0], x2, mid[1], y2, latLong);
    }else{
      var obj = {"latitude":x1,"longitude":y1};
      latLong.push(obj);
      console.log(latLong);  //I am getting here all latlong
      return latLong;
    }

}

function computeMidpoint(x1, x2, y1, y2){
  var mid = [];
  mid.push((x1+x2)/2);
  mid.push((y1+y2)/2);
  return mid;
}

3 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

function midpoint(p1, p2) {
    if (someStoppingConditionHasBeenReached())
        break;
    const mid = computeMidpoint(p1, p2);
    midpoint(p1, mid);
    midpoint(mid, p2);
}

这一切都非常通用。 someStoppingConditionHasBeenReached做什么取决于你。它可以是全局属性,例如enough points have been generateda certain level of precision has been reached(例如p1p2之间的距离小于epsilon)。

答案 1 :(得分:0)

对于线性方法,您可以采用wante点计数并采用线性斜率。



var p1 = [5, 4],
    p2 = [8, 7];
    points = 5,
    result = [p1],
    i = 1;
  
while (i <= points) {
    result.push([
        i * (p2[0] - p1[0]) / (points + 1) + p1[0],
        i * (p2[1] - p1[1]) / (points + 1) + p1[1]
    ]);
    i++;
}
result.push(p2),

console.log(result.map(a => JSON.stringify(a)));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

以下是此任务的简单递归方法

&#13;
&#13;
var p1   = [5,4],
    p2   = [8,7],
    run  = ([x1,y1], [x2,y2], n = 0, m = [(x1+x2)/2, (y1+y2)/2]) => n-- ? run([x1,y1], m, n).concat([m], run(m,[x2,y2],n)) : [];
    mids = (p1,p2,n) => [p1].concat(run(p1,p2,n),[p2]);

console.log(JSON.stringify(mids(p1,p2,3)));
&#13;
&#13;
&#13;

n参数根据2^n定义间隙数。