Header Ads Widget

Responsive Advertisement

Implementing Apex Maps API Geocoding in Salesforce to Update Latitude and Longitude

Implementing Apex Maps API Geocoding for Updating Custom Address Fields
maps-img

Implementing Maps API Geocoding for Updating Custom Address Fields

Salesforce provides a powerful integration with the Maps API, allowing you to geocode addresses and automatically update latitude and longitude fields for custom or standard objects. In this post, we will explore how to implement this using a custom trigger and the Queueable interface to handle geocode API calls efficiently.

Pre-requisites:

Before proceeding with implementation, ensure the following prerequisites are in place:

  • Salesforce Maps License: You must have Salesforce Maps installed and licensed in your org, as well as access to Maps objects and Apex classes. Permissions like SF Maps or SF Maps Admin must be granted to your user profile.
  • Geocoding via API: For standard objects (e.g., Accounts) with standard address fields (e.g., BillingAddress), Salesforce provides built-in address geocoding capabilities using integration rules. Custom objects and custom address fields require a custom solution using the Maps API Geocode method.
  • Enable Callouts in Apex: The trigger will make an external API call, so you need to ensure callouts are allowed. This can be handled through future methods or the Queueable interface to avoid uncommitted work errors during transaction processing.

Step 1: Create a Custom Trigger

First, create a trigger on your custom object to invoke the geocoding logic whenever an address field is inserted or updated.


trigger CustomObjectTrigger on CustomObject__c (after insert, after update) {
    List<Id> customObjectIds = new List<Id>();
    
    for (CustomObject__c obj : Trigger.new) {
        if (obj.Address_Field__c != null && (obj.Latitude__c == null || obj.Longitude__c == null)) {
            customObjectIds.add(obj.Id);
        }
    }

    if (!customObjectIds.isEmpty()) {
        System.enqueueJob(new CustomGeocodeQueueable(customObjectIds));
    }
}
    

This trigger collects custom object records that have an address but missing latitude and longitude, and enqueues the Queueable job to process the API call.

Step 2: Implement the Queueable Class

Next, create a Queueable class that makes the callout to the Maps API to retrieve latitude and longitude for the address field. Ensure you handle callouts in the execute() method of the Queueable class.


public class CustomGeocodeQueueable implements Queueable, Database.AllowsCallouts {
    private List<Id> customObjectIds;

    public CustomGeocodeQueueable(List<Id> customObjectIds) {
        this.customObjectIds = customObjectIds;
    }

    public void execute(QueueableContext context) {
        List<CustomObject__c> customObjects = [SELECT Id, Address_Field__c FROM CustomObject__c WHERE Id IN :customObjectIds];

        for (CustomObject__c obj : customObjects) {
            Map<String, Object> options = new Map<String, Object>();
            options.put('address', obj.Address_Field__c);
            options.put('version', '1');  // Version of the API endpoint.

            // Call the Maps API Geocode method
            Map<String, Object> response = maps.API.Geocode(options);

            if (response != null && (Boolean)response.get('success')) {
                Map<String, Object> position = (Map<String, Object>) response.get('data').get('position');
                obj.Latitude__c = (Decimal) position.get('lat');
                obj.Longitude__c = (Decimal) position.get('lng');
            } else {
                // Handle geocoding failure, if necessary.
                System.debug('Geocode failed for address: ' + obj.Address_Field__c);
            }
        }

        update customObjects;  // Update the records with new lat/long.
    }
}
    

The class:

  • Queries the custom object records.
  • Makes an API call to geocode the address.
  • Updates the Latitude__c and Longitude__c fields accordingly.

Step 3: Integration Rule for Standard Objects

For standard objects (e.g., Account, Contact) that use standard address fields (e.g., BillingAddress or ShippingAddress), Salesforce supports automatic geocoding through an Integration Rule. You can enable this rule via Setup under the Data Integration Rules section, which will automatically populate latitude and longitude fields.

Summary:

This solution involves:

  • A trigger on a custom object to detect address changes.
  • A Queueable class to handle API callouts for geocoding, avoiding uncommitted work errors.
  • Geocoding via API for custom objects, with built-in integration for standard objects using address fields.

This approach ensures that the address data in your custom Salesforce objects is geocoded accurately and asynchronously, providing enhanced location-based insights.

For more information on using the Maps API, check out the Salesforce Maps Developer Guide.

Post a Comment

0 Comments