Shortest path
This example shows how to use the shortestPath algorithm. A initial path is shown.
Left clicking on a node if will show the shortest path from the central node.
Open in a new window.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../build/ogma.min.js"></script>
<style>
#graph-container {
top: 0;
bottom: 0;
left: 0;
right: 0;
position: absolute;
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="graph-container"></div>
<script>
'use strict';
var ogma = new Ogma({ container: 'graph-container' });
ogma.generate.barabasiAlbert({
nodes: 150
}).then(function (graph) {
ogma.setGraph(graph);
ogma.getNodes().setAttribute('radius', 12);
return ogma.layouts.force({ locate: true });
}).then(function () {
// setup a click listener to seelct new target
ogma.events.onClick(function (event) {
// reset the style
ogma.getNodes().resetAttributes(['color']);
if (event.target.isNode) {
// pick only the first node
findShortestPath(0, event.target.getId());
}
});
findShortestPath(0, 99);
})
function findShortestPath(start, target) {
return ogma.algorithms.shortestPath({ source: start, target: target }).then(function (path) {
// highlight the path found
path.nodes.setAttribute('color', '#86315b');
// mark first and last node of the shorted path
path.nodes.setSelected(true);
path.edges.setSelected(true);
});
}
</script>
</body>
</html>