Tutorial: Java 6 + Maven


Maven library dependencies

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.11.0</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>


Java code

public class App {

  private final OkHttpClient client = new OkHttpClient();

  private final String apiKey = "YOUR-KEY-HERE";

  /**
   * Meta data for the place in the response.
   */
  static class GeolakePlace {
    String countryCode;
    String countryName;
    String currencyCode;
    String timezone;
    String tld;
    String city;
    String zipcode;
    String congrDistrict;
  }

  /**
   * Response from the Geolake API.
   */
  static class GeolakeResponse {
    boolean success;
    BigDecimal latitude;
    BigDecimal longitude;
    String accuracyType;
    Boolean typoCorrected;
    GeolakePlace place;
  }

  /**
   * Run an unstructured query.
   * @param query Unstructured query
   * @return Geolake response
   * @throws IOException
   */
  private GeolakeResponse unstructuredQuery(String query) throws IOException {
    HttpUrl.Builder builder = HttpUrl.parse("https://api.geolake.com/v1/geocode").newBuilder();
    builder.addQueryParameter("api_key", apiKey);
    builder.addQueryParameter("q", query);
    // Instead of q, you could also specify 'ip'
    // For structured addresses, see all components here: https://geolake.com/docs/api#address-components

    Request request = new Request.Builder().url(builder.build()).build();

    Response response = client.newCall(request).execute();
    try {
      if(!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
      }
      GeolakeResponse geolakeResponse = new Gson().fromJson(response.body().string(), GeolakeResponse.class);
      return geolakeResponse;
    } finally {
      response.close();
    }
  }

  /**
   * Run a test.
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    GeolakeResponse response = new App().unstructuredQuery("50 Central Park S, New York City, 10019 NY, US");
    if(response.success) {
      System.out.println("Location: " + response.latitude + "; " + response.longitude);
    } else {
      System.out.println("Not found");
    }
  }

}