function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Harjeet Singh 13Harjeet Singh 13 

After update triggers working everytime instead of after insert in geolocation triggers

Dear All,

I am immense need of help from all of you. After giving a much thought and so much brainstorming happened finally I turned up here for advise.

Requirement:
I need to fetch coordinates value of account based on Map address provided. Map addresses are new fields created on accounts object(map street,map city,map postal code,map countrymap state)

Solution approach
I create few fields on accounts like MapAddressCity,MapAddressState,MapAddressStreet,MapAddressPostalCode and MapAddresscountry on account. When an user enters values in Map fields and clicks on save button I am calling Google API. Google API will returns one coordinate value based on address filled in Map fields. I have created one field called "Location"(Data Type-Geolocation) which will stores coordinates and also I created 2 formula fields which stores the longitude and latitude values of coordinates in "LonField" and "LatField" respectively

If an user enters below in account:
MapAddressCity: San Francisco  
MapAddressCountry: United States  
MapAddressPostalCode: 94105  
MapPostalState: CA  
MapAddressStreet: One Market Street
and clicks on Save-Google API call will be made and below information wiull be stored on account:
Location-37°47'38''N 122°23'41''W  
LongValue-122.3948  
LatValue37.7939

My Question:
When I am trying to update an already existing account(update operation) then upon saving future method is called and coordinates are getting stored and in debug logs I can see "ta:coming in after UPDATE"(Kindly refer my trigger code) which is correct.But my worry point is when I am trying to insert a new account and provides map addresses and clicks on Save then also coordinates are getting stored which is also correct but in debug logs I cn still see  "ta:coming in after UPDATE"  instead of 'ta:coming in after insert' because its an insert not an update.

1.Why after trigger is not working and coordinates are getting populated correctly even for new insertion due to after update instead of after insert
2. When I am trying to insert account records through data loader some accounts have updated coordinates after insertion whereas some doesn't have coordinates inserted.
I tried inserting around 17K records upon which 5K records inserted succesfully and also their corresponding coordinates are updated. Rest 12K records also inserted succesfully but their coordinates are not updated.

Below is trigger which is written on account:
 
trigger geocodeAccountAddress on Account (after insert, after update) {
  
    Set<Id> li=new Set<Id>();
  //bulkify trigger in case of multiple accounts
  //
  if(Trigger.isAfter && Trigger.isInsert){
      System.debug('ta:coming in after insert');
      for(Account acc:Trigger.New){
           System.debug('ta:coming in after insert2');
        if((acc.Location__Latitude__s == null)  && (String.isNotBlank(acc.MapAddressCountry__c))){
  System.debug('ta:coming in after insert1');

li.add(acc.id);
System.debug('ta:coming in after insert4');
												AccountGeocodeAddress.newAccmethod(li);
}  
      }
  }
    
    if(Trigger.isAfter && Trigger.isUpdate){
   System.debug('ta:coming in after UPDATE');
	for(Account acc:Trigger.New){

 if((acc.Location__Latitude__s == null)  &&(String.isNotBlank(acc.MapAddressCountry__c))){
 System.debug('ta:coming in after UPDATE1');

li.add(acc.id);
 System.debug('ta:coming in after Update5');
												AccountGeocodeAddress.newAccmethod(li);
}
}
}
}

My class code is as belows:
 
public class AccountGeocodeAddress {

@future(callout=true)
static public void newAccmethod(set<id> li){

 	
	for(Account a : [SELECT MapAddressCity__c,MapAddressCountry__c,MapAddressPostalCode__c,MapAddressStreet__c,MapPostalState__c FROM Account  WHERE id =: li]){

		String address = ' ';

		if (a.MapAddressStreet__c!= null)
            address += a.MapAddressStreet__c+', ';
        if (a.MapAddressCity__c != null)
            address += a.MapAddressCity__c +', ';
        if (a.MapPostalState__c!= null)
            address += a.MapPostalState__c+' ';
        if (a.MapAddressPostalCode__c!= null)
            address += a.MapAddressPostalCode__c+', ';
        if (a.MapAddressCountry__c!= null)
            address += a.MapAddressCountry__c;

		address = EncodingUtil.urlEncode(address, 'UTF-8');

		// build callout

		Http h = new Http();

		HttpRequest req = new HttpRequest();

		//req.setEndpoint(‘http://maps.googleapis.com/maps/api/geocode/json?address=’+address+’&sensor=false’);
		req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address='+address + '&key='+ geocodingKey+ '&sensor=false');

		req.setMethod('GET');

		req.setTimeout(6000);
		try{

			// callout

			HttpResponse res = h.send(req);

			// parse coordinates from response

			JSONParser parser = JSON.createParser(res.getBody());
			system.debug('Harjeet:'+ res.getBody());
			double lat = null;

			double lon = null;

			while (parser.nextToken() != null) {

				if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
								(parser.getText() == 'location')){

					parser.nextToken(); // object start

					while (parser.nextToken() != JSONToken.END_OBJECT){

						String txt = parser.getText();

						parser.nextToken();

						if (txt == 'lat')

						lat = parser.getDoubleValue();

						else if (txt == 'lng')

						lon = parser.getDoubleValue();

					}

				}

			}

			// update coordinates if we get back

			if (lat != null){

				system.debug(lat+' '+lon);

				a.Location__Latitude__s = lat;
				system.debug(a.Location__Latitude__s+'Location__Latitude__s');

				a.Location__Longitude__s= lon;
				system.debug(a.Location__Longitude__s+'Location__Longitude__s');
				update a;

			}

		}

		catch (Exception e) {

			system.debug(e);

		}

	}	

}

}
User-added image


Any help will be greatly appreciated!

Thanks in advance

Thanks & Regards,
Harjeet
 
Amit Singh 1Amit Singh 1
Hi Harjeet,

Are you getting any kind of error? I have noticed that you are making the method call inside for loop and inside that method you are making the SOQL which will lead to SOQL 101 Error.

Also, we have limitation over the future method we can have only 50 future methods.

However, I have modified the code please use this and let me know if this works
trigger geocodeAccountAddress on Account(after insert, after update) {

 Set < Id > li = new Set < Id > ();
 //bulkify trigger in case of multiple accounts
 if (Trigger.isAfter && Trigger.isInsert) {
	  System.debug('ta:coming in after insert');
	  for (Account acc: Trigger.New) {
		   System.debug('ta:coming in after insert2');
		   if ((acc.Location__Latitude__s == null) && (String.isNotBlank(acc.MapAddressCountry__c))) {
				System.debug('ta:coming in after insert1');
				li.add(acc.id);
				System.debug('ta:coming in after insert4');
		   }
	  }
	  if(li !=null && li.size() > 0){
			AccountGeocodeAddress.newAccmethod(li);
	  }
 }

 if (Trigger.isAfter && Trigger.isUpdate) {
	  System.debug('ta:coming in after UPDATE');
	  for (Account acc: Trigger.New) {

		   if ((acc.Location__Latitude__s == null) && (String.isNotBlank(acc.MapAddressCountry__c))) {
				System.debug('ta:coming in after UPDATE1');
				li.add(acc.id);
				System.debug('ta:coming in after Update5');
		   }
	  }
	  if(li !=null && li.size() > 0){
			AccountGeocodeAddress.newAccmethod(li);
	  }
	}
}

Regards,
Amit
Harjeet Singh 13Harjeet Singh 13
Dear Amit,

Thanks for your response. I did gave a try modifying my code as suggested by you but it is doing the same thing which my code was working. Coordinates are getting stored succefully for both cases (for inserting a new account and updating an existing account).
My problem is when I am modifying an existing account then in debug log I can see "ta:coming after update" which confirms that flow is going inside after update but when I am creating a new account then also in debug log I can see "ta:coming after update "and I guess it should be "ta:coming after insert" because its an insertion of new accounts. Why the flow is going inside after update in both of the cases.

Also can you please specify what is the difference between my code and the one which you have provided

Kindly help me in knowing why after update is working for both insert operation and update operation. Ideally when I am creating a new account then flow should go inside after insert System.debug('ta:coming in after insert'); Right. Then why flow is till going inside after update. Although coordinate sare getting stored but according to me this is not correct.What is the usage of keeping after insert then??

Any help will be greatly appreciated!

Thanks in advance

Thanks & Regards,
Harjeet