/**
* 根据两点间的经纬度计算距离
* @param $lat1 纬度1
* @param $lng1 经度1
* @param $lat2 纬度2
* @param $lng2 经度2
* @return array
*/
function get_distance($lat1, $lng1, $lat2, $lng2): array
{
//赤道半径(单位m)
$earthRadius = 6378137;
$lat1 = ($lat1 * pi()) / 180;
$lng1 = ($lng1 * pi()) / 180;
$lat2 = ($lat2 * pi()) / 180;
$lng2 = ($lng2 * pi()) / 180;
$calcLongitude = $lng2 - $lng1;
$calcLatitude = $lat2 - $lat1;
$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
//米
$calculatedDistance = abs(round(($earthRadius * $stepTwo), 2));
//千米
$calculatedDistanceKm = abs(round(($calculatedDistance / 1000), 2));
if ($calculatedDistanceKm >= 1) {
if ($calculatedDistanceKm > 999) {
$distance_str = ">999 km";
} else {
$distance_str = $calculatedDistanceKm . " km";
}
} else {
$distance_str = $calculatedDistance . " m";
}
return [
'distance' => $calculatedDistance,
'distance_str' => $distance_str,
];
}