Find the nearest location using latitude and longitude in laravel | PHP

Hello buddy, how are you I hope you are doing fantastic, thanks for reaching out on our website, I bet this blog will definitely help you out to get the nearest location based on two latitudes and two longitude

You can use the mentioned code in your PHP or in the Laravel application as well, I know that you search over the internet, and at every places, they are finding out the nearest location by implementing the code in sql.

Will show you how to get the nearest location based on longitude and latitude by using the code on sql, or without writing sql code, by using just the plane PHP code.

Get nearest location by using PHP Code

$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
 $distance = acos($distance);
 $distance = rad2deg($distance);
 $distance = $distance * 60 * 1.1515;
 return round($distance, 2);

The above value comes in the KM, the above code will give you the distance in KM between two latitude and longitude.

By implementing the logic in sql

        $users = User::select(""
                        ,DB::raw("6371 * acos(cos(radians(" . $lat . ")) 
                        * cos(radians( 
                        * cos(radians(users.lon) - radians(" . $lon . ")) 
                        + sin(radians(" .$lat. ")) 
                        * sin(radians( AS distance"))

From the above way, you can also get the shortest distance between two latitude and longitude.

I hope now you understood how to get the shortest distance by using latitude and longitude, still facing issue feel free to comment.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button