Haversine distance calculation between two points in Laravel

前端 未结 7 1537
迷失自我
迷失自我 2020-12-13 16:45

I\'m working on a laravel appliciation in which I need to find all the products that are within a certain radius of the user\'s coordinates. Products have a one to many rela

7条回答
  •  醉梦人生
    2020-12-13 16:55

    This was my implementation of it. I've chosen to alias my query out ahead of time, this way I can take advantage of Pagination. Furthermore, you need to explicitly select the columns that you wish to retrieve from the query. add them at the ->select(). Such as users.latitude, users.longitude, products.name, or whatever they may be.

    I have created a scope which looks something like this:

    public function scopeIsWithinMaxDistance($query, $location, $radius = 25) {
    
         $haversine = "(6371 * acos(cos(radians($location->latitude)) 
                         * cos(radians(model.latitude)) 
                         * cos(radians(model.longitude) 
                         - radians($location->longitude)) 
                         + sin(radians($location->latitude)) 
                         * sin(radians(model.latitude))))";
         return $query
            ->select() //pick the columns you want here.
            ->selectRaw("{$haversine} AS distance")
            ->whereRaw("{$haversine} < ?", [$radius]);
    }
    

    You can apply this scope to any model with a latitude andlongitude.

    Replace the $location->latitude with your latitude that you wish to search against, and replace the $location->longitude with the longitude that you wish to search against.

    Replace the model.latitude and model.longitude with the Models you wish to find around the $location based on the distance defined in the $radius.

    I know you have a functioning Haversine formula, but if you need to Paginate you can't use the code you've supplied.

    Hopefully this helps.

提交回复
热议问题