Sub topic 10
Geolocation fields and location data
This chapter assumes you can create custom fields in Object Manager. It also assumes you have run basic SOQL queries and know what a field's API name is. The goal is to explain what a Geolocation field stores, how to query it, and when two plain Number fields are a better choice.
What a Geolocation field stores
A Geolocation field is a compound field. One field you create in Setup holds a latitude and a longitude together. Latitude is the position north or south of the equator, from -90 to 90. Longitude is the position east or west of the prime meridian, from -180 to 180.
When you create a Geolocation field named Location__c, Salesforce exposes three names:
| API name | What it is |
|---|---|
| `Location__c` | The compound field, which represents the point as a whole |
| `Location__Latitude__s` | The latitude component |
| `Location__Longitude__s` | The longitude component |
The __s suffix marks the two components. They behave like decimal numbers. You read and write them as separate values, and the compound field combines them for distance queries.
Creating the field
In Object Manager, choose Geolocation as the field type and set two options:
- Latitude and Longitude Display Notation: either decimal degrees (for example 37.7749) or degrees, minutes and seconds. This only changes how the value is shown to users.
- Decimal Places: how many digits appear after the decimal point. Six decimal places locate a point to within roughly a tenth of a metre, which is more than most business uses need.
In metadata, the field looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Location__c</fullName>
<label>Location</label>
<type>Location</type>
<displayLocationInDecimal>true</displayLocationInDecimal>
<scale>6</scale>
<required>false</required>
</CustomField>The metadata type is Location, not Geolocation. The scale element is the decimal place count, the same idea you saw with Number fields.
Where location data comes from
Salesforce does not fill a custom Geolocation field from an address. You supply the coordinates through one of these routes:
- A user types them in, which is rare and error-prone.
- A data load or integration writes
Location__Latitude__sandLocation__Longitude__s. - A mobile app or Lightning component captures the device position and saves it.
- An automation looks up an address with a geocoding service and writes the result.
Standard address fields are a separate case. Where geocoding is enabled, the standard addresses on Account, Contact and Lead can also carry latitude, longitude and geocode accuracy values. Those are standard fields. They are not your custom Geolocation field.
Querying by distance
The main reason to use a Geolocation field is distance. SOQL provides two functions for it:
GEOLOCATION(lat, lon)builds a point.DISTANCE(field, point, unit)returns the distance in'mi'or'km'.
You can use DISTANCE in WHERE and ORDER BY, and also in SELECT. Here is a method that finds the nearest warehouses to a point:
public with sharing class WarehouseFinder {
public static List<Warehouse__c> findNearby(Decimal lat, Decimal lon, Decimal maxKm) {
return [
SELECT Id, Name, Location__Latitude__s, Location__Longitude__s
FROM Warehouse__c
WHERE DISTANCE(Location__c, GEOLOCATION(:lat, :lon), 'km') < :maxKm
ORDER BY DISTANCE(Location__c, GEOLOCATION(:lat, :lon), 'km')
LIMIT 10
];
}
}Warehouse__c is an example custom object with a Geolocation field named Location__c. Apex bind variables (:lat, :lon, :maxKm) work inside these functions.
For a distance between two points you already hold in memory, Apex has a Location class. No query is needed:
Location sanFrancisco = Location.newInstance(37.7749, -122.4194);
Location oakland = Location.newInstance(37.8044, -122.2712);
Double km = sanFrancisco.getDistance(oakland, 'km');
System.debug(km);Limits and gotchas
- Restricted use in SOQL. You cannot compare a compound location field with
=or<. The field must appear insideDISTANCEorGEOLOCATION. Filter on the component fields only when you want a plain numeric range. - Formulas. A formula can use the compound field only inside
DISTANCEandGEOLOCATION. UseDISTANCEin a formula when you want a calculated distance to a fixed point. - Data loading. Load the two component fields,
__Latitude__sand__Longitude__s. Include both, because a point with only one coordinate is not valid. - Range checks. Values outside the latitude and longitude ranges are rejected. Swapped coordinates (longitude in the latitude column) are a common load error. A longitude such as -122 fails in the latitude column, but a swap of two small values passes silently and puts the point in the wrong place.
- No address lookup. The field does not convert an address to coordinates. That conversion is separate work.
- Reporting. Geolocation fields are not the same as map visualisation. Showing records on a map is a separate feature that uses addresses or coordinates.
Geolocation field or two Number fields
You could store latitude and longitude in two Number fields with a scale of 6 or more. That works for display and for plain filters. It does not give you DISTANCE queries. You would have to calculate distance in Apex or approximate it with a bounding box in the WHERE clause.
Choosing it in practice
Choose a Geolocation field when records are points on a map and users or code ask "what is near here?". Examples are stores, field service sites, warehouses and event venues. Choose standard address fields when the data is a mailing or billing address. Choose two Number fields when you only display coordinates or pass them to another system.
Exercise
A custom object stores service depots. Dispatchers need to list the five depots closest to a customer's coordinates. Which field type should hold the depot position, and which SOQL feature does the query use?
Show answer
Use a Geolocation field, because it supports distance queries. The query sorts with ORDER BY DISTANCE(Location__c, GEOLOCATION(lat, lon), 'km') and uses LIMIT 5.
Exercise
You load depot data from a spreadsheet into a Geolocation field named Location__c. Which field names must the load map the coordinates to?
Show answer
Map latitude to Location_Latitudes and longitude to LocationLongitude_s. Load both components, because the compound field itself is not loaded directly.