0

在我的应用程序中,我需要在地图上设置路线并获取距离。
我为此使用JxMaps,在地图表单上设置路线point Apoint B正常工作,
我使用他们的示例(下面的示例)程序来执行此操作,但我不知道如何获得该路线的距离。我尝试了几个想法,但到目前为止都没有奏效。
我应该将坐标设置为DirectionsLeg对象并以某种方式计算距离吗?

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.");
            }
        }
    });
}
4

1 回答 1

0

DirectionsResult 中的每条路线都有一个 DirectionLeg 对象的集合。要计算路线距离,您需要计算 DirectionLeg 距离的总和。请看下面提供的示例:

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);
            }
        } 
    }
});
于 2018-05-05T07:33:15.883 回答