3

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'm going crazy right now, a lot of solutions I have found online are proving hard to port over to laravels query builder using DB::raw, I currently have the function in a query scope as the user will be filtering API results using distance, no luck though!

I found some functions online for calculating the haversine but I have no idea how to use them. Here's an example: https://gist.github.com/fhferreira/9081607

Any help would be massively appreciated! :)

Thanks

ExohJosh
  • 1,832
  • 16
  • 22
  • You have the solution right under your fingers, put the function found in your own link into a controller and use it. – phaberest Feb 17 '16 at 21:13

2 Answers2

13

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.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • 1
    For any finding this. In the event you get non grouping field error - http://stackoverflow.com/questions/39053335/laravel-5-3-syntax-error-or-access-violation-1463-non-grouping-field-distance – RushVan Mar 07 '17 at 17:37
3

Haversine in Laravel works in this way:

                Travel::select(
                    DB::raw("travels.*,
                          ( 6371 * acos( cos( radians($lat) ) *
                            cos( radians( lat ) )
                            * cos( radians( lon ) - radians($lng)
                            ) + sin( radians($lat) ) *
                            sin( radians( lat ) ) )
                          ) AS distance"))
                ->orderBy('distance', 'asc')
                ->get();

and you will get a collection of points ordered by distance (nearest first)

Was used travel model with params lat and lng. parameter distance is added by the raw query