我希望使用lat和long值找到2个位置之间的距离(以英里为单位),并检查它们是否在彼此10英里范围内.
当用户登录时,他们的纬度/经度值将保存在会话中
$_SESSION['lat']
$_SESSION['long']
我有2个功能
这个以英里为单位计算距离并返回舍入值
function distance($lat1, $lng1, $lat2, $lng2){
$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lng1 *= $pi80;
$lat2 *= $pi80;
$lng2 *= $pi80;
$r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 - $lat1;
$dlng = $lng2 - $lng1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$km = $r * $c;
return floor($km * 0.621371192);
}
如果两组lat和long之间的距离小于10,则返回bool.
function is_within_10_miles($lat1, $lng1, $lat2, $lng2){
$d = distance($lat1, $lng1, $lat2, $lng2);
if( $d <= 10 ){
return True;
}else{
return False;
}
}
这两个函数按预期工作,如果我给出2组纬度/长度并且它们之间的距离是20英里,我的is_within_10_miles()函数返回false.
现在,我有一个’locations’数据库(4个字段–ID,name,lat,long).
我想找到半径10英里范围内的所有位置.
有任何想法吗?
编辑:我可以循环遍历所有并像这样在它们上执行is_within_10_miles()
$query = "SELECT * FROM `locations`";
$result = mysql_query($query);
while($location = mysql_fetch_assoc($result)){
echo $location['name']." is ";
echo distance($lat2, $lon2, $location['lat'], $location['lon']);
echo " miles form your house, is it with a 10 mile radius? ";
if( is_within_10_miles($lat2, $lon2, $location['lat'], $location['lon']) ){
echo "yeah";
}else{
echo "no";
}
echo "
";
}
样本结果将是
goodison park is 7 miles form your house, is it with a 10 mile radius? yeah
我需要以某种方式在我的查询中执行is_within_10_miles函数.
编辑编辑
SELECT ((ACOS(SIN($lat * PI() / 180) * SIN(lat * PI() / 180) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * COS(($lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM members HAVING distance<='10' ORDER BY distance ASC
它确实有效.问题是我想选择*行,而不是逐个选择它们.我怎么做?