# 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.

• Today I have exactly same question. I need to find out distance between nearest service center(based on customer's address) and customer's zip code. Can you help me out how did you resolve the issue. Thank You! Commented Jan 27, 2017 at 0:45

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
``````

Additional potentially useful features to go from the Zip Code to the geolocaiton:

• Thanks Daniel. I will check with my team and come back with our findings. Commented Aug 3, 2014 at 3:44
• @daniel - how do you resolve the zip code that the user enters to lat long? are you making an api call out? Commented Feb 3, 2023 at 5:38
• @PartOfTheOhana I've added some more useful links that could help you get from the zip code to the geolocation. Commented Feb 3, 2023 at 16:26