Retrieve the geographical coordinates of an address.

The Geocode() Apex method accepts a single address and provides the geographic coordinates along with the formatted address. If you need to obtain the geographical coordinates for multiple addresses, you should employ the BatchGeocode() Apex method.

Function Signature

Map<String, Object> maps.API.Geocode(Map<String, Object> options)

Where,

  • maps is the namespace that’s available after you install Salesforce Maps.
  • API is the class that contains the global methods exposed to developers.
  • Geocode() is the method.

Example Code

This code fetches the geographic coordinates of the Salesforce headquarters. The output also provides the formatted address and includes any missing details, like postal code and country, if they are accessible.

Warning

If you invoke methods within a flow, process builder, or trigger, do one of the following to avoid uncommitted work errors.

  • Call the methods through a future method
  • Call the methods as queueable

Different processes refresh the token, such as plotting a route or schedule. The refresh process is almost immediate after each qualifying action occurs.

Address Input Format

String address = '{HouseNumber} {Street}, {City}, {State} {PostalCode} {Country}';
String address = '{HouseNumber} {Street}, {City}, {State}';

Illustration

// Create and add an address.
String salesforceAddress = '415 Mission Street, San Francisco, CA 94105 USA';

Map<string,object> options = new Map<String,Object> {
            'version' => '1', // Required. Version of the API endpoint. Must be '1'.
            'address' => salesforceAddress
        };

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

// Log the resulting geographical coordinates and formatted address. 
system.debug(response);

Exemplary Response

Although the return value is an Apex Map<String, Object> object, this JSON response illustrates the essential data you receive in the resulting map.

If you invoke this method within a flow, process builder, or trigger and want to use the data from the JSON response, implement logic to retrieve that data. For example, you want to save the latitude and longitude coordinates from the JSON response to your records.

{
  "baseUrl": "https://internal.na.sfmapsapi.com/core/geocoding/2?address=415+Mission+Street%2C+San+Francisco%2C+CA+94105+USA",
  "data": {
    "houseNumber": "415",
    "matchLevel": "Address",
    "score": 100,
    "country": "USA",
    "postal": "94105",
    "state": "CA",
    "city": "San Francisco",
    "street": "Mission St",
    "fullAddress": "415 Mission St, San Francisco, CA 94105, United States",
    "position": {
      "lng": -122.397,
      "lat": 37.78977
    }
  },
  "source": "http",
  "success": true
}

Exemplary Response in Case of Non-Geocoded Data

{
  "success": false,
  "message": "No results for that particular address."
}