I have a gridview in which I show the distance between the registered user's latitude & longitude (set in their profile) and the gridview line's latitude & longitude. I've created a helper class which gives me a function to return said distance My gridview for distance is this :
[
'format'=>'raw',
'attribute'=>'distance (km)',
'value'=> function ($data) {
$latFrom = Yii::$app->user->identity->profile->city->latitude;
$longFrom = Yii::$app->user->identity->profile->city->longitude;
$latTo = $data->createdBy->profile->city->latitude;
$longTo = $data->createdBy->profile->city->longitude;
return GeoHelper::distance($latFrom, $longFrom, $latTo, $longTo);
},
],
I'm trying to add sorting for distance in my gridview, but can't seem to find how to do so. I've tried adding a public $distance property to the search model and setting it as safe and then adding
$dataProvider->sort->attributes['distance'] = [
'asc' => ['distance' => SORT_ASC],
'desc' => ['distance' => SORT_DESC],
];
But no luck
Any ideas ?
public static function distance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371) { // convert from degrees to radians $latFrom = deg2rad($latitudeFrom); $lonFrom = deg2rad($longitudeFrom); $latTo = deg2rad($latitudeTo); $lonTo = deg2rad($longitudeTo); $latDelta = $latTo - $latFrom; $lonDelta = $lonTo - $lonFrom; $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2))); return round($angle * $earthRadius); }
– Benoît