Skip to content

Instantly share code, notes, and snippets.

@LokeshSagi
Last active March 28, 2020 11:19
Show Gist options
  • Save LokeshSagi/c0f1e9acc397fa7b2401cf418849a9ba to your computer and use it in GitHub Desktop.
Save LokeshSagi/c0f1e9acc397fa7b2401cf418849a9ba to your computer and use it in GitHub Desktop.
<template>
<template if:true={sitePrediction}>
<li onclick={handlePredictionSelect} role="presentation" class="slds-listbox__item">
<div class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta"
role="option">
<span class="slds-media__body">
<p class="slds-listbox__option-text slds-listbox__option-text_entity slds-text-heading_small">
{sitePrediction.main_text}
</p>
<p class="slds-listbox__option-text slds-listbox__option-text_entity slds-text-title">
{sitePrediction.secondary_text}
</p>
</span>
</div>
</li>
</template>
</template>
import { LightningElement, api } from 'lwc';
export default class GoogleEachPrediction extends LightningElement {
@api sitePrediction;
handlePredictionSelect() {
const event = new CustomEvent('predictionselect', {
detail: { placeId: this.sitePrediction.place_id, placeName: this.sitePrediction.main_text }
});
this.dispatchEvent(event);
}
}
public class GooglePlacesAPI {
//Method to make a Callout to Google Place API to get search predications based on input search string
@AuraEnabled(cacheable=true)
public static String getAddressSet(String searchText, Boolean isPersonal){
String result = null;
system.debug('searchText is ' + searchText);
try{
if(searchText != null) {
String apiURL;
// String endpoint = 'callout:Google_Places_API'+EncodingUtil.urlEncode(searchText, 'UTF-8') + '&key=' + getAPIKey();
if(!isPersonal) {
apiURL = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=' +
EncodingUtil.urlEncode(searchText,
'UTF-8') + '&types=establishment&key=' + getAPIKey()+
'&location=37.839333,-84.270020&radius=100000';
} else if(isPersonal) {
apiURL = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=' +
EncodingUtil.urlEncode(searchText,
'UTF-8') + '&key=' + getAPIKey()+'&location=37.839333,-84.270020&radius=100000';
}
system.debug('apiURL is ' + apiURL);
HttpResponse res = getResponse(apiURL);
if(res.getStatusCode() == 200) {
system.debug('API invoked successfully');
result = res.getBody();
}
}
}
catch(exception e) {
//Handling exception
system.debug(e.getMessage());
throw new AuraHandledException('Error while getting location predictions ---> '+e.getMessage());
}
return result;
}
//Generic method to get GoogleAPIKey from Custom Label.
public static String getAPIKey() {
String api = Label.GoogleAPIKey;
return api;
}
//Generic Http Callout Method
public static HttpResponse getResponse(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);
return res;
}
//Method to call google API and fetch the address details by placeId
@AuraEnabled(cacheable=true)
public static String getAddressDetailsByPlaceId(String placeId){
String result = null;
system.debug('placeId is ' + placeId);
try{
if(placeId != null) {
// String endpoint = 'callout:Google_Places_Details_API'+EncodingUtil.urlEncode(placeId, 'UTF-8') + '&key=' + getAPIKey();
String apiURL = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=' +
EncodingUtil.urlEncode(placeId, 'UTF-8') + '&key=' + getAPIKey();
system.debug('apiURL is1 ' + apiURL);
HttpResponse res = getResponse(apiURL);
if(res.getStatusCode() == 200) {
system.debug('API invoked successfully');
result = res.getBody();
}
}
}
catch(exception e) {
//Handling exception
throw new AuraHandledException('Error while getting location predictions ---> '+e.getMessage());
}
return result;
}
}
/* eslint-disable guard-for-in */
/* eslint-disable vars-on-top */
/* eslint-disable no-console */
import { LightningElement, track, wire, api } from 'lwc';
import { CurrentPageReference } from "lightning/navigation";
import { fireEvent } from "c/pubsub";
import getInitialAddress from "@salesforce/apex/GooglePlacesAPI.getAddressSet";
import getAddressByPlaceId from "@salesforce/apex/GooglePlacesAPI.getAddressDetailsByPlaceId";
export default class GooglePlacesApi extends LightningElement {
@wire(CurrentPageReference) pageRef;
@api searchLabel = "Address or location search";
@api needHelpText;
@api isGlobal;
@track addressList;
@track showDropdown;
@track selectedPlaceId;
@track selectedPlaceName;
@track selectedAddress;
@track initSearchStatus;
@track placeVerified;
@api whichComponent;
@api isPersonal;
handleInputChange(event) {
// console.log('google api isglobal check--',this.isGlobal);
this.selectedPlaceId = undefined;
this.selectedAddress = undefined;
fireEvent(this.pageRef, "inputchange", this.whichComponent);
this.inputString = event.target.value;
if (this.inputString && this.inputString !== null && this.inputString !== '') {
getInitialAddress({ searchText: this.inputString, isPersonal: this.isPersonal })
.then(result => {
// console.log('Search results --> ' + JSON.stringify(JSON.parse(result)));
let predictions = JSON.parse(result).predictions;
let status = JSON.parse(result).status;
this.initSearchStatus = JSON.parse(result).status;
let addresses = [];
// console.log('search status --->'+ status);
// console.log('predictions ---> ' + JSON.stringify(predictions));
if (predictions.length > 0) {
fireEvent(this.pageRef, 'somesuggestions', null);
for (let i = 0; i < predictions.length; i++) {
let countryCheck = predictions[i].structured_formatting.secondary_text;
if ((this.isGlobal) || (!this.isGlobal && countryCheck.endsWith(', USA'))) {
addresses.push(
{
main_text: predictions[i].structured_formatting.main_text,
secondary_text: predictions[i].structured_formatting.secondary_text,
place_id: predictions[i].place_id
});
}
}
if (addresses.length > 0) {
this.addressList = addresses;
this.showDropdown = true;
} else {
this.addressList = undefined;
this.showDropdown = false;
fireEvent(this.pageRef, 'zerosuggestions', null);
}
}
else {
this.addressList = undefined;
this.showDropdown = false;
fireEvent(this.pageRef, 'zerosuggestions', null);
}
})
.catch(error => {
console.log('Error in Search results ---> ' + error);
});
}
else {
this.addressList = undefined;
this.showDropdown = false;
}
}
handlePredictionSelect(event) {
this.selectedPlaceId = event.detail.data.placeId;
this.selectedPlaceName = event.detail.data.placeName;
// console.log('selected place ---> ' + this.selectedPlaceName);
this.showDropdown = false;
if (this.selectedPlaceId) {
getAddressByPlaceId({ placeId: this.selectedPlaceId })
.then(result => {
// console.log('Place Details ---> ' + JSON.stringify(JSON.parse(result)));
let response = JSON.parse(result).result;
let postalCode = '', state = '', stateCode = '', country = '', countryCode = '', city = '', street = '', street_number = '', route = '', subLocal1 = '', subLocal2 = '';
if (response.address_components.length > 0) {
for (let key in response.address_components) {
var fieldLabel = response.address_components[key].types[0];
if (fieldLabel === 'sublocality_level_2' || fieldLabel === 'sublocality_level_1' || fieldLabel === 'street_number' ||
fieldLabel === 'route' || fieldLabel === 'locality' || fieldLabel === 'country' || fieldLabel === 'postal_code' ||
fieldLabel === 'administrative_area_level_1') {
switch (fieldLabel) {
case 'sublocality_level_2':
subLocal2 = response.address_components[key].long_name;
break;
case 'sublocality_level_1':
subLocal1 = response.address_components[key].long_name;
break;
case 'street_number':
street_number = response.address_components[key].long_name;
break;
case 'route':
route = response.address_components[key].short_name;
break;
case 'postal_code':
postalCode = response.address_components[key].long_name;
break;
case 'administrative_area_level_1':
state = response.address_components[key].long_name;
stateCode = response.address_components[key].short_name;
break;
case 'country':
country = response.address_components[key].long_name;
countryCode = response.address_components[key].short_name;
break;
case 'locality':
city = response.address_components[key].long_name;
break;
default:
break;
}
}
}
if (street_number && route) {
street = street_number + ' ' + route;
}
else {
street = street_number + ' ' + route;
}
if (street == null) {
if (subLocal2 && subLocal1) {
street = subLocal2 + ', ' + subLocal1;
}
else {
street = subLocal2 + ' ' + subLocal1;
}
}
if (this.initSearchStatus === 'OK' && street_number) {
this.placeVerified = true;
}
else {
this.placeVerified = false;
street = this.selectedPlaceName;
}
}
// console.log('street --> ' + street);
// console.log('city --> ' + city);
// console.log('state --> ' + state);
// console.log('country --> ' + country);
// console.log('postalCode --> ' + postalCode);
let address = {
name: response.name ? response.name : this.selectedPlaceName,
street: street,
city: city,
state: state,
stateCode: stateCode,
country: country,
countryCode: countryCode,
postalCode: postalCode,
phone: response.formatted_phone_number,
lat: response.geometry.location.lat,
lon: response.geometry.location.lng
};
this.selectedAddress = address;
// console.log('selectedaddress ---> ' + JSON.stringify(this.selectedAddress));
//this.template.querySelector(`[data-divtag="divtag"]`).removeAttribute('style');
fireEvent(this.pageRef, "apilocationselected", this.selectedAddress);
})
.catch(error => {
console.log('Error while getting place details --> ' + error);
});
}
}
}
<template>
<div class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right" role="none">
<div class="help-block slds-grid">
<div class="slds-text-heading_medium slds-p-bottom_x-small">{searchLabel}</div>
</div>
<lightning-input variant="label-hidden" type="search" placeholder="Start typing" onchange={handleInputChange}>
</lightning-input>
</div>
<template if:true={showDropdown}>
<div id="listbox-id-1"
class="slds-dropdown slds-dropdown_length-with-icon-7 slds-dropdown_fluid address-typeahead" role="listbox">
<ul class="slds-listbox slds-listbox_vertical" role="presentation">
<template if:true={addressList}>
<template for:each={addressList} for:index="index" for:item="prediction">
<c-google-each-new-prediction class="item" onpredictionselect={handlePredictionSelect}
site-prediction={prediction} key={prediction.place_id}></c-google-each-new-prediction>
</template>
</template>
<template if:false={addressList}>
<div>Please refine your search.</div>
</template>
</ul>
</div>
</template>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment