Javascript中循环内的实时路径查找
我正在尝试使用d3可视化起点和终点之间的路径。每次单击鼠标时,它都会更新网格/地图,并执行Javascript中循环内的实时路径查找,javascript,d3.js,Javascript,D3.js,我正在尝试使用d3可视化起点和终点之间的路径。每次单击鼠标时,它都会更新网格/地图,并执行visPath()函数 我正在使用Pathfinding.JS库 var pathLoc = [[],[],[],[]]; // This is a global variable gets updated with the `updateMap` function function visPath(){ var grid = new PF.Grid(pathMatrix); var f
visPath()
函数
我正在使用Pathfinding.JS库
var pathLoc = [[],[],[],[]]; // This is a global variable gets updated with the `updateMap` function
function visPath(){
var grid = new PF.Grid(pathMatrix);
var finder = new PF.AStarFinder();
pathData = [];
if(pathLoc[0].length > 0 && pathLoc[2].length > 0) {
setTimeout(function () {
pathLoc[0].forEach(function (d) {
pathLoc[2].forEach(function (dd) {
var gridBackup = grid.clone();
var path = finder.findPath(d[0], d[1], dd[0], dd[1], grid);
grid = gridBackup;
console.log(path);
pathData.push(path);
});
});
pathData.forEach(function (d) {
d.forEach(function (dd) {
d3.selectAll("g.rID" + dd[0] + " rect.w" + dd[1]).attr("fill", "#f00");
});
})
}, 2000); //Without the timeout, pathData is always empty. However, with this I only get few paths, not all of them, and not all the time.
}
}
我认为pathData
在finder.findPath()
完成路径查找之前,会推送path
,最终得到一个空数组
此处可能有帮助的其他功能:
// Example of data passed to updateMap() function
// the map could look something like this:
mapData = [
[1, 1, 1, 1, 1,1, 1, 1, 1, 1,1],
[1,12,13,21,22,1,12,13,21,22,1],
[1,31,51,51,31,1,33,51,51,32,1],
[1,21,51,51,42,1,23,51,51,42,1],
[1,13,41,42,21,1,13,41,42,21,1],
[2, 2, 2, 2, 2,2, 2, 2, 2, 2,2],
[1,12,13,21,22,1,12,13,21,22,1],
[1,31,51,51,31,1,31,51,51,31,1],
[1,21,51,51,42,1,21,51,51,42,1],
[1,13,41,42,21,1,13,41,43,21,1],
[1, 1, 1, 1, 1,1, 1, 1, 1, 1,1]
]
function updateMap(data){
pathLoc = [[],[],[],[]];
//check the type of each cell (residential, commercial...etc.)
data.forEach(function(d,i){
d.forEach(function(dd,ii){
var dString = dd.toString();
var dNum = +dString.charAt(0);
var lNum = +dString.charAt(1);
if(dString.length>1){ // This means it's not a street/road
// update pathMatrix map, which will be used by Pathfinding
pathLoc[dNum-1].push([i,ii]);
pathMatrix[i][ii] = 0;
if(dNum==4){ //Recreational
// not important now
}
}
})
});;
}
var pathMatrix = [
[0,0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,1,1,1,1,0,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0,0]
];
任何帮助都将不胜感激。从您的代码中,我甚至看不到变量
pathLoc
,如果所讨论的代码不全在这里,任何人应该如何假定来帮助您?\u-我更新了代码pathLoc
包含一个源和目标的数组。现在,我使用pathLoc[0]
作为源数组,每个源数组都有[x,y]
值,pathLoc[2]
作为目标数组,每个目标数组都有[x,y]
值,对应于pathMatrix数据。