实际上,我正在使用PHP查找两个地方之间的最小距离。
我在两个变量(LAT FROM和LON FROM)中定义了第一位的值
第二个位置是从数据库中拾取的地址数组。 一个函数拾取地址并找到距离,然后另一个函数选择最小距离。
一切正常,我能够打印出最小距离,但是我要寻找的是知道如何从数组中打印出与该功能找到的最小距离相对应的地址。
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$latitudeFrom = '45.6686653';
$longitudeFrom = '12.2396675';
$sql = "SELECT address FROM mydatabase;";
$result = $conn->query($sql);
$datiordinati = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$datiordinati[] = $row["address"];
}
} else {
echo "0 results";
}
$len=count($datiordinati);
for ($i=0;$i<$len;$i++){
// Get JSON results from this request
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($datiordinati[$i]).'&sensor=false');
$geo = json_decode($geo, true); // Convert the JSON to an array
if (isset($geo['status']) && ($geo['status'] == 'OK')) {
$latitudeTo = $geo['results'][0]['geometry']['location']['lat']; // Latitude
$longitudeTo = $geo['results'][0]['geometry']['location']['lng']; // Longitude
}
//Calculate distance from latitude and longitude
$theta = $longitudeFrom - $longitudeTo;
$dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) + cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$distance[$i] = ($miles * 1.609344).' km';
}
function getMin($distance)
{
$n = count($distance);
$min = $distance[0];
for ($i = 1; $i < $n; $i++)
if ($min > $distance[$i])
$min = $distance[$i];
return $min;
}
$finalecho = (getMin($distance));
echo $finalecho; // This print me out the minimum distance
$conn->close();