[SalesForce] can geolocation fields be used to calculate and display distance

I have a geolocation field setup on an object and want to be able to display the distance from another location in miles on a Visualforce page. I see with the new geolocation fields you can use DISTANCE in the WHERE clause combined with <, >, and other operators but I'd like to see the actual distance not just filter the results, is this possible without using an outside API?

Best Answer

You can use the DISTANCE and GEOLOCATION formula functions to create a custom field that will calculate the distance in miles to a fixed location. Then you can use this field in your Visualforce pages as required.

DISTANCE(acme_distribution__c, GEOLOCATION(37.775,-122.418), "mi")

Failing that, you can do the haversine formula calculation yourself in Apex:

public Decimal calculateHaversineDistance(Decimal lat1, Decimal lon1, Decimal lat2, Decimal lon2){
    // Earth's radius varies from 6356.752 km at the poles to 6378.137 km at the equator
    Double radius = 6371.00;
    Double dLat = toRadians(lat2-lat1);
    Double dLon = toRadians(lon2-lon1);
    Double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
    Double c = 2 * Math.asin(Math.sqrt(a));

    double kmToMiles = 0.621371;
    return radius * c * kmToMiles;
}

private Double toRadians(Decimal degree){
    return degree * 3.1415926 / 180;
}

Note that this includes the conversion from kilometres to miles in case you are in one of the three countries in the world that don't use the metric system :)

You may want to work to, say, 4 significant figures, as there are a number of simplifications in this approach.

Related Topic