[SalesForce] Find nearest branch from ZIP code entered by customer

We need to calculate the distance between the ZIP code entered by customer and the nearest branch (Branch is an object) to that ZIP code address. The Lat and Long values are calculated for both ZIP and all the branches. However, need to find some logic on how to figure out nearest branch based on these values.

To explain more, we have an input field where customer fills out the ZIP code, then we have to provide them nearest branch of the customer available in that area.

They have 203 Branches, we have all the details of the Branches, including their Lat and Long values.

The drop down options should be like this : The nearest branch within that range should be the first option. Second nearest will be second option and so on.

The approach followed currently is :

We are getting the Long and Lat values of the ZIP code entered by customer from Google API, we have Long and Lat values of the branches in the Branch Table. We need some logic to figure out the nearest branch based on these values.

We are also able to pull out the branches which have Lat values greater than that of the Customer's ZIP value. But that may or may not be the nearest branch.

Please advise/guide on the logic of how to get the nearest branch for mentioned ZIP code.

Best Answer

This seems like a good candidate for the SOQL Geolocation support.

Try something like the following to find the first 10 branches within 20 kilometers ordered by closest branches first.

SELECT Id, Name
FROM Branch__c 
WHERE DISTANCE(Location__c, GEOLOCATION(37.775,-122.418), 'km') < 20 
ORDER BY DISTANCE(Location__c, GEOLOCATION(37.775,-122.418), 'km')
LIMIT 10
Related Topic