Haversine和Laravel [英] Haversine and Laravel

查看:65
本文介绍了Haversine和Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过距离参数(以英里为单位)将用户位置(通过URL中的参数发送)与offer.offer_lat和offer.offer_long(在我的数据库中)进行比较

I'm attempting to compare a users location (Sent via params in the URL) to offers.offer_lat and offers.offer_long (in my DB) by a distance argument (set in miles)

我现在要疯了,网上发现的许多解决方案都很难用DB :: raw移植到laravels查询构建器,我目前在查询范围内具有该功能,因为用户将进行过滤API结果使用距离,但是没有运气!

I'm going crazy right now, a lot of solutions I have found online are proving hard to port over to laravels query builder using DB::raw, I currently have the function in a query scope as the user will be filtering API results using distance, no luck though!

我在网上发现了一些用于计算己二醛的功能,但我不知道如何使用它们.这是一个例子: https://gist.github.com/fhferreira/9081607

I found some functions online for calculating the haversine but I have no idea how to use them. Here's an example: https://gist.github.com/fhferreira/9081607

任何帮助将不胜感激! :)

Any help would be massively appreciated! :)

谢谢

推荐答案

因此,您不需要该要点中的所有膨胀,而是可以使用以下公式:

So you don't need all the bloat that is in that gist, instead, you can use the following formulae:

public function get_offers_near($latitude, $longitude, $radius = 1){

    $offers = Offer::select('offers.*')
        ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                           cos( radians( offer_lat ) )
                           * cos( radians( offer_long ) - radians(?)
                           ) + sin( radians(?) ) *
                           sin( radians( offer_lat ) ) )
                         ) AS distance', [$latitude, $longitude, $latitude])
        ->havingRaw("distance < ?", [$radius])
        ->get();

    return $offers;
}

这假设您从用户处传入了latitudelongitude.另外,如果您不希望半径为1,则可以传入第3个参数并提供自定义半径.

This assumes that you pass in the latitude and longitude from your user. Also, if you don't want the radius to be 1, you can pass in the 3rd argument and provide a custom radius.

当然,我们假设这是针对Offer模型的.在需要的地方更改您的命名约定.

And of course, we're assuming that this is for a model of Offer. Change your naming convention where required.

这篇关于Haversine和Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆