Skip to content

Instantly share code, notes, and snippets.

@SalesforceBobLightning
Last active April 7, 2023 15:30
Show Gist options
  • Save SalesforceBobLightning/4c21befe198dcf78541a8072be0bb6b8 to your computer and use it in GitHub Desktop.
Save SalesforceBobLightning/4c21befe198dcf78541a8072be0bb6b8 to your computer and use it in GitHub Desktop.
Using Google Maps API Place Autocomplete with Salesforce Apex
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);
return httpResponse.getBody();
}
private string getAPIKey() {
return ''; // add api key or get from custom settings
}
}
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment