Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible to get the total path distance from a pathFinder lookup? #20

Open
Sjoerd82 opened this issue Oct 12, 2020 · 1 comment
Open

Comments

@Sjoerd82
Copy link

I just started using ngraph, it's pretty good. When I try the "Weighted Graph" example from the Readme, I get the correct paths. But to get the total distance I still need to traverse my dataset to lookup the weight of every path? Or is ngraph able to deliver this as part of the result as well (and if so, how???)

I use it in vue.js (webpack), so the code looks slightly different:

        let graphRoads = createGraph();
        graphRoads.addLink('Hobitton', 'Bywater', {weight: 465});
        graphRoads.addLink('Hobitton', 'Overhill', {weight: 500});
        graphRoads.addLink('Bywater', 'Frogmorton', {weight: 450});
        graphRoads.addLink('Bywater', 'Whitfurrows', {weight: 482});
        let pathFinder = path.aStar(graphRoads, {
            // We tell our pathfinder what should it use as a distance function:
            distance(fromNode, toNode, link) {
                // We don't really care about from/to nodes in this case,
                // as link.data has all needed information:
                return link.data.weight;
            }
        });
        let pathThing = pathFinder.find('Hobitton', 'Frogmorton');
        console.log('pathThing',pathThing)

Returns an array of the three nodes, it takes to get from Hobitton to Frogmorton. There is a "data" key, but it's "undefined":


[
   Node {id: "Frogmorton", links: Array(1), data: undefined
   Node {id: "Bywater", links: Array(3), data: undefined
   Node {id: "Hobitton", links: Array(2), data: undefined
]
@bigsu
Copy link

bigsu commented Aug 9, 2023

function findShortestPath(graph, start, end) {
    const pathFinder = npath.aGreedy(graph, {
        distance(fromNode, toNode, link) {
            return link.data.weight;
        }
    });

    const pathResult = pathFinder.find(start, end);
    const shortestPath = pathResult.map(node => node.id.split(',').map(Number));

    let totalLength = 0;
    for (let i = 0; i < pathResult.length - 1; i++) {
        const fromNode = pathResult[i];
        const toNode = pathResult[i + 1];
        const link = graph.getLink(fromNode.id, toNode.id);
        totalLength += link.data.weight;
    }

    return { routelatlon: shortestPath, distance: totalLength };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants