This Apex class returns a PlaceAutocompleteResponse object.
Usage
String input = 'Amoeba';
String types = 'address';
String components = 'country:GB';
GoogleMapsAutoCompleteAPI api = new GoogleMapsAutoCompleteAPI()
PlaceAutocompleteResponse response = api.getAutoComplete(input, types, components);
Apex GoogleMapsAutoCompleteAPI Class
public class GoogleMapsAutoCompleteAPI {
// Google Maps API Place Autocomplete
// Documentation: https://developers.google.com/places/web-service/autocomplete
public PlaceAutocompleteResponse getAutoComplete(String input, String types, String components) {
String url = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input='
+ EncodingUtil.urlEncode(input, 'UTF-8')
+ '&components=' + components // country:uk'
+ '&types=' + types
+ '&key=' + getGoogleMapsAPIKey();
return PlaceAutocompleteResponse.parse(makeAPICall(url));
}
private string makeAPICall(string url) {
Http http = new Http();
HttpRequest httpRequest = new HttpRequest();
HttpResponse httpResponse = new HttpResponse();
httpRequest.setMethod('GET');
httpRequest.setEndpoint(url);
httpRequest.setTimeout(120000);
httpResponse = http.send(httpRequest);
if (httpResponse.getStatusCode() == 200){
return httpResponse.getBody();
} else {
System.debug(httpResponse.getStatusCode());
System.debug(httpResponse.getBody());
throw new AuraHandledException(httpResponse.getBody());
}
}
private string getAPIKey() {
return ''; // add api key or get from custom settings
}
}
Apex PlaceAutocompleteResponse Class
public class PlaceAutocompleteResponse {
public class Matched_substrings {
public Integer length;
public Integer offset;
}
public String status;
public List<Predictions> predictions;
public class Predictions {
public String description;
public String id;
public List<Matched_substrings> matched_substrings;
public String place_id;
public String reference;
public List<Terms> terms;
public List<String> types;
}
public class Terms {
public Integer offset;
public String value;
}
public static PlaceAutocompleteResponse parse(String json) {
return (PlaceAutocompleteResponse) System.JSON.deserialize(json, PlaceAutocompleteResponse.class);
}
}