views:

53

answers:

1

i have a database table with a list of restaurants including their names, latitudes, and longitudes. i would like to select all the restaurants that are within a certain distance from my current location. the current location is determined in the php file (right now i'm just using a static lat & lng). i found code for calculating the distance:

function findDist($lat, $lng){
    $currLat = 33.777563;
    $currLng = -84.389959;

    $currLat = deg2rad ($currLat);
    $sincurrLat = sin ($currLat);
    $lat = deg2rad ($lat);
    $currLng = deg2rad ($currLng);
    $lng = deg2rad ($lng);

    return round((7926 - 26 * $sincurrLat) * asin (min (1, 0.707106781186548 * sqrt ((1 - (sin ($lat) * $sincurrLat) - cos ($currLat) * cos ($lat) * cos ($lng - $currLng))))),4);
}  

but how do i incorporate that into my select query? i tried this:

$query = "SELECT *
FROM
    eateries E
WHERE
    EXISTS
    (
        SELECT *
        FROM
            eateries_hours EH, eateries_type ET
        WHERE
            EH.eateries_id = E.id AND ET.eateries_id = E.id
            AND findDist(E.lat, E.lng) <= .5
    )";

but of course that doesn't work because it's not recognizing the function. can i do a separate query just for lats and lngs at first, calculate the distances, and then join that with the above query somehow? any ideas?

thanks.

+2  A: 

Take a look at a question that I previously answered. You can create a stored function in MySQL (or other databases) that does this provided that you have the latitudes and longitudes.

DELIMITER $$

DROP FUNCTION IF EXISTS `FindDist` $$
CREATE FUNCTION `FindDist` (lt1 DOUBLE,lg1 DOUBLE,lt2 DOUBLE,lg2 DOUBLE) RETURNS DOUBLE
DETERMINISTIC
BEGIN
    DECLARE dist,eradius DOUBLE;

    SET eradius=3963.1;
    SET dist=Acos(Cos(lt1) * Cos(lg1) * Cos(lt2) * Cos(lg2) + Cos(lt1) * Sin(lg1) * Cos(lt2) * Sin(lg2) + Sin(lt1) * Sin(lt2)) * eradius;
    RETURN dist;
END $$

DELIMITER ;
Buggabill
http://dev.mysql.com/doc/refman/5.1/en/stored-routines.html This is the MySQL documentation for stored procedures and functions
gawpertron
thanks for the help! this looks like it'll work. unfortunately i'm getting an error but i think it's an issue with phpMyAdmin and not with the code. i'll work on figuring it out. by the way, what unit distance (miles, km, etc.) does this function output?
vee
This is in miles. To output it in km, change the value of `eradius` to 6378.1.
Buggabill