Nearby stores in Laravel

时光总嘲笑我的痴心妄想 提交于 2020-11-28 10:45:49

问题


i'm try to get neraby store in Laravel 5.1 I have geocoding parser that caluclate coorinate. But i have problem with haversine formulas. Basically i need that from table Aziende (Stores) given a lat, long e category passed trough url, fetch the nearby stores.

I try with this code:

$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();
 }
 ?>

回答1:


The following should work for you to implement the haversine formula in an SQL query. My answer is assuming you have a model setup to correspond with the database table "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();


来源:https://stackoverflow.com/questions/40817300/nearby-stores-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!