Find nearest latitude/longitude with an SQL query

Basit picture Basit · Feb 10, 2010 · Viewed 217k times · Source

I have latitude and longitude and I want to pull the record from the database, which has nearest latitude and longitude by the distance, if that distance gets longer than specified one, then don't retrieve it.

Table structure:

id
latitude
longitude
place name
city
country
state
zip
sealevel

Answer

Kaletha picture Kaletha · Apr 5, 2011
SELECT latitude, longitude, SQRT(
    POW(69.1 * (latitude - [startlat]), 2) +
    POW(69.1 * ([startlng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < 25 ORDER BY distance;

where [starlat] and [startlng] is the position where to start measuring the distance.