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 insert triggers not working properly 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.

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  

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');

									 System.debug('ta:coming in after insert4');
    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');

												 System.debug('ta:coming in after Update5');

My class code is as belows:
public class AccountGeocodeAddress {

static public void newAccmethod(set<id> li){

 	String  geocodingKey ='AIzaSyD6DLnewg4y0Casi0-iFFjoenLJmmayt8c';
	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(''+address + '&key='+ geocodingKey+ '&sensor=false');



			// 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();


						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;

				a.Location__Longitude__s= lon;
				update a;



		catch (Exception e) {





User-added image
Any help will be greatly appreciated!

Thanks in advance

Thanks & Regards,