Google Geo ReverseCoding — Java

Helps in finding the address based on Lat, Lng. (Geo Coordinates)

picture from google website

1. Create Context:

private GeoApiContext context;

@PostConstruct
public void init() {
this.context = new GeoApiContext.Builder().apiKey(securityEncoder.decrypt(this.googleKey)).build();
}

You can ignore the Security Encoder and supply the key directly for your testing. @PostConstruct is a spring annotation and you can ignore it if not needed. Maintain only one context across the application is recommended.

2. Synchronous Call:

GeocodingApiRequest request = GeocodingApi.reverseGeocode(context, new LatLng(lat, lng));try {
GeocodingResult[] result = request.await();
String city = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.LOCALITY)
.findFirst()
.get()
.shortName;
String zipcode = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.POSTAL_CODE)
.findFirst()
.get()
.shortName;
String country = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.COUNTRY)
.findFirst()
.get()
.shortName;
String state = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.ADMINISTRATIVE_AREA_LEVEL_1)
.findFirst()
.get()
.shortName;
log.info("--> {}, {} {}, {}", city, state, zipcode, country);
} catch (ApiException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

3. Async Call:

request.setCallback(
new PendingResult.Callback<GeocodingResult[]>() {
@Override
public void onResult(GeocodingResult[] result) {
log.debug("Google Callback Received...");
String city = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.LOCALITY)
.findFirst()
.get()
.shortName;
String zipcode = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.POSTAL_CODE)
.findFirst()
.get()
.shortName;
String country = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.COUNTRY)
.findFirst()
.get()
.shortName;
String state = Arrays
.stream(result[0].addressComponents)
.filter(c -> c.types[0] == AddressComponentType.ADMINISTRATIVE_AREA_LEVEL_1)
.findFirst()
.get()
.shortName;
log.info("--> {}, {} {}, {}", city, state, zipcode, country);
}

@Override
public void onFailure(Throwable e) {
log.error("Google Geo Code Error --> {}", e);
}
}
);

4. build.gradle

implementation group: 'com.google.maps', name: 'google-maps-services', version: '0.18.1'
implementation group: 'com.google.code.geocoder-java', name: 'geocoder-java', version: '0.16'

Find other articles @ my publication: ThinkSpecial

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store