我正在尝试使用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 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
在path
完成查找路径之前推动finder.findPath()
,我最终得到一个空数组。
其他可能有帮助的功能:
// 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]
];
任何帮助都将不胜感激。