所以我在尝试查找RegionCode /坐标状态时遇到了这个问题。我(假设)已经正确实现了来自Maps 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我的问题是我将如何去接收RegionCode字符串甚至地址
JSON
最佳答案
给定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...);