这是一个用于从JSON文件加载读取值以提供纬度,经度,地址等的示例。我使用min()返回数组$ cart中的最低值,无法弄清楚如何从数组中输入和获取其他值。它显示了所需的最近距离,但我想抓住最近距离的纬度和经度。
<?php
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;
}
}
$cart = array();
foreach ($json_a as $pos_name => $pos_a) {
echo "['" . $pos_a['name'] . "', " . $pos_a['latlng'][0] . ", " . $pos_a['latlng'][1] . ", '" . $pos_a['address'] . "', 0],";
array_push($cart, distance($lat, $lon, $pos_a['latlng'][0], $pos_a['latlng'][1], "M") . "");
}
echo min($cart);
?>
答案 0 :(得分:1)
问题非常不明确。但是,我会尝试假装我知道您有一个固定点($lat
,$long
)的坐标和一个由其坐标标识的其他点的列表($json_a
)你想从这个列表中找到最接近上述固定点的点。
显然,你应该保持距离和 $cart
数组中每个点的坐标。为简单起见,我将使用距离索引$cart
数组:
$cart = array();
foreach ($json_a as $pos_name => $pos_a) {
// Compute the distance
$distance = distance($lat, $lon, $pos_a['latlng'][0], $pos_a['latlng'][1], "M");
// Store point info and the distance in $pos, index by distance
$cart[$distance] = array(
'name' => $pos_a['name'],
'lat' => $pos_a['latlng'][0],
'long' => $pos_a['latlng'][1],
'dist' => $distance,
);
}
// Get the minimum distance
$distance = min(array_keys($cart));
// Get the position corresponding to the minimum distance
$position = $cart[$distance];
上面的代码包含逻辑错误。将鼠标放在下方的黄色区域以了解它,或者更好地锻炼大脑并自己发现它。
如果距离点的距离相同,则有两个或更多位置,只有最后一个位置存储在数组中。如果距离不是最小的,则不会以任何方式影响处理。
答案 1 :(得分:0)
如果循环也可以找到最低值。
$min = null;
foreach ($json_a as $pos_name => $pos_a) {
echo "['".$pos_a['name']."', ".$pos_a['latlng'][0].", ".$pos_a['latlng'][1].", '".$pos_a['address']."', 0],";
$distance = distance($lat, $lon, $pos_a['latlng'][0], $pos_a['latlng'][1], "M");
if($min === null || $distance < $min) {
$min = $distance;
}
array_push($cart, $distance."");
}