Last active
May 20, 2018 12:46
-
-
Save SalesforceBobLightning/f78af6294723b8e50bd76f8a63c78030 to your computer and use it in GitHub Desktop.
Using StreetLayerAPI Address AutoComplete in Salesforce Apex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StreetLayerAddressAutoCompleteAPI { | |
// Street Layer: https://streetlayer.com/ | |
// Documentation: https://streetlayer.com/documentation | |
public List<String> getAddressAutoComplete(String input, String countryCode) { | |
string responseData = makeAPICall(input, countryCode); | |
AutoCompleteResponse response = (AutoCompleteResponse)JSON.deserialize(responseData, AutoCompleteResponse.class); | |
List<String> addresses = new List<String>(); | |
if (!response.success){ | |
return addresses; | |
} | |
for(AutoCompleteResponseResults r : response.results){ | |
addresses.add(String.join(r.formatted_address, ', ')); | |
} | |
return addresses; | |
} | |
private string makeAPICall(string input, string countryCode) { | |
String url = 'http://apilayer.net/api/autocomplete' | |
+ '?access_key=' + getAccessKey() | |
+ '&text=' + EncodingUtil.urlEncode(input, 'UTF-8') | |
+ '&country_code=' + countryCode; | |
Http http = new Http(); | |
HttpRequest request = new HttpRequest(); | |
HttpResponse response = new HttpResponse(); | |
request.setMethod('GET'); | |
request.setEndpoint(url); | |
request.setTimeout(120000); | |
response = http.send(request); | |
return response.getBody(); | |
} | |
private String getAccessKey() { | |
return ''; // Add your access key or get it from custom settings | |
} | |
class AutoCompleteResponse { | |
Boolean success; | |
List<AutoCompleteResponseResults> results; | |
} | |
class AutoCompleteResponseResults { | |
AutoCompleteAddress address_components; | |
String[] formatted_address; | |
AutoCompleteCoordinates coordinates; | |
} | |
class AutoCompleteAddress { | |
String country_code_alpha2; | |
String country_code_alpha3; | |
String country; | |
String county; | |
String locality; | |
String postal_code; | |
String region; | |
String street; | |
String housenumber; | |
String neighbourhood; | |
} | |
class AutoCompleteCoordinates { | |
Decimal latitude; | |
Decimal longitude; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment