Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer
    
Unfortunately the custom field option won't work since I need to display the distance between a selected event and other events so it needs to be more dynamic. I also learned I need the driving distance not 'as the crow flies' distance so I'll need to use an API anyway. It looks like the haversine formula would work for actual distance. It'd be nice if they'd expose the logic that DISTANCE uses in the MATH or perhaps a GEOLOCATION class. –  Phil B May 28 at 15:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.