---
schema_version: "1"
id: 4bf3c4dd5e16e0f2a23e18b58da9c9591c145d385119663359a957685fbee1e9
title: Add a Geocode to a Custom Address Field
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/platform/caf-dev/guides/caf/caf-dev-add-geocode.md
canonical_url: https://developer.salesforce.com/docs/platform/caf-dev/guide/caf-dev-add-geocode.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 0e364f91a076745e42266fef7cdb816fa76ab3b8b6b0411d07ff7b160c7e4ede
products:
  - Custom Address Fields Developer Guide
  - Platform Developer Content
---

# 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](https://help.salesforce.com/s/articleView?id=xcloud.overview_edition_lex_only.htm)) 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`.

    <!-- otherprops: apex_code -->
    ```trigger
    public class GeoCodeExample {
        @future(callout=true)
        public static void parseJSONResponse() {  
            double lat;
            double lng;
            String city = null;
            String street = null;
               String stateCode = null; 
            String countryCode = null;
            
            Account record = [SELECT Mailing_Address__c FROM Account WHERE Id = 'Account ID'];
            Address customAddress = record.Mailing_Address__c;
            
            //Remove white spaces from address components
            if(customAddress.getCity() != null){
                 city = customAddress.getCity().deleteWhitespace();
            }
            if(customAddress.getStreet() != null){
                 street = customAddress.getStreet().deleteWhitespace();
            }
            if(customAddress.getStateCode() != null){
                 stateCode = customAddress.getStateCode();
            }
            if(customAddress.getCountryCode() != null){
                 countryCode = customAddress.getCountryCode();
            }    
            
            //concatenate strings
            String address = street+city+stateCode+countryCode;
            
            String key='API key';
            Http httpProtocol = new Http();
            // Create HTTP request to send.
            HttpRequest request = new HttpRequest();
            // Set the endpoint URL.
            // USING GOOGLE MAP API 
            String endpoint = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&key='+key;
            request.setEndPoint(endpoint);
            // Set the HTTP verb to GET.
            request.setMethod('GET');
            // Send the HTTP request and get the response.
            // The response is in JSON format.
            HttpResponse response = httpProtocol.send(request);
          
           // Parse JSON response to get all the totalPrice field values.
            JSONParser parser = JSON.createParser(response.getBody());
            
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                    (parser.getText() == 'lat')) {
                    parser.nextToken();
                    // Get latitude
                    lat = parser.getDoubleValue();
               
                    parser.nextToken();
                    parser.nextToken();
                    //Get longitude    
                    lng = parser.getDoubleValue();
                     } 
                  }
            // Update lat long of account record
            record.Mailing_Address__Latitude__s=lat;
            record.Mailing_Address__Longitude__s=lng;
            update record;
        }
    }
    ```

2.  Create a Visualforce page that triggers the geocode service from the map API.

    <!-- otherprops: apex_code -->
    ```trigger
    <apex:page id="pg" controller="GeoCodeExample">
    <apex:form >
        <apex:pageBlock id="pb">
            <apex:pageBlockButtons >
                <apex:commandButton value="Get GeoCode For Custom Address Field" 
                action="{!parseJSONResponse}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
    </apex:page>
    ```

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.](https://developer.salesforce.com/media/caf-dev/caf_dev_geocode_post_query.png)


To automate the process of updating custom address fields with latitude and longitude, set up a trigger to invoke the Apex class.

**note:** 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.

