What Is The Distance Formula Apex? Simply Explained

7 min read

What’s the one thing that makes a map feel alive?
The ability to know exactly how far you are from a point of interest—whether it’s a rival’s base, the next loot drop, or a customer’s address. In Apex (the Salesforce‑flavored programming language), that magic lives in the distance formula That's the part that actually makes a difference..

If you’ve ever stared at a long list of latitude and longitude fields and wondered, “How far apart are these two records, really?” you’re not alone. Also, turns out the answer is a handful of lines of code, a sprinkle of trigonometry, and a solid grasp of what the formula actually does. Below is the deep dive you’ve been waiting for.


What Is the Distance Formula in Apex

At its core, the distance formula in Apex is a way to compute the straight‑line (great‑circle) distance between two points on the Earth’s surface given their latitude and longitude values. It’s not a Salesforce‑specific invention; it’s the same Haversine or “spherical law of cosines” math you see in GIS tools Worth keeping that in mind. Practical, not theoretical..

In Apex you usually write it as a formula field or a utility class that returns the distance in miles, kilometers, or even nautical miles. The key ingredients are:

  • Latitude of point A (lat1)
  • Longitude of point A (lon1)
  • Latitude of point B (lat2)
  • Longitude of point B (lon2)

All of those numbers have to be in decimal degrees, not radians. Apex will handle the conversion for you, but you need to remember the order of operations.

The math behind it

The most common version in Apex looks like this:

public static Double calculateDistance(
    Double lat1, Double lon1,
    Double lat2, Double lon2,
    String unit) {

    Double R = (unit == 'km') ? Here's the thing — radians(lat2 - lat1);
    Double dLon = Math. cos(Math.6371 : 3958.Day to day, cos(Math. sin(dLat/2) +
               Math.radians(lon2 - lon1);
    Double a = Math.Now, radians(lat1)) * Math. Which means sin(dLon/2) * Math. In practice, radians(lat2)) *
               Math. 8; // Earth radius
    Double dLat = Math.sin(dLat/2) * Math.sin(dLon/2);
    Double c = 2 * Math.Still, atan2(Math. sqrt(a), Math.

And yeah — that's actually more nuanced than it sounds.

That snippet is the Haversine formula wrapped in Apex’s `Math` class. The `R` constant swaps between kilometers and miles depending on what you ask for.  

If you prefer the spherical law of cosines, replace the `a`/`c` block with:

```apex
Double distance = Math.acos(
    Math.sin(Math.radians(lat1)) * Math.sin(Math.radians(lat2)) +
    Math.cos(Math.radians(lat1)) * Math.cos(Math.radians(lat2)) *
    Math.cos(Math.radians(lon2 - lon1))
) * R;

Both give you a “as‑the‑crow‑flies” distance that’s accurate enough for most business use cases.


Why It Matters / Why People Care

You might think, “Sure, it’s cool math, but why do I need it in my org?” Real‑world scenarios make the difference crystal clear Not complicated — just consistent..

  • Territory management – Sales reps often need to know which accounts fall within a 30‑mile radius of a regional office. A distance formula field lets you filter those accounts instantly, no external GIS tool required.
  • Field service routing – Dispatchers can assign technicians based on proximity, cutting travel time and fuel costs.
  • Event planning – Marketing teams can target attendees who live near a venue, improving conversion rates on local promotions.
  • Compliance – Some regulations require you to prove that a service location is within a certain distance of a customer’s address. Having the calculation baked into Salesforce means audit trails are automatic.

When you skip the distance check, you end up with missed opportunities, wasted mileage, or even compliance headaches. Here's the thing — the short version? Knowing the distance in Salesforce saves you time, money, and a few headaches Which is the point..


How It Works (or How to Do It)

Below is a step‑by‑step guide that walks you from a blank org to a fully functional distance calculator. I’ll cover three common approaches:

  1. Formula field – quick, declarative, no code.
  2. Apex utility class – reusable, works on bulk data.
  3. Lightning component – real‑time distance display on a record page.

Feel free to pick the one that matches your comfort level.

1. Formula Field Approach

If you only need the distance between a record and a single reference point (say, your headquarters), a formula field is the fastest route.

  1. Create custom fields for Latitude and Longitude on the object you’re measuring (e.g., Account.Latitude__c, Account.Longitude__c).
  2. Add a custom text field to hold the reference point’s coordinates, or hard‑code them directly in the formula.
  3. Create a new formula field (Number) called Distance_from_HQ__c. Use the following expression (Miles version):
6371 * ACOS(
    SIN(RADIANS(Latitude__c)) * SIN(RADIANS(40.7128)) +
    COS(RADIANS(Latitude__c)) * COS(RADIANS(40.7128)) *
    COS(RADIANS(Longitude__c - (-74.0060)))
)

Replace 40.7128 and -74.Which means 0060 with your HQ’s latitude/longitude. Change 6371 to 3958.8 for miles.

  1. Add the field to page layouts and reports. That’s it. The formula runs automatically whenever the record is saved.

Pros: No code, instant results, works in reports.
Cons: Not bulk‑friendly; each record stores its own distance, which can be wasteful if you have many reference points That alone is useful..

2. Apex Utility Class

When you need to compute distances on the fly, compare a record against multiple locations, or run the calculation in a batch, an Apex class is the way to go Simple, but easy to overlook..

a. Build the class

Create a new Apex class called DistanceUtil. Paste the Haversine method shown earlier. Add a helper method that accepts a list of records:

public static Map distancesToLocation(
    List records,
    Double targetLat,
    Double targetLon,
    String unit) {

    Map results = new Map();
    for (SObject rec : records) {
        Double lat = (Double)rec.get('Latitude__c');
        Double lon = (Double)rec.get('Longitude__

Double lon = (Double)rec.get('Longitude__c');
        
        if (lat !Now, = null && lon ! = null) {
            Double dist = calculateHaversineDistance(lat, lon, targetLat, targetLon, unit);
            results.put(rec.

#### b. Call it from a trigger or batch

```apex
// Example: Update all Accounts with distance to NYC office
List accs = [SELECT Id, Latitude__c, Longitude__c FROM Account WHERE Latitude__c != NULL];
Map distances = DistanceUtil.distancesToLocation(accs, 40.7128, -74.0060, 'miles');

for (Account a : accs) {
    a.Distance_to_NYC__c = distances.get(a.

**Pros:** Reusable, handles bulk operations, flexible with multiple target locations.  
**Cons:** Requires code deployment, slightly higher maintenance.

### 3. Lightning Component (Real‑Time)

For scenarios where users need to see distance **as they work**—like a field agent checking proximity to the next stop—a Lightning component delivers instant feedback without saving anything.

#### a. Create the component

```javascript
// distanceCalculator.js
import { LightningElement, api } from 'lwc';
import getDistance from '@salesforce/apex/DistanceUtil.getDistance';

export default class DistanceCalculator extends LightningElement {
    @api recordId;
    targetLat = 40.7128;
    targetLon = -74.0060;
    distance;

    connectedCallback() {
        getDistance({ recordId: this.recordId, targetLat: this.targetLat, targetLon: this.But targetLon })
            . then(result => {
                this.distance = result;
            })
            .catch(error => {
                console.

#### b. Add an Apex controller method

```apex
@AuraEnabled
public static Double getDistance(Id recordId, Double targetLat, Double targetLon) {
    SObject rec = [SELECT Latitude__c, Longitude__c FROM Account WHERE Id = :recordId LIMIT 1];
    return DistanceUtil.calculateHaversineDistance(
        (Double)rec.get('Latitude__c'),
        (Double)rec.get('Longitude__c'),
        targetLat, targetLon, 'miles'
    );
}

c. Deploy to the record page

Add the component to the Account record page via Lightning App Builder. Users now see the distance to your reference point the moment the record loads It's one of those things that adds up. But it adds up..

Pros: Real‑time, interactive, great for mobile users.
Cons: Requires Lightning Experience, depends on API calls Still holds up..


Which Path Should You Take?

Approach Best For Complexity
Formula Single reference point, simple reporting Low
Apex Bulk processing, multiple targets, scheduled jobs Medium
Lightning Real‑time user experience, mobile field teams High

If you're just getting started, the formula field is the low‑effort win. As your use cases grow—think logistics fleets, multi‑branch routing, or dynamic customer segmentation—invest in the Apex and Lightning options.


Final Thoughts

Distance isn't just a number in Salesforce; it's a strategic asset. Plus, by embedding geographic context directly into your data model, you tap into smarter routing, tighter compliance, and faster decision‑making. Whether you choose the declarative route or go full code, the key is matching the complexity of the solution to the maturity of your org.

Start small, measure the impact, and scale up. Your customers—and your sales team—will thank you for the extra miles saved And that's really what it comes down to..

This Week's New Stuff

Current Topics

Fits Well With This

Before You Head Out

Thank you for reading about What Is The Distance Formula Apex? Simply Explained. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home