在数组中查找最接近的经度和纬度? [英] Find closest longitude and latitude in array?
问题描述
我在PHP中像下面这样在字符串中具有经度和纬度
I have a longitude and latitude as a string in PHP like below
49.648881
-103.575312
我想接受它并查看一组值以找到最接近的值.数组看起来像
And I want to take that and look in an array of values to find the closest one. The array looks like
array(
'0'=>array('item1','otheritem1details....','55.645645','-42.5323'),
'1'=>array('item1','otheritem1details....','100.645645','-402.5323')
);
我想返回具有最接近的long和lad的数组.在这种情况下,它将是第一个(是的,我知道-400是不可能的值).
I want to return the array that has the closest long and lad. In this case it would be the first one (and yes I know -400 is not a a possible value).
是否有任何快速简便的方法来做到这一点?我尝试了数组搜索,但是没有用.
Is there any quick and easy way to do this? I tried array searching but that didn't work.
差异代码
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;
}
}
推荐答案
您需要先将每个项目的距离映射到参考点.
You need to map the distance of each item to the reference point first.
然后您对地图进行排序,然后您可以分辨出哪个距离最小(如果反向搜索,则距离最大):
Then you sort the map and then you can tell which has the lowest (or highest if you reverse the search) distance:
$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"
}
请注意,您的经度和纬度顺序正确.
Take care you have the right order of lat and long.
距离功能(仅标题略有更改,单位已删除):
The distance function (only the header slightly changed and units have been dropped):
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;
}
这篇关于在数组中查找最接近的经度和纬度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!