Skip to content

Instantly share code, notes, and snippets.

@robotmay
Created March 2, 2011 16:55
Show Gist options
  • Save robotmay/851250 to your computer and use it in GitHub Desktop.
Save robotmay/851250 to your computer and use it in GitHub Desktop.
SQL query to search based on latitude, longitude, and a distance in miles from a location
# Using an example table of 'addresses' with a latitude and longitude column
# Replace #LONGITUDE#, #LATITUDE#, and #DISTANCE_IN_MILES# with your search values
SELECT addresses.*, (ACOS( SIN(RADIANS(#LATITUDE#)) * SIN(RADIANS(addresses.latitude)) + COS(RADIANS(#LATITUDE#)) * COS(RADIANS(addresses.latitude)) * COS(RADIANS(addresses.longitude) - RADIANS(#LONGITUDE#)) ) * 3963.1676) AS distance
FROM addresses
WHERE (((ACOS( SIN(RADIANS(#LATITUDE#)) * SIN(RADIANS(addresses.latitude)) + COS(RADIANS(#LATITUDE#)) * COS(RADIANS(addresses.latitude)) * COS(RADIANS(addresses.longitude) - RADIANS(#LONGITUDE#)) ) * 3963.1676) <= #DISTANCE#) OR (addresses.latitude = #LATITUDE# AND addresses.longitude = #LONGITUDE#))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment