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
¢er_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.