首页 > 解决方案 > How to search users from a given latitude/longitude with in 3 km in laravel

问题描述

I know such type of questions is asked but not getting any proper solution.

I have my latitude/longitude with me. I have also the collection of latitude/longitude in my database. What I am trying to do is, when I enter distance =3, it will show all users within 3 kilometres from database.

Here is my code :

public function nearbyResults(Request $request)
    {
        $user_id = request('user_id');
        $latitude = request('latitude');
        $longitude = request('longitude');
        $distance = 3;

        $upper_latitude = $latitude + $distance;
        $lower_latitude = $latitude - $distance;
        $upper_longitude = $longitude + $distance;
        $lower_longitude = $longitude - $distance;

        $drivers = UsersDetail::whereBetween('latitude', [$lower_latitude, $upper_latitude])->whereBetween('longitude', [$lower_longitude, $upper_longitude])->get();

        return Response()->json([
            'status' => 'success',
            'data' => $drivers
        ], 200);
    }

标签: laravel

解决方案


要计算范围,您需要对计算范围的点进行一些计算。

$lat = $_GET['lat']; // latitude of centre of bounding circle in degrees 
$lon = $_GET['lon']; // longitude of centre of bounding circle in degrees 
$rad = $_GET['rad']; // radius of bounding circle in kilometers 
$R = 6371; // earth's mean radius, km // first-cut bounding box (in degrees) 
$maxLat = $lat + rad2deg($rad/$R); 
$minLat = $lat - rad2deg($rad/$R); 
$maxLon = $lon + rad2deg(asin($rad/$R) / cos(deg2rad($lat))); 
$minLon = $lon - rad2deg(asin($rad/$R) / cos(deg2rad($lat)));

现在您可以在查询中使用这些最小和最大 Lat long 来确定半径中的用户


推荐阅读