Sort distance record based on latitude and longitude - Laravel

Asked

Viewed 36 times

4

I have a table companies who has a one to one polymorphic relationship with addresses I have the parameter of latitude and longitude and I would like to order the Commissaries to the distance of the smallest to the greatest. The SQL I have works correctly if I search directly in the table Addresses, but need to be returned companies.

        $request['latitude'] = '-21.12633165824461';
        $request['longitude'] = '-47.766933831153125';

        $sqlDistance = DB::raw('( 111.045 * acos( cos( radians(' . $request['latitude'] . ') ) 
   * cos( radians( addresses.latitude ) ) 
   * cos( radians( addresses.longitude ) 
   - radians(' . $request['longitude'] . ') ) 
   + sin( radians(' . $request['latitude'] . ') ) 
   * sin( radians( addresses.latitude ) ) ) )');

        return $this->company->with(['bonusRule', 'address'])
            ->whereHas('address', function (Builder $query) use ($sqlDistance) {
                return $query->selectRaw("{$sqlDistance} AS distance")
                    ->orderBy('distance');
            })->paginate(10);

1 answer

1


I figured it out, so here’s the solution for whoever needs it:

    $request['latitude'] = '-21.12633165824461';
    $request['longitude'] = '-47.766933831153125';

        $sqlDistance = DB::raw('( 111.045 * acos( cos( radians(' . $request['latitude'] . ') ) 
   * cos( radians( addresses.latitude ) ) 
   * cos( radians( addresses.longitude ) 
   - radians(' . $request['longitude'] . ') ) 
   + sin( radians(' . $request['latitude'] . ') ) 
   * sin( radians( addresses.latitude ) ) ) )');

        return $this->company->selectRaw("companies.*, {$sqlDistance} AS distance")
            ->with(['bonusRule', 'address'])
            ->join('addresses', 'companies.id', '=', 'addresses.addressable_id')
            ->where('addresses.addressable_type', 'company')
            ->orderBy('distance')
            ->paginate(10);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.