0

I have a model Location, and it has a one to one relationship with another model Address with attributes like latitude and longitude, and I'm working on an endpoint to get a list of locations based their distance to user. So my GET request, for example, looks something like /locations?latitude=70.00&longitude=-80.01.

In my LocationController I already have a function like haversineGreatCircleDistance( $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) that takes 4 arguments as float and return the distance to user input location as a float.

function haversineGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, isMile = false) { 
    if ($isMile) {
        $earthRadius = self::EARTH_RADIUS_IN_MILE;
    else {
        $earthRadius = self::EARTH_RADIUS_IN_KM;
    }

    $dLat = deg2rad($latitudeTo - $latitudeFrom);  
    $dLon = deg2rad($longitudeTo - $longitudeFrom);  

    $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * sin($dLon/2) * sin($dLon/2);  
    $c = 2 * asin(sqrt($a));  
    $d = $earthRadius * $c;  

    return $d;
}

My question is, how do I use this function as part of my eloquent query to get the distance? My eloquent query currently looks something like this:

$distance = self::haversineGreatCircleDistance($latitude, $longitude, 'latitude', 'longitude') . ' AS distance';

$query = Location::select('*', \DB::raw($distance))
->with('address')
->sortBy('distance');

However it's not working and all the distances calculated are the same as if the second latitude and longitude parameters were 0. And if there's no way to make the query work with php functions, what is a better solution? Please let me know if you need more information. Thanks so much!

danni114
  • 57
  • 3
  • 9
  • i think your haversineGreatCircleDistance must be in your model. Can you shoe your haversineGreatCircleDistance function? – db1975 Feb 05 '20 at 00:35
  • Take a look at this: https://stackoverflow.com/questions/37618764/inserting-a-variable-in-a-raw-sql-query-laravel#37619436 I think it will might help you. – brunobraga Feb 05 '20 at 00:35
  • you send only the distance to your Location model. I think you must send latitude and longtidue to the model too. – db1975 Feb 05 '20 at 00:57
  • i think it must similar to this https://laracasts.com/discuss/channels/general-discussion/how-to-find-nearest-cities-from-latitude-and-longitude – db1975 Feb 05 '20 at 00:59
  • you are put the number in `DB::raw()`, and is the method `haversineGreatCircleDistance` in your Location Model? – TsaiKoga Feb 05 '20 at 02:00

0 Answers0