1
public function nearby()
{
    $user = auth()->user();

    $lat = auth()->user()->latitude;
    $lon = auth()->user()->longitude;
    $radius = 3; // km => converted to meter

    $angle_radius = (float)$radius / ( 111 * cos( (float)$lat ) ); // Every lat|lon degree° is ~ 111Km
    $min_lat = (float)$lat - (float)$angle_radius;
    $max_lat = (float)$lat + (float)$angle_radius;
    $min_lon = (float)$lon - (float)$angle_radius;
    $max_lon = (float)$lon + (float)$angle_radius;

    $persons = User::where('status', STATUS::ACTIVE)
                ->where('id', '!=', $user->id)
                ->whereBetween('latitude', [$min_lat, $max_lat])
                ->whereBetween('longitude', [$min_lon, $max_lon])
                ->get();

    $persons->each(function($person) {
        /* auth user coordinate vs user's coordinates */
        $point1 = array('lat' => auth()->user()->latitude, 'long' => auth()->user()->longitude);
        $point2 = array('lat' => $person->latitude, 'long' => $person->longitude);
        $distance = $person->getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);

        $person['distance'] = $distance;
    }); 

    return $persons;

}

I'm searching users within the 3km radius based on user's long/lat. I'm comparing auth long/lat to nearby user long/lat. It returns collections of user with distance.

enter image description here

Now I am having trouble sorting it by distance.

If I add orderBy('distance', 'desc') of course it will result an error, because I do not have distance column on my DB.

Is their a way to sort it and paginate it.

Randy Corpuz
  • 153
  • 1
  • 10

2 Answers2

2

The $persons variable is a collection object, you can use collection methods found in the documentation here: https://laravel.com/docs/5.6/collections#available-methods

You can use the sortBy function of the collection object.


The pagination of laravel is in database query level (https://laravel.com/docs/5.6/pagination), so that you can use the eloquent orderBy method.

If you want to make this work, put a distance column in the users table, but I think you don't want this because you programmatically compute the distance in the getDistanceBetweenPoints.

Another solution that I think of is create a separate table for the distances of each user.

You must think of a solution that will sort distance in the database query level.


Hope this will help you to solve your problem: latitude/longitude find nearest latitude/longitude - complex sql or complex calculation

aceraven777
  • 4,358
  • 3
  • 31
  • 55
0

This may help.

 $persons->sortBy('distance');
    return $persons;
Shailendra Gupta
  • 1,054
  • 6
  • 15