Often, in real-estate , dating and other similar websites, you might have noticed how they allow you to search nearby to any location. You can easily accomplish that in your laravel application using Haversine formula.
Source -- Tighten.co
Last year, I worked on real-estate project in my college as an capstone project and that's when I got to work on this query. Though haversine formula is easy to find but to use it in laravel through Eloquent was very difficult. I tried many solutions found in Stackoverflow, laracasts forum and other sources but couldn't make them work. Some of them did work but since they were using raw queries, I couldn't paginate the results which is what I needed.
After some trial and error, I finally make it working. So, here I am sharing the code snippet.
$gr_circle_radius = 6371;
$max_distance = 500;
$distance_select = sprintf(
"
( %d * acos( cos( radians(%s) ) " .
" * cos( radians( lat ) ) " .
" * cos( radians( long ) - radians(%s) ) " .
" + sin( radians(%s) ) * sin( radians( lat ) ) " .
" ) " .
")
",
$gr_circle_radius,
$lat,
$long,
$lat
);
$properties = Property::select('*')
->having(DB::raw($distance_select), '<=', $max_distance)
->groupBy('properties.id')->paginate(1);
Here, I have set maximum distance = 500 Km so it will show all results within 500 Km of the given Latitude and Longitude (used $lat, $long as variables).
To see the Demo, Check out my real estate project -- FirstFloor
The post How to find nearby places using Latitude and longitude in Laravel 5 appeared first on Parth Patel - a Web Developer.
Top comments (1)
does not work my dear friend :)