Get Longitude and Latitude from the Google Api
Requirement: To get longitude and latitude of address using google api in salesforce.
When Account is insert/update if account has shipping address then auto fill latitude and longitude values
Soloution >>
You need to hit google api call. it is free you can call it easily
Note>>1) Add end point URL in Remote site setting
SetUp>> remoteSiteSetting>> AddURL: https://maps.googleapis.com
2) Add two fields as a text type on Account object one is longitude and othe is latitude
Longitude >> Longitude__c
Latitude >> Latitude__c
Step 1>> Need to Write trigger on Account Object
You need to write two class and one trigger
Class 1
/*
This class is using for quering Billing address and call Google Map api and find the lattitue and long from API
*/
public class AccountGetBillingAdress {
// toCheckFutueCall varibale is a boolean variable if it has alreday exist
private static Boolean toCheckFutueCall = false;
public static void populateLatandLongCode(id accountId) {
if (toCheckFutueCall || System.isFuture()) {
System.debug(LoggingLevel.WARN, '***Show the Waring!!!!!!!!');
return;
}
toCheckFutueCall = true;
callBillingAdresss(accountId);
}
// Future Call out
@future (callout = true)
static private void callBillingAdresss(id accountId) {
// This is key of Geocoding API for Google Maps
String keyofgeoCode = 'AIzaSyA32dZ7q_a7xlz8VPsU6vxkAHIoZ4XzgVs';
Account objAccountGeo = [SELECT BillingStreet, BillingCity, BillingState, BillingCountry, BillingPostalCode, Latitude__c, Longitude__c FROM Account WHERE id = :accountId];
if ((objAccountGeo.BillingStreet == null) || (objAccountGeo.BillingCity == null)) {
System.debug(LoggingLevel.WARN, 'Insufficient Data to Geocode Address');
return;
}
String strBillingAddres = '';
if (objAccountGeo.BillingStreet != null)
strBillingAddres += objAccountGeo.BillingStreet + ', ';
if (objAccountGeo.BillingCity != null)
strBillingAddres += objAccountGeo.BillingCity + ', ';
if (objAccountGeo.BillingState != null)
strBillingAddres += objAccountGeo.BillingState + ', ';
if (objAccountGeo.BillingCountry != null)
strBillingAddres += objAccountGeo.BillingCountry + ', ';
if (objAccountGeo.BillingPostalCode != null)
strBillingAddres += objAccountGeo.BillingPostalCode;
// encode the string so we can pass it as part of URL
system.debug('strBillingAddres ...'+strBillingAddres);
strBillingAddres = EncodingUtil.urlEncode(strBillingAddres, 'UTF-8');
// build and make the callout to the Geocoding API
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address=' + strBillingAddres + '&key=' + keyofgeoCode + '&sensor=false');
request.setMethod('GET');
request.setTimeout(120000);
try {
HttpResponse response = http.send(request);
JSONParser responseParser = JSON.createParser(response.getBody());
double latitude = null;
double longitude = null;
while (responseParser.nextToken() != null) {
if ((responseParser.getCurrentToken() == JSONToken.FIELD_NAME) && (responseParser.getText() == 'location')) {
responseParser.nextToken();
while (responseParser.nextToken() != JSONToken.END_OBJECT) {
String locationText = responseParser.getText();
responseParser.nextToken();
if (locationText == 'lat')
latitude = responseParser.getDoubleValue();
else if (locationText == 'lng')
longitude = responseParser.getDoubleValue();
}
}
}
system.debug('latitude::::::::'+latitude);
system.debug('longitude ::::::::'+longitude);
// Update Lat and Long on Account
if(latitude != null) {
objAccountGeo.Lat__c = String.ValueOf(latitude);
objAccountGeo.Long__c = String.ValueOf(longitude);
update objAccountGeo; // update account with lat and long
}
} catch
(Exception e) {
System.debug(LoggingLevel.ERROR, 'get if any error- ' + e.getMessage());
}
}
}
Class 2
// This class is verifying the account billing address is filled or not this class called in Account
// Trigger
public class Account_TriggerHandlerHelperClass {
//Handler for after insert methods
public void onAfterInsert(list<Account> lstofAccount) {
UpdateLatandLogOnInsertion (lstofAccount);
}
//Handler for after Update methods
public void onAfterUpdate(list<Account> lstofAccount, map<id, Account> triggerOldMap) {
UpdateLatandLogOnUpdation (lstofAccount , triggerOldMap) ;
}
private void UpdateLatandLogOnUpdation (list<Account> lstofAccount, map<id, Account> triggerOldMap ) {
if (lstofAccount !null && lstofAccount.size()>0 ) {
for (Account objAcc : lstofAccount ) {
if (!String.isBlank(objAcc.BillingStreet)
&& !String.isBlank(objAcc.BillingCity)
&& !String.isBlank(objAcc.BillingState)
&& !String.isBlank(objAcc.BillingPostalCode)
&& !String.isBlank(objAcc.BillingCountry)
&& (objAcc.BillingStreet != triggerOldMap.get(objAcc.Id).BillingStreet || objAcc.BillingCity != triggerOldMap.get(objAcc.Id).BillingCity || objAcc.BillingState != triggerOldMap.get(objAcc.Id).BillingState || objAcc.BillingPostalCode != triggerOldMap.get(objAcc.Id).BillingPostalCode || objAcc.BillingCountry != triggerOldMap.get(objAcc.Id).BillingCountry) ) {
AccountGetBillingAdress.populateLatandLongCode(objAcc.Id);
}
}
}
}
private void UpdateLatandLogOnInsertion (list<Account> lstofAccount ) {
if (lstofAccount !null && lstofAccount.size()>0 ) {
for (Account objAcc : lstofAccount ) {
if (!String.isBlank(objAcc.BillingStreet)
&& !String.isBlank(objAcc.BillingCity)
&& !String.isBlank(objAcc.BillingState)
&& !String.isBlank(objAcc.BillingPostalCode)
&& !String.isBlank(objAcc.BillingCountry)) {
AccountGetBillingAdress.populateLatandLongCode(objAcc.Id);
}
}
}
}
}
Account Trigger
trigger AccountTrigger on Account (after insert, after update)
{
Account_TriggerHandlerHelperClass objHandler = new Account_TriggerHandlerHelperClass();
if (Trigger.isInsert && Trigger.isAfter )
{
objHandler.onAfterInsert(Trigger.New);
}
if (Trigger.isUpdate && Trigger.isAfter)
{
objHandler.onAfterUpdate(Trigger.New,Trigger.oldMap);
}
}
OutPut
------------------
When Account is insert/update if account has shipping address then auto fill latitude and longitude values
Soloution >>
You need to hit google api call. it is free you can call it easily
Note>>1) Add end point URL in Remote site setting
SetUp>> remoteSiteSetting>> AddURL: https://maps.googleapis.com
2) Add two fields as a text type on Account object one is longitude and othe is latitude
Longitude >> Longitude__c
Latitude >> Latitude__c
Step 1>> Need to Write trigger on Account Object
You need to write two class and one trigger
Class 1
/*
This class is using for quering Billing address and call Google Map api and find the lattitue and long from API
*/
public class AccountGetBillingAdress {
// toCheckFutueCall varibale is a boolean variable if it has alreday exist
private static Boolean toCheckFutueCall = false;
public static void populateLatandLongCode(id accountId) {
if (toCheckFutueCall || System.isFuture()) {
System.debug(LoggingLevel.WARN, '***Show the Waring!!!!!!!!');
return;
}
toCheckFutueCall = true;
callBillingAdresss(accountId);
}
// Future Call out
@future (callout = true)
static private void callBillingAdresss(id accountId) {
// This is key of Geocoding API for Google Maps
String keyofgeoCode = 'AIzaSyA32dZ7q_a7xlz8VPsU6vxkAHIoZ4XzgVs';
Account objAccountGeo = [SELECT BillingStreet, BillingCity, BillingState, BillingCountry, BillingPostalCode, Latitude__c, Longitude__c FROM Account WHERE id = :accountId];
if ((objAccountGeo.BillingStreet == null) || (objAccountGeo.BillingCity == null)) {
System.debug(LoggingLevel.WARN, 'Insufficient Data to Geocode Address');
return;
}
String strBillingAddres = '';
if (objAccountGeo.BillingStreet != null)
strBillingAddres += objAccountGeo.BillingStreet + ', ';
if (objAccountGeo.BillingCity != null)
strBillingAddres += objAccountGeo.BillingCity + ', ';
if (objAccountGeo.BillingState != null)
strBillingAddres += objAccountGeo.BillingState + ', ';
if (objAccountGeo.BillingCountry != null)
strBillingAddres += objAccountGeo.BillingCountry + ', ';
if (objAccountGeo.BillingPostalCode != null)
strBillingAddres += objAccountGeo.BillingPostalCode;
// encode the string so we can pass it as part of URL
system.debug('strBillingAddres ...'+strBillingAddres);
strBillingAddres = EncodingUtil.urlEncode(strBillingAddres, 'UTF-8');
// build and make the callout to the Geocoding API
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address=' + strBillingAddres + '&key=' + keyofgeoCode + '&sensor=false');
request.setMethod('GET');
request.setTimeout(120000);
try {
HttpResponse response = http.send(request);
JSONParser responseParser = JSON.createParser(response.getBody());
double latitude = null;
double longitude = null;
while (responseParser.nextToken() != null) {
if ((responseParser.getCurrentToken() == JSONToken.FIELD_NAME) && (responseParser.getText() == 'location')) {
responseParser.nextToken();
while (responseParser.nextToken() != JSONToken.END_OBJECT) {
String locationText = responseParser.getText();
responseParser.nextToken();
if (locationText == 'lat')
latitude = responseParser.getDoubleValue();
else if (locationText == 'lng')
longitude = responseParser.getDoubleValue();
}
}
}
system.debug('latitude::::::::'+latitude);
system.debug('longitude ::::::::'+longitude);
// Update Lat and Long on Account
if(latitude != null) {
objAccountGeo.Lat__c = String.ValueOf(latitude);
objAccountGeo.Long__c = String.ValueOf(longitude);
update objAccountGeo; // update account with lat and long
}
} catch
(Exception e) {
System.debug(LoggingLevel.ERROR, 'get if any error- ' + e.getMessage());
}
}
}
Class 2
// This class is verifying the account billing address is filled or not this class called in Account
// Trigger
public class Account_TriggerHandlerHelperClass {
//Handler for after insert methods
public void onAfterInsert(list<Account> lstofAccount) {
UpdateLatandLogOnInsertion (lstofAccount);
}
//Handler for after Update methods
public void onAfterUpdate(list<Account> lstofAccount, map<id, Account> triggerOldMap) {
UpdateLatandLogOnUpdation (lstofAccount , triggerOldMap) ;
}
private void UpdateLatandLogOnUpdation (list<Account> lstofAccount, map<id, Account> triggerOldMap ) {
if (lstofAccount !null && lstofAccount.size()>0 ) {
for (Account objAcc : lstofAccount ) {
if (!String.isBlank(objAcc.BillingStreet)
&& !String.isBlank(objAcc.BillingCity)
&& !String.isBlank(objAcc.BillingState)
&& !String.isBlank(objAcc.BillingPostalCode)
&& !String.isBlank(objAcc.BillingCountry)
&& (objAcc.BillingStreet != triggerOldMap.get(objAcc.Id).BillingStreet || objAcc.BillingCity != triggerOldMap.get(objAcc.Id).BillingCity || objAcc.BillingState != triggerOldMap.get(objAcc.Id).BillingState || objAcc.BillingPostalCode != triggerOldMap.get(objAcc.Id).BillingPostalCode || objAcc.BillingCountry != triggerOldMap.get(objAcc.Id).BillingCountry) ) {
AccountGetBillingAdress.populateLatandLongCode(objAcc.Id);
}
}
}
}
private void UpdateLatandLogOnInsertion (list<Account> lstofAccount ) {
if (lstofAccount !null && lstofAccount.size()>0 ) {
for (Account objAcc : lstofAccount ) {
if (!String.isBlank(objAcc.BillingStreet)
&& !String.isBlank(objAcc.BillingCity)
&& !String.isBlank(objAcc.BillingState)
&& !String.isBlank(objAcc.BillingPostalCode)
&& !String.isBlank(objAcc.BillingCountry)) {
AccountGetBillingAdress.populateLatandLongCode(objAcc.Id);
}
}
}
}
}
Account Trigger
trigger AccountTrigger on Account (after insert, after update)
{
Account_TriggerHandlerHelperClass objHandler = new Account_TriggerHandlerHelperClass();
if (Trigger.isInsert && Trigger.isAfter )
{
objHandler.onAfterInsert(Trigger.New);
}
if (Trigger.isUpdate && Trigger.isAfter)
{
objHandler.onAfterUpdate(Trigger.New,Trigger.oldMap);
}
}
OutPut
------------------
Comments
Post a Comment