我有两个坐标,我想找到两个坐标之间的所有中间点。例如
(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;
}
答案 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 generated
或a certain level of precision has been reached
(例如p1
和p2
之间的距离小于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;
答案 2 :(得分:0)
以下是此任务的简单递归方法
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;
n
参数根据2^n
定义间隙数。