如何从 MySql 查询中提供的纬度和经度获取半径范围内的所有结果

How to get all the results within radius from provided lat and long from MySql Query

我的本地服务器上有一个 MySQL table。 table 包括用户标记地点的纬度和经度。我正在尝试获取所有在提供的纬度和经度 1 公里范围内标记其位置的 ID。但是我的结果不是预期的。

Table: map_locations

id  user_id lat     lng     place_name
1   1   28.584688   77.31593    Sec 2, Noida
2   2   28.596026   77.314494   Sec 7, Noida
3   5   28.579876   77.356131   Sec 35, Noida
4   1   28.516831   77.487405   Surajpur, Greater Noida
5   1   28.631451   77.216667   Connaught Place, New Delhi
6   2   19.098003   72.83407    Juhu Airport, Mumbai

这是PHP脚本

$lat = '28.596026';
$long = '77.314494';
$query = "SELECT  id,
                  (6371 * acos( cos( radians($lat) ) * cos( radians('lat') ) *
                        cos( radians('lng') - radians($long)) +
                        sin(radians($lat)) * sin(radians('lat')) )
                  ) as distance
    FROM  map_locations
    HAVING  'distance' < 1
    ORDER BY  id
    LIMIT  25";

$_res = mysqli_query($conn, $query) or die('Error query:  '.$query);
$detail = array();
$i=0;
while($row = $_res->fetch_assoc()) {
    $detail[$i] = $row['id'];
    $i++;
}
print_r($detail);

结果:

Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
   [4] => 5
   [5] => 6
)

查询 returns 来自 table 的所有记录。任何人都可以让我知道查询中有什么问题吗?

是的,有可能所有记录都在 1 公里以内,唯一的建议是您尝试更改距离。

让我再次为您修改查询,然后检查它是否为您提供了完美的结果

$query = "SELECT id,(6371 * acos( cos( radians($lat) ) * cos( radians('lat') ) * cos( radians('lng') - radians($long)) + sin(radians($lat)) * sin(radians('lat')) )) as distance FROM map_locations HAVING 'distance' < 0.5 ORDER BY id LIMIT 25";

您也可以通过更改给定的手动经纬度进一步检查,

$lat = '21.591026';
$long = '79.314994';

如果有任何疑问,请告诉我。

您的查询包含一些带引号的字符串,例如 'lat'、'long' 和 'distance',其中应包含列名称,例如纬度、经度和距离。

特别是它以

结尾
 HAVING 'distance' < 0.5

这总是正确的,因为 MySQL 在数字上下文中使用字符串时总是将它们强制转换为数字。 MySQL 看起来像 HAVING 0 < 0.5。你想要

 HAVING distance < 0.5 

试试这个查询。 (http://sqlfiddle.com/#!9/4f5116/5/2)

SELECT id, 
       (6371 * acos( cos( radians($lat) ) * cos( radians(lat) ) * 
        cos( radians(lng) - radians($long)) + sin(radians($lat)) *
        sin(radians(lat)) )) as distance 
  FROM map_locations
HAVING distance < 0.5

还有,小心!当您在 map_locations table 中获得数千行时,此查询将比交通堵塞时的纽约公共汽车慢。您应该研究使用边界框来加快速度。 Read this