Add a Geocode to a Custom Address Field

The method to get geocodes differs between standard and custom address fields. To give your users precise geographical information, add geocode information to a custom address field with Apex, Visualforce, and a map API.

Available in: both Salesforce Classic (not available in all orgs) and Lightning Experience
Available in: all editions
User Permissions Needed
To modify user interface settings:Customize Application
  1. Create an Apex class that retrieves latitude and longitude from your preferred map API. This example calls the Google Map API as defined in the String variable endpoint.

  2. Create a Visualforce page that triggers the geocode service from the map API.

  3. On the Visualforce page, click Get GeoCode For Custom Address Field to trigger the code. To see the latitude and longitude values populated, query the account information in Developer Console.

    Query results in Developer Console.

To automate the process of updating custom address fields with latitude and longitude, set up a trigger to invoke the Apex class.

The example in this topic uses a third-party map API to retrieve latitude and longitude. Using a Salesforce trigger to invoke this Apex class calls the map API each time the class is invoked. This action can result in charges from your API provider.