代碼如下:
function getDistance($lat1,$lng1,$lat2,$lng2,$len_type = 1,$decimal = 3){
$earthRadius = 6371; // 地球半徑(單位:公里)
// 將角度轉(zhuǎn)換為弧度
$lat1 = deg2rad($lat1);
$lon1 = deg2rad($lng1);
$lat2 = deg2rad($lat2);
$lon2 = deg2rad($lng2);
// 計(jì)算緯度和經(jīng)度的差值
$latDiff = $lat2 - $lat1;
$lonDiff = $lon2 - $lon1;
// Haversine 公式
$a = sin($latDiff / 2) ** 2 + cos($lat1) * cos($lat2) * sin($lonDiff / 2) ** 2;
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
// 計(jì)算距離
$distance = $earthRadius * $c;
if ($len_type == 1){
$distance = round($distance * 1000,0);
}
return round($distance,0);
}