1. 直接透過 mysql 查詢
DB::table('shop')->selectRaw("id,lon,lat,
ROUND(ST_DISTANCE(point(lon,lat),point({$lon},{$lat})) /0.0111,2) distance")
->orderBy('distance')
->first();
2. 查詢所有座標,迴圈計算距離
function nearestShop($shopList, $lon, $lat){
$arr = [];
foreach ($shopList as $key => $shop){
$arr[$key] = getDistance($lon, $lat, $shop->lon, $shop->lat);
}
asort($arr);
return $shopList[array_keys($arr)[0]];
}
function getDistance($lon1, $lat1, $lon2, $lat2, $unit = 2, $decimal = 2){
$EARTH_RADIUS = 6371;
$radLng1 = deg2rad($lon1);
$radLat2 = deg2rad($lat2);
$radLat1 = deg2rad($lat1);
$radLng2 = deg2rad($lon2);
$distance = 2 * asin(sqrt(pow(sin(($radLat1-$radLat2) / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin(($radLng1-$radLng2) / 2), 2))) * $EARTH_RADIUS * 1000;
if ($unit === 2) {
$distance /= 1000;
}
return round($distance, $decimal);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結