gpt4 book ai didi

php mysql比较long和lat,返回10英里以下的

转载 作者:可可西里 更新时间:2023-11-01 06:42:22 25 4
gpt4 key购买 nike

嘿,我想使用纬度和经度值找到 2 个位置之间的距离(以英里为单位),并检查它们是否在彼此的 10 英里半径范围内。

当用户登录时,他们的纬度/经度值会保存在 session 中

$_SESSION['lat']
$_SESSION['long']

我有两个函数

这个计算出以英里为单位的距离并返回一个四舍五入的值

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);
}

如果两组纬度和经度之间的距离小于 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。

现在,我有一个“位置”数据库(4 个字段 - ID、名称、纬度、经度)。

我想找到 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 "<br>";

样本结果是

goodison park is 7 miles form your house, is it with a 10 mile radius? yeah

我需要以某种方式在我的查询中执行 is_within_10_miles 函数。

编辑编辑

这个图例来自 http://www.zcentric.com/blog/2007/03/calculate_distance_in_mysql_wi.html想出了这个...

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

它确实有效。问题是我想选择 * 行,而不是一一选择。我该怎么做?

最佳答案

您可能不需要在代码中执行此操作,您可能可以在数据库中执行所有操作。如果你使用 spatial index . MySQL docuemtnation for spatial index

编辑以反射(reflect)您的编辑:

我想你想要这样的东西:

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 locations HAVING distance<='10' ORDER BY distance ASC

VIA: http://www.zcentric.com/blog/2007/03/calculate_distance_in_mysql_wi.html :

关于php mysql比较long和lat,返回10英里以下的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2296824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com