[SalesForce] Google maps api request from apex batch

everyone.

I am trying to run batch, wich will fill the geolocation field on accounts. And for now, i have an issue with http request, that fails.

so, here it is

public static String[] getCoordinates(String commonAddress){ 
  String[] Coordinates; 

  String url = 'https://maps.googleapis.com/maps/api/geocode/json?';
  url += 'address=' + commonAddress; 
  url += '&sensor=false'; 

  system.debug(Logginglevel.ERROR,'GeoUtilitiesCoordinates url: ' + url);    

  Http h = new Http(); 
  HttpRequest req = new HttpRequest();

  req.setMethod('GET');
  req.setEndpoint(url); 

  String responseBody;
  if (!Test.isRunningTest()){ 
  // Methods defined as TestMethod do not support Web service callouts
    HttpResponse res = h.send(req); 
    system.debug('res // ' + res);
    responseBody = res.getBody();
  }
  else {
    // dummy data
    responseBody = '\"location\" : { \"lat\" : 32.0719776,\"lng\" : 34.7914048}';
  } 
  system.debug('responseBody // ' + responseBody);

  /*
     body parsing should be here
  */

  return Coordinates; 
}

The problem is – i have System.HttpResponse[Status=Bad Request, StatusCode=400] in my debug log.

but the request itself
System.HttpRequest[Endpoint=https://maps.googleapis.com/maps/api/geocode/json?address=Nottingham,&sensor=false, Method=GET]

has a correct endpoint and it works fine in browser.

Response body says

Your client has issued a malformed or illegal request. That’s all we know.

What is the problem could be?

Best Answer

In my experience, the error Google is throwing back at you is because the URL wasn't formatted correctly. Most commonly, it's because there was a space in the address variable instead of the plus/+ sign. For example, in your URL let's say it would say:

System.HttpRequest[Endpoint=https://maps.googleapis.com/maps/api/geocode/json?address=Nottingham,+UK&sensor=false, Method=GET]

Instead of

System.HttpRequest[Endpoint=https://maps.googleapis.com/maps/api/geocode/json?address=Nottingham, UK&sensor=false, Method=GET]

I understand in your example that it doesn't show anything past "Nottingham," but I have a feeling this is what is causing your error. Try adding code to replace white space with plus signs and see if it resolves your problem.

Good luck!

EDIT: Keep in mind that using server side geocoding is limited to 5 requests per second, and 2,500 per day without paying for an API key. If you are going to be transcribing more than 5 more second, then you will need to stagger them in batches of 5, at least one second a part from each other.

Related Topic