antv/g6-节点最短路径

// 查询所有选中的元素
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);
      }
    });
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值