Geolocation and distance
Select, filter, and order distances using structured coordinates.
This page uses a fictional Account.Office__c geolocation field. Replace it with a generated location field from your org.
The generated field value is SalesforceGeolocation, which has numeric latitude and longitude properties.
Query nearby records
import { db } from "./db";
const nearby = db
.selectFrom("Account")
.select(["Id", "Office__c"])
.select(({ fn }) =>
fn.distance("Office__c", fn.geolocation(-33.8688, 151.2093), "km")
.as("distanceFromSydney"),
)
.where((eb) =>
eb(
eb.fn.distance(
"Office__c",
eb.fn.geolocation(-33.8688, 151.2093),
"km",
),
"<",
25,
),
)
.orderBy(({ fn }) =>
fn.distance("Office__c", fn.geolocation(-33.8688, 151.2093), "km"),
)
.limit(50);fn.geolocation(latitude, longitude) validates finite coordinates within the normal latitude and longitude ranges.
fn.distance(locationField, destination, unit) accepts "mi" or "km". The destination can be a fixed geolocation() value or another compatible location field.
A selected distance needs an alias and returns a number, with nullability inherited from the source field or relationship.
Where distance is supported
Use distance() for:
- aliased record selections
WHEREcomparisons with<or>- ordering
Filtering requires a generated filterable location field. Ordering requires sortable location metadata.
Use the function expression again in orderBy(). A selected alias such as distanceFromSydney is a result property, not a Salesforce field you can order by.
Kysoql does not expose raw location equality, direct location ordering, distance equality, <= or >= distance filters, or geolocation grouping and aggregation.