How to get distance between 2 points using JxMaps

522 Views Asked by At

In my application I need to set a route on a map and get it's distance.
I'm using JxMaps for this, setting a route on a map form point A to point B works just fine,
I used their example (example below) program to do this, but I don't know how to get a distance of that route. I tried several ideas, but none of them have worked so far.
Should I set coordinates to DirectionsLeg object and calculate the distance somehow?

private void calculateDirection() {
    // Getting the associated map object
    final Map map = getMap();
    // Creating a directions request
    DirectionsRequest request = new DirectionsRequest();
    // Setting of the origin location to the request
    request.setOriginString(fromField.getText());
    // Setting of the destination location to the request
    request.setDestinationString(toField.getText());
    // Setting of the travel mode
    request.setTravelMode(TravelMode.DRIVING);
    // Calculating the route between locations
    getServices().getDirectionService().route(request, new DirectionsRouteCallback(map) {
        @Override
        public void onRoute(DirectionsResult result, DirectionsStatus status) {
            // Checking of the operation status
            if (status == DirectionsStatus.OK) {
                // Drawing the calculated route on the map
                map.getDirectionsRenderer().setDirections(result);
            } else {
                JOptionPane.showMessageDialog(DirectionsExample.this, "Error. Route cannot be calculated.\nPlease correct input data.");
            }
        }
    });
}
1

There are 1 best solutions below

1
On

Each route in the DirectionsResult has a collection of the DirectionLeg objects. To calculate route distance you need to calculate the sum of DirectionLeg distances. Please take a look at the example provided below:

mapView.getServices().getDirectionService().route(request, new DirectionsRouteCallback(map) {

    @Override
    public void onRoute(DirectionsResult result, DirectionsStatus status) {
        if (status == DirectionsStatus.OK) {
            map.getDirectionsRenderer().setDirections(result);

            DirectionsRoute[] routes = result.getRoutes();

            if (routes.length > 0) {
                double distance = 0;
                for (DirectionsLeg leg : routes[0].getLegs())
                    distance += leg.getDistance().getValue();

                System.out.println("distance = " + distance);
            }
        } 
    }
});