+ Start a Discussion
Ola BamideleOla Bamidele 

How to use Haversine to calculate distance from somewhere to where you are

Hi gurus, 

I have created an appp when shows leads on a map however, I want to also add a feature which displays the distance of the lead on the map.

I was told to look into Haversine and ive done so but my understanding on how to write it is not good at the moment as I just began.

So does anyone please know what i need to add to my code to display the distance on the map please?

This is my code:
public with sharing class AccountController {
    public static List<Account> findAll() {
    return [SELECT id, name, Location__Latitude__s, Location__Longitude__s, Industry
            FROM Account
            WHERE Location__Latitude__s != NULL AND Location__Longitude__s != NULL
            LIMIT 50];

Please if you know what i need to add then let me kno please!
NagendraNagendra (Salesforce Developers) 
Hi Ola,

Salesforce now has a DISTANCE() function which can be used in formula fields, but it is only "straight-line" distance and not the distance you would travel is using roads.

I use this in a custom formula field today to help sales agents prioritize and identify Leads nearest them.

One Example: Distance between two geolocation fields
DISTANCE(warehouse_location__c, store_location__c, 'mi')
This formula returns the distance, in miles, between the warehouse and the store. In this example, warehouse_location__c and store_location__c are the names of two custom geolocation fields.
  • https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_functions_a_h.htm&language=en_US#DISTANCE
To easily get driving directions, you can create a custom formula field with the type of URL that will open GoogleMaps with the geocoordinates populated as parameters. You can use Merge fields in Salesforce to get the Lat/Lon values for each geolocation.
  • https://www.google.com/maps?saddr=29.653,-95.577&daddr=29.753,-95.577
saddr is your starting point daddr is your destination.

When the map loads, you can see driving distance and instantly get directions. What's nice is this also works seamlessly on mobile devices from the salesforce1 app.

Hope this helps.

Kindly mark this as solved if the reply was helpful.

Ola BamideleOla Bamidele
Hi Nagendra, 

Thanks for your response, the information made this a lot clearer.

However, I am trying to find the distance from where the person is that makes sense?

So  in Salesforce1 app, when someone logs on, we want to display the distance that that person is from a lead. So the coding needs to be dynamic rather than fixed in the code. 

Hope I explained that better.

Thanks very much!