Luc Damhuis
Luc Damhuis

Reputation: 31

Getting stuck with reverse geocoding while using maps api in java

So I have this problem where I am trying to find the RegionCode/State of coordinates. I (assume) have correctly implemented the reverse geocoding from maps API. However now I'm stuck at actually doing something with the data. My code is

 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);

So now I have this geocodingApiRequest my question is how would I go about receiving a RegionCode string or even the address JSON

Upvotes: 2

Views: 322

Answers (1)

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

Given the API specification I would expect the following two to work, depending on whether you want synchronous:

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

or asynchronous behaviour

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...);

Upvotes: 1

Related Questions