Friday, September 22, 2017

Salesforce Lightning: Google Places Autocomplete Predictions Search



I have created a lookup component which on entering few characters of a location will display location predictions.

There are 3 methods that has been defined in client-side controller:
  • keyPressController: executed when the user enters a search key. I have taken into consideration that the user need to enter at least 3 characters to fetch the location predictions.
  • selectOption: executed when the user selects a value from the list box
  • clear: executed on click of cross icon to remove the selected value from the lookup

To fetch the results, I am calling Place Autocomplete service, a part of the Google Places API Web Service, using the below Apex method, which returns location predictions in response to this HTTP request. For more details about this web service, please check the link in the references section of this post.
@AuraEnabled
public static string getAddressAutoComplete(String input, String types) {
    String url = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input='
            + EncodingUtil.urlEncode(input, 'UTF-8')
            + '&types=' + types
            + '&key=' + GoogleMapsController.getGoogleMapsAPIKey();
    return GoogleMapsController.getHttp(url);
}

The response which is in JSON format is parsed in Javascript in the helper method of the component as below:
displayOptionsLocation: function (component, searchKey) {
    var action = component.get("c.getAddressAutoComplete");
    action.setParams({
        "input": searchKey,
        "types": '(regions)'
    });

    action.setCallback(this, function (response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            var options = JSON.parse(response.getReturnValue());
            var predictions = options.predictions;
            var addresses = [];
            if (predictions.length > 0) {
                for (var i = 0; i < predictions.length; i++) {
                    addresses.push(
                        {
                            value: predictions[i].types[0],
                            label: predictions[i].description
                        });
                }
                component.set("v.filteredOptions", addresses);
            }
        }
    });
    $A.enqueueAction(action);
}

The look and feel of this component is controlled by $A.util.addClass and $A.util.removeClass methods.

Please check the github link for the component code below:
https://github.com/iamsonal/GoogleMapsAutocomplete

References:
https://developers.google.com/places/web-service/autocomplete
Share This:    Facebook Twitter

6 comments:

  1. Can you please share the complete apex class?

    ReplyDelete
    Replies
    1. The only Apex method that is of use for the usecase has been provided in the blogpost.

      Delete
    2. Use Below Apex Class:

      public class GoogleMapsController{
      public static string getGoogleMapsAPIKey(){
      string strKey = 'YOUR-KEY';
      return strKey;
      }
      @AuraEnabled
      public static string getAddressAutoComplete(String input, String types) {
      String url = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input='
      + EncodingUtil.urlEncode(input, 'UTF-8')
      + '&types=' + types
      + '&key=' + GoogleMapsController.getGoogleMapsAPIKey();
      return GoogleMapsController.getHttp(url);
      }

      public static string getHttp(string strURL){
      Http h = new Http();
      HttpRequest req = new HttpRequest();
      HttpResponse res = new HttpResponse();
      req.setMethod('GET');
      req.setEndpoint(strURL);
      req.setTimeout(120000);
      res = h.send(req);
      String responseBody = res.getBody();
      return responseBody;
      }
      }

      Delete
  2. Hello Hitesh,

    From where we are generating api key?

    ReplyDelete
    Replies
    1. Register with google for the key

      https://developers.google.com/maps/documentation/javascript/get-api-key

      Delete
  3. I am getting error:
    Failed to save GoogleMapsAutocomplete.cmp: No COMPONENT named markup://c:svg foundresource SLDS cannot be found in namespace .: Source

    ReplyDelete

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top