// 查询所有选中的元素
export function selectAllActiveItem() {
// 查询所有选中的元素
const nodes = graph.findAllByState('node', 'selected');
return nodes;
}
// 最短路径
export function shortestpath(data: any) {
let allSelectedNodes = selectAllActiveItem();
if (allSelectedNodes.length != 2) {
return;
}
graph.getNodes().forEach((node: any) => {
// 选择的两点不清除
if (
node.getModel().id == allSelectedNodes[0].getModel().id ||
node.getModel().id == allSelectedNodes[1].getModel().id
) {
graph.setItemState(node, 'hover', true);
} else {
graph.clearItemStates(node);
}
});
// 边
graph.getEdges().forEach((edge: any) => {
graph.clearItemStates(edge);
});
const { findShortestPath }: any = G6.Algorithm; // 算法
// 算法findShortestPath
// 返回:path 为其中一条最短路径,allPath 为所有的最短路径
// 参数:图谱所有节点、边数据,选中的两点的id
const { path, allPath } = findShortestPath(
data,
allSelectedNodes[0].getModel().id,
allSelectedNodes[1].getModel().id
);
if (allPath?.length > 0) {
const pathNodeMap: any = {};
let pathArr = [...new Set(allPath.flat())];
allPath.map((path: any) => {
path.forEach((id: any) => {
const pathNode = graph.findById(id);
let hasEdge = false;
graph.getEdges().forEach((edge: any) => {
// 全路径上有边被删除
const edgeModel = edge.getModel();
const source = edgeModel.source;
const target = edgeModel.target;
if (path.includes(target) && path.includes(source)) {
hasEdge = true;
}
});
if (hasEdge) {
pathNode.toFront();
pathNodeMap[id] = true;
}
});
});
graph.getEdges().forEach((edge: any) => {
const edgeModel = edge.getModel();
const source = edgeModel.source;
const target = edgeModel.target;
const sourceInPathIdx = pathArr.indexOf(source);
const targetInPathIdx = pathArr.indexOf(target);
graph.clearItemStates(edge);
// 路径边清除状态
if (sourceInPathIdx === -1 || targetInPathIdx === -1) {
//
} else {
// 高亮
graph.setItemState(edge, 'hover', true);
}
});
}
}
antv/g6-节点最短路径
最新推荐文章于 2024-05-21 23:21:19 发布