how do you use the google geocode and timezone api with the official java library?

Viewed 408

I know how to make calls in the old-fashioned way where I'm basically just constructing a string which is the full url of the request and then sending that off for a response.

However, google has this library for java available (https://developers.google.com/api-client-library/java) and I would like to use it. However, I can't find examples on their github sample page relating to how to use geocode or timezone APIs.

What examples they do have for other services seems really complex. I just want to see a basic example of how you construct and make a call and get a response using my API key.

In pseudocode what I want to do is:

String location = "123 main street, new york, ny";
String response = // send location plus my API key to google geocoder
// now have a json file response that I can deserialize?
1 Answers

I would suggest having a look at the Java Client for Google Maps Services an official library of Google Maps team that you can find on GitHub and there are some basic examples of using it.

In the Readme.md file you will find instructions how to add this library to your project via Maven or Gradle.

The code snippet to use the library with Geocoding API is the following

GeoApiContext context = new GeoApiContext.Builder()
            .apiKey("YOUR_API_KEY")
            .build();
String location = "123 main street, new york, ny";
try {
    GeocodingApiRequest req = GeocodingApi.newRequest(context);
    GeocodingResult[] results = req.address(address).await();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String jsonResults = gson.toJson(results);
} catch(ApiException e){
    //Handle API exceptions here
}   

The code snippet for Time Zone API is the following

GeoApiContext context = new GeoApiContext.Builder()
            .apiKey("YOUR_API_KEY")
            .build();
LatLng location = new LatLng(41.385064,2.173403);
java.util.TimeZone result = TimeZoneApi.getTimeZone(context, location).await();

For further details on classes and methods of the library you can refer to JavaDoc located at

https://www.javadoc.io/doc/com.google.maps/google-maps-services/latest/index.html

Enjoy!

Related