How to sort laravel collection by distance from location?

Member

by denis , in category: Third Party Scripts , 4 months ago

How to sort laravel collection by distance from location?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 4 months ago

@denis 

To sort a Laravel collection by distance from a specific location, you can use the sortBy method along with a custom comparison function.


First, you will need to calculate the distance between the location and each item in the collection. You can achieve this by using a library like haversine formula or Vincenty formula.


Here is an example of how you can sort a Laravel collection by distance using the haversine formula:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$location = ['latitude' => 37.7749, 'longitude' => -122.4194];

$collection = YourModel::all();

$sortedCollection = $collection->sortBy(function ($item) use ($location) {
    $latitudeFrom = $location['latitude'];
    $longitudeFrom = $location['longitude'];

    $earthRadius = 6371; // in kilometers

    $latitudeTo = $item->latitude;
    $longitudeTo = $item->longitude;

    $latDelta = deg2rad($latitudeTo - $latitudeFrom);
    $lonDelta = deg2rad($longitudeTo - $longitudeFrom);

    $a = sin($latDelta / 2) * sin($latDelta / 2) +
         cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) *
         sin($lonDelta / 2) * sin($lonDelta / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

    $distance = $earthRadius * $c;

    return $distance;
});


In this example, replace YourModel with the name of your model class and latitude and longitude with the respective column names in your model.


Make sure to adjust the earthRadius constant to get the distance in the desired unit (kilometers or miles).


After sorting the collection based on the calculated distance, the $sortedCollection variable will contain the collection sorted by distance from the specified location.