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!

5
  • i think your haversineGreatCircleDistance must be in your model. Can you shoe your haversineGreatCircleDistance function? Commented Feb 5, 2020 at 0:35
  • Take a look at this: stackoverflow.com/questions/37618764/… I think it will might help you. Commented Feb 5, 2020 at 0:35
  • you send only the distance to your Location model. I think you must send latitude and longtidue to the model too. Commented Feb 5, 2020 at 0:57
  • i think it must similar to this laracasts.com/discuss/channels/general-discussion/… Commented Feb 5, 2020 at 0:59
  • you are put the number in DB::raw(), and is the method haversineGreatCircleDistance in your Location Model? Commented Feb 5, 2020 at 2:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.