Hay. I want to find the distance (in miles) between two points using the lat and long values, and check if they are within 10 miles of each other.
When a user logs in, their lat / long values ββare stored in the session
$_SESSION['lat'] $_SESSION['long']
I have 2 functions
This sets the distance in miles and returns a rounded value
function distance($lat1, $lng1, $lat2, $lng2){ $pi80 = M_PI / 180; $lat1 *= $pi80; $lng1 *= $pi80; $lat2 *= $pi80; $lng2 *= $pi80; $r = 6372.797; // mean radius of Earth in km $dlat = $lat2 - $lat1; $dlng = $lng2 - $lng1; $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); $km = $r * $c; return floor($km * 0.621371192); }
This returns bool if the distance between the two sets of lat and long is less than 10.
function is_within_10_miles($lat1, $lng1, $lat2, $lng2){ $d = distance($lat1, $lng1, $lat2, $lng2); if( $d <= 10 ){ return True; }else{ return False; } }
Both functions work as expected, if I give 2 sets of lats / lengths and say the distance between them is 20 miles, the is_within_10_miles () function returns false.
Now I have a database of "location" (4 fields - identifier, name, lat, long).
I want to find all locations within a 10 mile radius.
Any ideas?
EDIT: I can scroll ALL and execute on them as is_within_10_miles () like this
$query = "SELECT * FROM `locations`"; $result = mysql_query($query); while($location = mysql_fetch_assoc($result)){ echo $location['name']." is "; echo distance($lat2, $lon2, $location['lat'], $location['lon']); echo " miles form your house, is it with a 10 mile radius? "; if( is_within_10_miles($lat2, $lon2, $location['lat'], $location['lon']) ){ echo "yeah"; }else{ echo "no"; } echo "<br>";
}
Sample result will be
goodison park is 7 miles form your house, is it with a 10 mile radius? yeah
I need to somehow execute the is_within_10_miles function in my request.
EDIT EDIT
This legend from http://www.zcentric.com/blog/2007/03/calculate_distance_in_mysql_wi.html came up with this ...
SELECT ((ACOS(SIN($lat * PI() / 180) * SIN(lat * PI() / 180) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * COS(($lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM members HAVING distance<='10' ORDER BY distance ASC
It really works. The problem is that I want to select * rows, and not select them one at a time. How to do it?