Get Geo location from Google API in Salesforce

To get Geo-location from google API in Salesforce, I did a small integration with Google Geocode API.

Get Geo location from Google API in Salesforce

To call Google API, we need the API key. Follow the steps in this article to get the key.

Steps to get the latitude and longitude from Google Geolocation

Create an Apex trigger with below code. The trigger runs after insert or update.

 // Trigger runs getLocation() on Accounts with no Geolocation
trigger SetGeolocation on Account (after insert, after update) {
//bulkify trigger in case of multiple accounts
  for(Account account : trigger.new) {
  
    //check if Billing Address has been updated
    Boolean addressChangedFlag = false;
    if(Trigger.isUpdate) {
      Account oldAccount = Trigger.oldMap.get(account.Id);
      if((account.billingaddress__c!= oldAccount.billingaddress__c) || (account.City__c!= oldAccount.City__c) ||
        (account.State__c!= oldAccount.State__c) ||(account.Zip_Code__c!= oldAccount.Zip_Code__c)||(account.Country__c!= oldAccount.Country__c)){
addressChangedFlag = true;
        
      }
    }
    // if Location is null or  address has been changed, call the Geocode class
    if((account.Location__Latitude__s == null) || (addressChangedFlag == true)) {
      AccountGeocodeAddress.DoAddressGeocode(account.id);
    }
  }
}

public class AccountGeocodeAddress {
private static Boolean geocoding= false;
public static void DoAddressGeocode(id accountId) {
if(geocodingCalled || System.isFuture()) {
    System.debug(LoggingLevel.WARN, 'Method Already Called');
    return;
  }
 //Else call the future method
geocoding = true;
geocodeAddress.geocodeAddress(accountId);
}
}

The following class is where future call out occurs. As a result, lat long are saved in Account record.

 public class geocodeAddress {
// we need a future method to call Google Geocoding API from Salesforce
@future (callout=true)
static public void geocodeAddress(Id accountId)

  // Key for Google Maps Geocoding API
  String geocodingKey = <Your API Key>
Account geoAccount = [SELECT billingaddress__c, City__c, State__c, Country__c,Zip_Code__c,Location_Status__c FROM Account WHERE
id = :accountId];
 
  //create a string for the address to pass to Google Geocoding API
  String geoAddress = '';
  if(geoAccount.billingaddress__c!= null)
    geoAddress+= geoAccount.billingaddress__c+ ', ';
  if(geoAccount.City__c != null)
    geoAddress+= geoAccount.City__c+ ', ';
  if(geoAccount.State__c!= null)
    geoAddress+= geoAccount.State__c+ ', ';
  if(geoAccount.Country__c!= null)
    geoAddress+= geoAccount.Country__c+ ', ';
  if(geoAccount.Zip_Code__c!= null)
    geoAddress+= geoAccount.Zip_Code__c;
  
  //encode the string so we can pass it as part of URL
  geoAddress= EncodingUtil.urlEncode(geoAddress, 'UTF-8');
  //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='+geoAddress +'&key='+ geocodingKey+'&sensor=false');
  request.setMethod('GET');
  request.setTimeout(60000);
  try {
    // make the http callout
    HttpResponse response = http.send(request);
    System.debug(response.getBody());
    // parse JSON to extract co-ordinates
    JSONParser responseParser = JSON.createParser(response.getBody());
    // initialize co-ordinates
    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();
        }
      }
         else 
         { 
           geoAccount.Location_Status__c='Address Invalid';
          
         }
         
      
    }
     
    //update co-ordinates on address if we get them back
    if(latitude != null) {
      geoAccount.Location__Latitude__s= latitude;
      geoAccount.Location__Longitude__s= longitude;
     geoAccount.Location_Status__c='Location Updated';
      
    }
  } catch
(Exception e) {
    System.debug(LoggingLevel.ERROR,
'Error Geocoding Address - ' + e.getMessage());
  }
  update geoAccount;
}
}

Now whenever new account is inserted or address is updated, API will be called to get the location coordinates.

4 thoughts on “Get Geo location from Google API in Salesforce

  1. Thank you!
    Although I have been working with Salesforce for years I am only now getting to grips with writing Apex. I was able to use your code as a template to add geocoding for addresses on a custom object.

    Do you have a mock callout class that I could use to help me write a test for this?

    Best regards,

    Ian

    1. Hi Ian,

      Please tell me what you have written and I can help you with correcting it. You can use the link to get more information on writing mock callout classes.
      Thanks.

  2. Hi Neha,
    In my org, I have more than 1 lakh records and all record have address populated as of now. Is there any way to pass the address to google api in bulk manner instead of one record at a time. Because I don’t want to call google api 1 lakh times. Any help would be appreciated. Thanks!!

    1. Hi Jagdeep,

      I am not sure if Google API allows bulk queries. There are some other third-party services for this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top