DEV Community

Parth Patel
Parth Patel

Posted on • Originally published at parthpatel.net on

How to find nearby places using Latitude and longitude in Laravel 5

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.

nearby location in laravel

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);
Enter fullscreen mode Exit fullscreen mode

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
erfanhemmati profile image
Erfan Hemmati

does not work my dear friend :)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay