Skip to content

esign-consulting/google-geocode

Repository files navigation

google-geocode

License: MIT Build status Quality Gate Status Known Vulnerabilities GitHub tag Maven Central

Simple Java library for the Google Geocoding API.

pom.xml

The library is provided through Maven since the release of the version 2.0.0. Starting in the version 3.0.0, it is compiled with Java 11. Just include the following dependency in your pom.xml:

<dependency>
    <groupId>br.com.esign</groupId>
    <artifactId>google-geocode</artifactId>
    <version>3.0.0</version>
</dependency>

Code examples

GoogleGeocode googleGeocode = new GoogleGeocode(your_api_key, address); // the address must not be encoded
String jsonString = googleGeocode.getJsonString(); // may throw IOException

Alternatively, an object representing the Google Geocoding API json response can be returned:

GoogleGeocode googleGeocode = new GoogleGeocode(your_api_key, latitude, longitude); // reverse geocoding
GeocodeResponse geocodeResponse = googleGeocode.getResponseObject(); // may throw IOException

This object is usefull to get the response content:

if (googleResponse.isStatusOK()) {
   String country = getCountryShortName(); // returns the country short name of the first result
   // more code
}

Any result in the list of results can be accessed through two ways:

// returns the formatted address of the third result
// or null if the index is out of bounds
geocodeResponse.setIndex(2);
String formattedAddress = geocodeResponse.getFormattedAddress();

Or

// returns the geometry object of the position in the results list defined by the index parameter
// or null if it is out of bounds
Geometry geometry = geocodeResponse.getGeometry(index);

The Google Geocoding API language parameter can also be defined:

GoogleGeocode googleGeocode = new GoogleGeocode(your_api_key, address);
googleGeocode.setLanguage(GoogleGeocodeLanguage.PORTUGUESE_BRAZIL);

Enjoy! 😄