Start Dijkstra Shortest Path using JMapViewer

As mentioned in the last post to JMapViewer, I want to show you how to start the Dijkstra shortest path algorithm using JMapViewer. Based on this Gist, I will briefly explain how to call Dijkstra and visualise the shortest path.

In fact, you just have to add the following code to connect your JMapViewer instance to your Graph:

map().addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1) {
            map().getAttribution().handleAttribution(e.getPoint(), true);
            ICoordinate position = map().getPosition(e.getPoint());

            // save point by using:
            // position.getLat();
            // position.getLon();

            // add a map marker to the map
            map().addMapMarker(new MapMarkerDot(position.getLat(), position.getLon()));

            if (...) {
                // if you have saved two points, then call your Dijkstra
                // dijkstra.getShortestPath(startPoint, endPoint);

                List shortestPath = ; // get list of single nodes between start and end point from dijkstra

                Layer routeLayer = new Layer("Name of your path, so you can hide it later in the map.");
                for (Node node : shortestPath) {
                    // add a marker for each point, so you can visualise the shortest path
                    MapMarkerDot marker = new MapMarkerDot(routeLayer, node.getLat(), node.getLon());
                    map().addMapMarker(marker);
                }
            }
        }
    }
});

Line 1: Adding a mouse listener listens for every mouse click

Line 4: This line checks that the left mouse has been clicked.

Line 5-6: Now you have to retrieve the position of the mouse click.

Line 9-10: With the position, you can get latitude or longitude values. You should store these position information somewhere, e.g. in a class property.

Line 13: In order to support the users view, you should add a MapMarker to the map. This shows the user where he has clicked.

Line 15: If you have stored two points (i.e a user has clicked twice), then you can forward your points to Dijkstra.

Line 17: Calling Dijkstra is done within the if-body.

Line 21-26: If you have retrieved a shortest path, you should the single nodes (points) of the path in the map. This can be established by iterating through the node list and adding a MapMarker for each node.

 

That’s it. Very easy. If you have used a Layer for the path nodes, you can easily show/hide the path in your map. Just (un-)select the layer in your application.