Newer Version Available

This content describes an older version of this product. View Latest

Get the Geographical Coordinates of an Address

The Geocode() Apex method takes a single address and returns the geographical coordinates and the formatted address.

To get the geographical coordinates of more than one address, use the BatchGeocode() Apex method.

Signature

1Map<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.

Sample Code

This code returns the geographical coordinates of the Salesforce headquarters. The output also returns the formatted address and adds missing information, such as postal code and country, if available.

Input Format of the Address

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

Example

1// Create and add an address.
2String salesforceAddress = '415 Mission Street, San Francisco, CA 94105 USA';
3
4Map<string,object> options = new Map<String,Object> {
5            'version' => '1', // Required. Version of the API endpoint. Must be '1'.
6            'address' => salesforceAddress
7        };
8
9// Call the Geocode() method with the address.
10Map<String, Object> response = maps.API.Geocode(options);
11
12// Log the resulting geographical coordinates and formatted address. 
13system.debug(response);

Sample 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.

1{
2  "baseUrl": "https://internal.na.sfmapsapi.com/core/geocoding/2?address=415+Mission+Street%2C+San+Francisco%2C+CA+94105+USA",
3  "data": {
4    "houseNumber": "415",
5    "matchLevel": "Address",
6    "score": 100,
7    "country": "USA",
8    "postal": "94105",
9    "state": "CA",
10    "city": "San Francisco",
11    "street": "Mission St",
12    "fullAddress": "415 Mission St, San Francisco, CA 94105, United States",
13    "position": {
14      "lng": -122.397,
15      "lat": 37.78977
16    }
17  },
18  "source": "http",
19  "success": true
20}

Sample Response If Not Geocoded

If an address can't be geocoded, you receive this 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.

1{
2  "success": false,
3  "message": "No results for that particular address."
4}