Location-Based SOQL Queries in Salesforce
In Salesforce, location-based SOQL queries allow you to retrieve records based on their geographic location. This feature is particularly useful for applications that require proximity-based searches or location-aware functionality. Location-based SOQL queries leverage the Salesforce Object Query Language (SOQL) along with the geolocation fields available in custom objects or standard objects like Account, Contact, and Lead.
Location-Based SOQL Query Considerations
Location-based queries are supported in SOQL in Apex and in the SOAP and REST APIs. Keep in mind these considerations.
DISTANCE and GEOLOCATION are supported in WHERE and ORDER BY clauses in SOQL, but not in GROUP BY. DISTANCE is supported in SELECT clauses.
DISTANCE supports only the logical operators > and <, returning values within (<) or beyond (>) a specified radius.
When using the GEOLOCATION function in SOQL queries, the geolocation field must precede the latitude and longitude coordinates. For example, DISTANCE(warehouse_location__c, GEOLOCATION(37.775,-122.418), 'km') works but DISTANCE(GEOLOCATION(37.775,-122.418), warehouse_location__c, 'km') doesn’t work.
Apex bind variables aren’t supported for the units parameter in the DISTANCE function. This query doesn’t work.
Geolocation Fields:
Salesforce provides special geolocation fields (Geolocation) that store latitude and longitude coordinates for a specific location. These fields can be added to custom objects or certain standard objects to store location data.
Geolocation fields can be populated manually or automatically using integration with mapping services or external data sources.
SOQL Queries:
Location-based SOQL queries enable you to search for records based on their proximity to a specified location.
You can use the DISTANCE and GEOLOCATION() functions in SOQL to perform location-based queries.
Here's an example of a simple SOQL query to retrieve Accounts within a certain distance from a specified location:
SELECT Id, Name, BillingLatitude, BillingLongitudeFROM Account
WHERE DISTANCE(BillingAddress, GEOLOCATION(latitude, longitude), 'mi') < 10
Comments
Post a Comment