为我的本地社区构建一个基于PHP和SQL的拼车应用程序。虽然我通常对php编码很感兴趣,但我很难找到列出所需的数学公式:
- 前5名附近用户,根据主要用户的长/纬度从最近到最远排序
- 仅限于距离主要用户长/纬度500米以内的用户
SQL数据库包含每个在线用户的long/lat,每隔5分钟更新一次。
我四处寻找,但我想我可能找错东西了。非常感谢任何指导。
以下SQL查询使用余弦球面定律来计算坐标与表中坐标之间的距离。
d=acos(sin(lat1).sin(lat2)+cos(lat1
查询使用SQL数学函数
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;
?>
使用PDO而不是不推荐使用的mysql_
函数。
您将需要修改声明以适应。调试后,还要删除catch块中的echo。