DistanceMatrix API的回调函数

时间:2016-03-02 06:19:54

标签: java google-maps

我正在使用Google Distance Matrix API计算不同纬度之间的距离。我正在调用下面提到的相应API

public void computeDistanceAndTime() 
{    
        try 
        {
            DistanceMatrixApiRequest req =     DistanceMatrixApi.newRequest(Context.getContext()).origins(src)
                    .destinations(dst).mode(TravelMode.WALKING);
                DistanceMatrix matrix = req.await();
        }
        catch (OverQueryLimitException o) 
        {
            System.out.println(o.getMessage());
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
}

实际上我想使用setCallback函数DistanceMatrixApiRequest设置回调。所以我假设相当接受的问题是回调将被调用并且可以避免

  

com.google.maps.internal.OkHttpPendingResult重试

来自Google的

异常。 现在我不知道如何设置回调,如

  1. 回叫的签名是什么?
  2. 我们是否需要继承任何类来设置回调
  3. 该功能的参数是什么?
  4. 我假设在调用await函数之前需要调用,我是否正确?
  5. 我可以看到地理编码的一个例子,如下所示,

    req.setCallback(new PendingResult.Callback<GeocodingResult[]>() {
      @Override
      public void onResult(GeocodingResult[] result) {
        // Handle successful request.
      }
    
      @Override
      public void onFailure(Throwable e) {
        // Handle error.
      }
    });
    

    即使我按照类似的方式使用距离矩阵,我也不会成功。

     req.setCallback(new PendingResult.Callback<DistanceMatrix[]>() {
      @Override
      public void onResult(DistanceMatrix[] result) {
        // Handle successful request.
      }
    
      @Override
      public void onFailure(Throwable e) {
            System.out.println("There is a failure in Distance function");
      }
    });
    

1 个答案:

答案 0 :(得分:2)

以下是使用DistanceMatrixApi代替await()进行回调的示例。注意,由于OkHTTP在后台线程上调用回调,我需要使用CountDownLatch

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.maps.DistanceMatrixApi;
import com.google.maps.DistanceMatrixApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.PendingResult;
import com.google.maps.model.DistanceMatrix;

import java.util.concurrent.CountDownLatch;

public class DistanceMatrixApp {
  public static void main(String[] args) throws InterruptedException {
    GeoApiContext context = new GeoApiContext();
    context.setApiKey("[API KEY]");
    DistanceMatrixApiRequest req = DistanceMatrixApi.getDistanceMatrix(context,
    new String[]{"Sydney Town Hall"},
    new String[]{"Parramatta Station"});

    final CountDownLatch latch = new CountDownLatch(1);
    req.setCallback(new PendingResult.Callback<DistanceMatrix>() {
      @Override
      public void onResult(DistanceMatrix result) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(result));
        latch.countDown();
      }

      @Override
      public void onFailure(Throwable e) {
        System.out.println("Exception thrown: "+e);
        latch.countDown();
      }
    });

    // We have to hold the main thread open until callback is called by OkHTTP.
    latch.await();
  }
}