java持续时间,返回的时间null distancematrix.api

时间:2018-03-15 19:46:15

标签: java google-maps google-distancematrix-api

我对如何使用google distancematrix.api获取持续时间,时间和距离感到困惑。我无法理解什么是不使用我的代码,所有我得到的都是空值。为什么?下面是我的javacode

         DistanceMatrix results1 =  DistanceMatrixApi.getDistanceMatrix(context, 
                new String[] {"rose hill"}, new String[] {"port louis"}).units(Unit.METRIC).await();

    System.out.println(results1.rows[0].elements[0].duration);
    System.out.println(results1.rows[0].elements[0].distance);
    System.out.println(results1.rows[0].elements[0].distance);

请求的上下文

        GeoApiContext context = new GeoApiContext.Builder()
.apiKey("AIzaSyC..")
.build();

1 个答案:

答案 0 :(得分:0)

只需在Google地图上创建(并启用)API密钥

,它对我有用

这是我的代码

public class GoogleDistance {
    public static void main(String[] args) throws InterruptedException, ApiException, IOException {
        new GoogleDistance().go();
    }

    void go() throws InterruptedException, ApiException, IOException {
        String API_KEY = "AIzy....";
        GeoApiContext.Builder builder = new GeoApiContext.Builder();
        builder.apiKey(API_KEY);

        GeoApiContext geoApiContext = builder.build();
        DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(geoApiContext,
                new String[]{"rose hill"}, new String[]{"port louis"}).units(Unit.METRIC).await();
        System.out.println(Arrays.toString(results1.destinationAddresses));
    }
}

我认为问题可能出在你的版画上:我不认为你应该做rows[0].elements[0]只是使用Arrays.toString()。

当我运行我的代码时,它会输出[Port Louis, Mauritius]

修改

我想我现在看到你想要做什么。请看下面的

public class GoogleDistance {
    public static void main(String[] args) throws InterruptedException, ApiException, IOException {
        new GoogleDistance().go();
    }

    void go() throws InterruptedException, ApiException, IOException {
        String API_KEY = "AIzy...";
        GeoApiContext.Builder builder = new GeoApiContext.Builder();
        builder.apiKey(API_KEY);

        GeoApiContext geoApiContext = builder.build();
        DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(geoApiContext,
                new String[]{"los angeles"}, new String[]{"san francisco"}).units(Unit.METRIC).await();


        DistanceMatrixRow[] rows = results1.rows;
        for (DistanceMatrixRow row : rows) {
            DistanceMatrixElement[] elements = row.elements;
            for (DistanceMatrixElement element : elements) {
                Distance distance = element.distance;
                if(distance == null){
                    System.out.println("distance is null");
                    continue;
                }
                String dist = distance.humanReadable;
                String dur = element.duration.humanReadable;
                System.out.println(dist);
                System.out.println(dur);
            }
        }

    }
}

我相信你得到的是因为谷歌不能在你提供的地点之间进行映射。