Haversine distance calculation between two points in Laravel

前端 未结 7 1629
迷失自我
迷失自我 2020-12-13 16:45

I\'m working on a laravel appliciation in which I need to find all the products that are within a certain radius of the user\'s coordinates. Products have a one to many rela

7条回答
  •  春和景丽
    2020-12-13 17:01

    I got a solution in Laravel.

        public function near($myLon, $myLat, $areaLon, $areaLat)
    {
        $this->applyCriteria();
        $this->applyScope();
    
        $results = $this->model->select(DB::raw("SQRT(
            POW(69.1 * (latitude - " . $myLat . "), 2) +
            POW(69.1 * (" . $myLon . " - longitude) * COS(latitude / 57.3), 2)) AS distance, SQRT(
            POW(69.1 * (latitude - " . $areaLat . "), 2) +
            POW(69.1 * (" . $areaLon . " - longitude) * COS(latitude / 57.3), 2)) AS area"), "YOUR_TABLE.*")->get();
    
        $this->resetModel();
        $this->resetScope();
    
        return $this->parserResult($results);
    }
    

    The answer is in Miles, you will have to replace YOUR_TABLE with the name of your database table. Thank you hope it helps

提交回复
热议问题