SQL – Select Closest Locations

This is an older script but still works nicely.

Setup: You have a table with medical centers that has the address along with latitude and longitude columns.

I used this script with a GPS application that pulled your current location and sent it to a web service to get the results.

GPS Provided Latitude: 43.0011
GPS Provided Longitude: -83.7742

SELECT TOP 20 *, ( 3959 * acos( cos( radians(43.0011) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-83.7742) ) + sin( radians(43.0011) ) * sin( radians( lat ) ) ) ) AS distance 
FROM MedicalCenters 
WHERE ( 3959 * acos( cos( radians(43.0011) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-83.7742) ) + sin( radians(43.0011) ) * sin( radians( lat ) ) ) ) < 250
ORDER BY distance
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.