Haversine and Laravel

后端 未结 2 1396
春和景丽
春和景丽 2020-12-20 00:39

I\'m attempting to compare a users location (Sent via params in the URL) to offers.offer_lat and offers.offer_long (in my DB) by a distance argument (set in miles)

I

2条回答
  •  遥遥无期
    2020-12-20 00:48

    So you don't need all the bloat that is in that gist, instead, you can use the following formulae:

    public function get_offers_near($latitude, $longitude, $radius = 1){
    
        $offers = Offer::select('offers.*')
            ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                               cos( radians( offer_lat ) )
                               * cos( radians( offer_long ) - radians(?)
                               ) + sin( radians(?) ) *
                               sin( radians( offer_lat ) ) )
                             ) AS distance', [$latitude, $longitude, $latitude])
            ->havingRaw("distance < ?", [$radius])
            ->get();
    
        return $offers;
    }
    

    This assumes that you pass in the latitude and longitude from your user. Also, if you don't want the radius to be 1, you can pass in the 3rd argument and provide a custom radius.

    And of course, we're assuming that this is for a model of Offer. Change your naming convention where required.

提交回复
热议问题