I have a database which holds different locations, each of which has its own longitude and latitude variable. I want to be able to use a distance function I made that returns the distance between two longitudes and latitudes in my WHERE statement. So I am looking for the distance between two points and it pass the WHERE statement if it is less than the radius I am searching.
distance function:
function distance($lat1, $lon1, $lat2, $lon2) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
return $miles;
}
inside my SELECT statement I want something like this:
SELECT * FROM Locations WHERE distance($latitude, $longitude, 'latitude', 'longitude')
however that is not working. I have tried these without any luck...
"SELECT * FROM Locations WHERE distance($latitude, $longitude, 'latitude', 'longitude') < $radius"
and
sprintf("SELECT * FROM Locations WHERE %f < $radius", distance($latitude, $longitude, 'latitude', 'longitude'))
Is this even possible to preform? If not what is a good way around this problem? Thanks!
EDIT: I tried to do
"SELECT * FROM Locations WHERE '" . distance('Latitude', 'Longitude', $latitude, $longitude) . "' < $radius"
but it didn't work however if I just echo it it outputs the result I am looking for. But it doesn't work right when I try to use it inside mysqli_query