php - 在数组中找到最近的经度和纬度?

标签 php latitude-longitude

我在 PHP 中将经度和纬度作为字符串,如下所示

49.648881
-103.575312

我想利用它并查看一组值以找到最接近的值。数组看起来像

array(
'0'=>array('item1','otheritem1details....','55.645645','-42.5323'),
'1'=>array('item1','otheritem1details....','100.645645','-402.5323')
);

我想返回 long 和 lad 最接近的数组。在这种情况下,它将是第一个(是的,我知道 -400 不是一个可能的值)。

有没有快速简便的方法来做到这一点?我尝试了数组搜索,但没有用。

差异代码

function distance($lat1, $lon1, $lat2, $lon2, $unit) { 

  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

最佳答案

您需要先将每个项目映射到引用点的距离。

然后你对 map 进行排序,然后你可以判断哪个距离最短(或者如果你反向搜索则距离最高):

$ref = array(49.648881, -103.575312);

$items = array(
    '0' => array('item1','otheritem1details....','55.645645','-42.5323'),
    '1' => array('item1','otheritem1details....','100.645645','-402.5323')
);

$distances = array_map(function($item) use($ref) {
    $a = array_slice($item, -2);
    return distance($a, $ref);
}, $items);

asort($distances);

echo 'Closest item is: ', var_dump($items[key($distances)]);

输出:

Closest item is: array(4) {
  [0]=>
  string(5) "item1"
  [1]=>
  string(21) "otheritem1details...."
  [2]=>
  string(9) "55.645645"
  [3]=>
  string(8) "-42.5323"
}

注意您的经纬度顺序正确。

距离函数(只有标题略有变化,单位被删除):

function distance($a, $b)
{
    list($lat1, $lon1) = $a;
    list($lat2, $lon2) = $b;

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    return $miles;
}

关于php - 在数组中找到最近的经度和纬度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9589130/

相关文章:

javascript - 将下拉列表值传递给谷歌地图javascript

php - 更多结果 - 更快的查询(在 mysql 中按纬度和经度搜索)

php - 查询在给定的纬度/经度内查找地点

algorithm - 如何对地理数据进行排序以便快速搜索

php - set_error_handler() 不适用于 fatal error

php - 从一个表中删除行并添加到另一个表中

php - 使用经度/纬度计算 OSGR

php - 如何通过 PHP 脚本设置 cron 作业

javascript - 如何使用 php mysql json 根据 url 中的行 id 从数据库检索值?

php - 将变量中的整数添加到 mysql 列