Skip to content

Instantly share code, notes, and snippets.

@kimmellj
Created October 18, 2012 17:25
Show Gist options
  • Save kimmellj/3913489 to your computer and use it in GitHub Desktop.
Save kimmellj/3913489 to your computer and use it in GitHub Desktop.
This is a MySQL function that will calculate the distance between two latitude and longitude points
DELIMITER ;;
/*!50003 CREATE*/ /*!50020 DEFINER=`foobar`@`localhost`*/ /*!50003 FUNCTION `distance`( lat1 DOUBLE, lon1 DOUBLE, lat2 DOUBLE, lon2 DOUBLE ) RETURNS DOUBLE
DETERMINISTIC
BEGIN
RETURN 3956 * 2 * ASIN(SQRT(POWER(SIN((lat1 - lat2) * pi()/180 / 2), 2) + COS(lat1 * pi()/180) * COS(lat2 * pi()/180) * POWER(SIN((lon1 - lon2) * pi()/180 / 2), 2)));
END */;;
@Emizy
Copy link

Emizy commented Mar 3, 2019

my code

$lat = Auth::user()->lat;
$long = Auth::user()->long;
$radius = 10;

    $raw = DB::raw('(6371 * 2 * ASIN(SQRT(POWER(SIN(('.$lat.' - lat) / 2),2) + COS('.$lat.') * COS(lat) * POWER(SIN(('.$long.' - long) / 2),2) ))) as distance');
    $location = DB::table('users')->select('*', $raw)
        ->addSelect($raw)->where('user_type', 'Agency')
        ->orderBy('distance', 'ASC')
        ->having('distance', '<=', $radius)->get();
    return response()->json($location);

while lat and long are column in my user tables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment