Haversine calculation: Show users within set

285 views Asked by At

Building a carpooling app for my local community built on PHP and SQL. While I'm usually ofay with php coding, I'm stumped looking for the mathematical formula needed to list:

  • Top 5 nearby users, ordered from closest to furthest given the long / lat of the primary user
  • Limited to those within 500 meters of the primary users long / lat

The SQL database contains the long / lat of every online user that is updated at 5 minute intervals.

Have searched around, but think I may be looking for the wrong thing. Any guidance is greatly appreciated.

1

There are 1 answers

1
david strachan On BEST ANSWER

The following SQL query uses Spherical Law of Cosines to calculate the distance between a coordinate and coordinates in a table.

d = acos( sin(lat1).sin(lat2) + cos(lat1).cos(lat2).cos(lng2-lng1) ).R

The query uses SQL Math functions

require("dbinfo.php");//database parameters
&center_lat = primaryLat;
$center_lng = primarylng;
$radius =  0.5;//500 meters

$arr = array();
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    // Prepare statement
    $stmt = $dbh->prepare("SELECT  name, lat, lng, ( 3959 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM gbstn HAVING distance < ? ORDER BY distance LIMIT 0 , 5");
    // Assign parameters
    $stmt->bindParam(1,$center_lat);
    $stmt->bindParam(2,$center_lng);
    $stmt->bindParam(3,$center_lat);
    $stmt->bindParam(4,$radius);
    //Execute query
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    $stmt->execute();
    //Show the results  
    while($obj = $stmt->fetch()) {  
        $arr[] = $obj;
    }
    if (count($arr) >= 1)
    {
        echo '{"marker":'.json_encode($arr).'}';
    }else{
        echo '{"marker":[{"name":"No Results","lat":'.$center_lat.',"lng":'.$center_lng.',"distance":0}]}';  
    }

}


catch(PDOException $e) {
    echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing 
    file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", mapSelect.php, ". $e->getMessage()."\r\n", FILE_APPEND);  
 }
//Close the connection
$dbh = null; 
?>

Using PDO instead of deprecated mysql_ functions.

You will require to modify the statement to suit . Also remove the echo in catch block after debugging.