2016-11-26 61 views
4

我試圖在Laravel 5.1中獲得neraby商店我有地理編碼解析器,caluclate coorinate。但是,我有與haversine公式問題。基本上我需要從表Aziende(商店)給出一個lat,long e類別通過低谷url,拿取附近的商店。Laravel附近的商店

我嘗試使用此代碼:

$dove = Input::get('dove'); 
    $categoria_id = Input::get('id_categoria'); 
    // 4: check if any matches found in the database table 
    if (!empty($dove)) { 
     $response = \GoogleMaps::load('geocoding')->setParamByKey ('address', $dove)->get(); 
     $response = json_decode($response, true); 
     $latitude = $response['results'][0]['geometry']['location']['lat']; 
     $longitude = $response['results'][0]['geometry']['location']['lng']; 
     $radius = '5'; 
     $aziende = DB::table('aziende') 
      ->select(
       ('lat * acos(cos(radians(50)) * cos(radians(lat)) * cos(radians(lng) - radians(-122)) 
         + sin(radians(37)) * sin(radians(lat))) as distance'))->get(); 




    } else { 
    $aziende = DB::table("aziende")->where('categoria', $categoria_id)->get(); 
} 
?> 
+0

你使用什麼數據庫/版本?如果你使用MySQL,你有ST_Distance ... v5.7有ST_Distance_Sphere https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html – jcorry

回答

0

下面應該爲你工作,以實現在一個SQL查詢haversine公式。我的答案是假設你有一個模型設置與數據庫表「aziende」相對應。

$lat = floatval($response['results'][0]['geometry']['location']['lat']); 
$lng = floatval($response['results'][0]['geometry']['location']['lng']); 
$radius = 5; 
$distance = DB::raw("*, (6371 * acos(cos(radians($lat)) * cos(radians(lat)) * cos(radians(lng) - radians($lng)) + sin(radians($lat)) * sin(radians(lat)))) AS distance"); 
$aziende = Aziende::select($distance)->orderBy('distance')->where('distance', '<=', $radius)->get();