我正在使用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
设置回调。所以我假设相当接受的问题是回调将被调用并且可以避免
来自Google的com.google.maps.internal.OkHttpPendingResult重试
异常。 现在我不知道如何设置回调,如
我可以看到地理编码的一个例子,如下所示,
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");
}
});
答案 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();
}
}