在java

时间:2018-05-15 09:46:57

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

所以我有这个问题,我试图找到RegionCode /坐标状态。我(假设)已经正确地实现了地图API的反向地理编码。但是现在我一直坚持用数据做某事。我的代码是

 String API_KEY = "AIzaSyABXoV5ktBurLqodVntX6ImhNHOjDBgciQ";

 GeoApiContext apiContext = new GeoApiContext.Builder()
   .apiKey(API_KEY)
   .build();

 LatLng test = new LatLng( -8.96238,-40.68703);
 GeocodingApiRequest geocodingApi = GmapsController.reverseGeocode(apiContext, test);

所以现在我有这个geocodingApiRequest我的qeustion是如何接收RegionCode字符串甚至是地址JSON

1 个答案:

答案 0 :(得分:1)

鉴于API规范,我希望以下两个工作正常,具体取决于您是否需要同步:

GeocodingResult[] results = geocodingApi.await();
for (GeocodingResult result: results) {
  String address = result.formattedAddress;
  // use it or check other fields on `result`
}

或异步行为

class FutureCompletingCallback implements PendingResult.Callback<GeocodingResult[]> {
    final CompletableFuture<GeocodingResult[]> resultsFuture;

    FutureCompletingCallback(CompletableFuture<GeocodingResult[]> resultsFuture) {
         this.resultsFuture = resultsFuture;
    }

    public void onResult(GeocodingResult[] results) {
        resultsFuture.complete(results);
    }

    public void onFailure(Throwable t) {
        resultsFuture.compleExceptionally(t);
    }
}

CompletableFuture<GeocodingResult[]> resultsFuture = new CompletableFuture<>();
geocodingApi.setCallback(new FutureCompletingCallback(resultsFuture));
// collect result synchronously
GeocodingResult[] results = resultsFuture.get()
// OR act asynchronously
resultsFuture.whenComplete(...some action...);