Home » Java » Java google-maps-services returning NullPointerException

Java google-maps-services returning NullPointerException

Posted by: admin October 26, 2017 Leave a comment

Questions:

I am developing a Web Application, in which a client enters an address which, alongside with alongside with it’s coordinates (latitude/longitude), get persisted in a db.

To get the coordinates, I am using the Java Client for Google Maps Services. For testing purposes I just copied the given example into a test project and added a few details.
When I run the project though, the method which calls the google services throws a NullPointerException.

My GeocodingHandler class:

public class GeocodingHandler {

private static final String API_KEY = "AIza...";
private GeoApiContext context;

public void GeocodingHandler(){
    this.context = new GeoApiContext.Builder()                
            .apiKey(API_KEY)
            .maxRetries(3)
            .retryTimeout(10, TimeUnit.SECONDS)
            .build();
}

public PGpoint resolveAddress(String address) throws ApiException{

    PGpoint p = null;
    try {
        GeocodingResult[] results =  GeocodingApi.geocode(this.context,
                address).await();
        double lat = results[0].geometry.location.lat;
        double lng = results[0].geometry.location.lng;
        p = new PGpoint(lat, lng);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(results[0].addressComponents));

    } catch (InterruptedException ex) {
        Logger.getLogger(GeocodingHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GeocodingHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex) {
        Logger.getLogger(GeocodingHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return p;
}

The returned exception error:

java.lang.NullPointerException
at com.google.maps.PendingResultBase.makeRequest(PendingResultBase.java:80)
at com.google.maps.PendingResultBase.await(PendingResultBase.java:55)
at javatestapp.GeocodingHandler.resolveAddress(GeocodingHandler.java:44)
at javatestapp.JavaTestApp.geo(JavaTestApp.java:41)
at javatestapp.JavaTestApp.main(JavaTestApp.java:24)

The corresponding method(s) which cause the error (can also be found here):

abstract class PendingResultBase<T, A extends PendingResultBase<T, A, R>, R extends ApiResponse<T>>
implements PendingResult<T> {

private final GeoApiContext context;
private final ApiConfig config;
private HashMap<String, String> params = new HashMap<String, String>();
private PendingResult<T> delegate;
private Class<? extends R> responseClass;

protected PendingResultBase(GeoApiContext context, ApiConfig config, Class<? extends R> clazz) {
  this.context = context;
  this.config = config;
  this.responseClass = clazz;
}

@Override
public final void setCallback(Callback<T> callback) {
  makeRequest().setCallback(callback);
}

@Override
public final T await() throws ApiException, InterruptedException, IOException {
  PendingResult<T> request = makeRequest();
  return request.await();
}

@Override
public final T awaitIgnoreError() {
  return makeRequest().awaitIgnoreError();
}

private PendingResult<T> makeRequest() {
  if (delegate != null) {
    throw new IllegalStateException(
        "'await', 'awaitIgnoreError' or 'setCallback' was already called.");
  }
  validateRequest();
  switch (config.requestVerb) {
    case "GET":
      return delegate = context.get(config, responseClass, params);
    case "POST":
      return delegate = context.post(config, responseClass, params);
    default:
      throw new IllegalStateException(
          String.format("Unexpected request method '%s'", config.requestVerb));
  }
}

Am I missing any dependencies or things I have to configure?
Formatting of the address string is “(street) (houseNo), (postcode) (city)”, just as you would type it to search an address.

The only alternative I see so far is to try to get the data by calling the Google Maps Geocoding Api through URL

https://maps.googleapis.com/maps/api/geocode/json?address=ADDRESS&key=MY_API_KEY

and fetch it from the JSON.

Answers: