Search code examples
phpmysqlgeolocation

PHP mysqli_fetch_array selecting smallest values


Hey guys and thanks for your help. What I'm trying to do is use the latitude and longitude from a user, and compare it to the latitude and longitude I have saved in my DB with associated names of cities. The code I have now, works, but the problem is there could be more than one row within a 30 mi radius. Take a look at my code, help me if you can.

<?php function distance($lat1, $lon1, $lat2, $lon2) {

    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lon1 *= $pi80;
    $lat2 *= $pi80;
    $lon2 *= $pi80;

    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlon = $lon2 - $lon1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;

    //echo '<br/>'.$km;
    $km = $km * 0.621371;
    return $km;
 }
    include_once("dbconnect.php");
    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }
    $grabCities = "SELECT * FROM cities";
    $result = $mysqli->query($grabCities);
    while($row = mysqli_fetch_array($result)){ 
    $distance = distance(41.08866717,-81.4780426,$row['lat'],$row['longitude']);
    if ($distance < 30){
        echo $myCity = $row['City'] . "<BR>";
    }

    }
    $mysqli->close();
?>

Solution

  • You can do this using MYSQL, 1 result returned which is the one your want.

    sprintf('
        SELECT
            *,
            (((acos(sin((%1$d*pi()/180)) * 
                sin((`lat`*pi()/180))+cos((%1$d*pi()/180)) * 
                cos((`lat`*pi()/180))*cos(((%2$d-`longitude`) * 
                pi()/180))))*180/pi())
            ) as distance
            FROM `cities` 
        ORDER BY
            distance ASC
        LIMIT 1
        ',
        $latitude,
        $longitude
    );