Philipp Ludwig Philipp Ludwig - 3 years ago 57
C++ Question

How do you access the coordinates in a boost graph topology layout?

I'm trying to create an application which displays a simple graph and since I'm using boost::graph for the underlying data structure, I'd like to use the layouting algorithms available in the library as well.

The answer presented here explains how to use a layout algorithm within the boost library to lay out vertices of graph:
How does the attractive force of Fruchterman Reingold work with Boost Graph Library

But sadly it does not explain how - after the layout has been calculated - the coordinates of the vertices can actually be accessed. Even though we get a vector of positions (or rather points), the float components are private, so that doesn't help. The boost::graph documentation also doesn't address this topic.

So how can simple (X,Y) coordinates of each vertex be retrieved after a layouting algorithm has been applied?

Answer Source

After reviewing the boost graph source code it turned out that this isn't so hard after all. We can use a property map to iterate over the PositionsMap and the [] operator to access the coordinates:

template<typename Graph, typename Positions>
void print_positions(const Graph &g, const Positions &positions) {
    auto index_map = boost::get(boost::vertex_index, graph);

    using PropertyMap = boost::iterator_property_map<Positions::iterator, decltype(index_map)>;
    PropertyMap position_map(positions.begin(), index_map);
    BGL_FORALL_VERTICES(v, graph, Graph) {
        Position pos = position_map[v];
        cout << v << ": " << pos[0] << "|" << pos[1] << endl;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download