如何使用JxMaps获得2点之间的距离

时间:2018-05-03 12:18:23

标签: java swing jxmaps

在我的应用程序中,我需要在地图上设置路线并获得它的距离 我为此使用 JxMaps ,在地图表单point A上设置路径point 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.");
            }
        }
    });
}

1 个答案:

答案 0 :(得分: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);
            }
        } 
    }
});