2016-07-27 52 views
1

半径搜索如何编写laravel控制器此查询与谷歌地图和MySQL在laravel

SELECT *, ACOS(SIN(RADIANS(lat)) * SIN(RADIANS($lat)) + 
     COS(RADIANS(lat)) * COS(RADIANS($lat)) * COS(RADIANS(lon) - 
     RADIANS($long))) * 6380 AS distance 
FROM places 
WHERE ACOS(SIN(RADIANS(lat)) * SIN(RADIANS($lat)) + 
    COS(RADIANS(lat)) * COS(RADIANS($lat)) * COS(RADIANS(lon) - 
    RADIANS($long))) * 6380 < 10 
ORDER BY distance 

10是公里半径 $ lat和$长为中心或cirlce 纬度和经度是属性如果您的表格

回答

0

您只是在此处实施了半砂公式。他是一个可以附加到模型的快速示波器。

public function scopeCloseTo($query, $location, $radius = 25) 
{ 

    /** 
    * In order for this to work correctly, you need a $location object 
    * with a ->latitude and ->longitude. 
    */ 
    $haversine = "(6371 * acos(cos(radians($location->latitude)) * cos(radians(latitude)) * cos(radians(longitude) - radians($location->longitude)) + sin(radians($location->latitude)) * sin(radians(latitude))))"; 
    return $query 
     ->select(['comma','separated','list','of','your','columns']) 
     ->selectRaw("{$haversine} AS distance") 
     ->whereRaw("{$haversine} < ?", [$radius]); 
} 

在上面的功能,可以设置$radius为第三个参数,所以你的情况10

第二个参数是location,您希望从中找到半径范围内的地方of。把这看作你的出发点。

E.G .;如果你想获得你家附近的所有地方。 your house然后将作为location对象作为第三个参数传递,并具有longitudelatitude属性。

您可以调整radians(longitude)以匹配您的模型表。或者你可以使用this来引用当前模型,使这个可重复使用(这是我们选择了

然后你就可以调用它是这样的:

App\Models; 

class Hairdresser extends Eloquent { 
    //scopeCloseTo function in here 
} 

最后,调用它:

$hairdressers = Hairdresser::closeTo($location, 10); 

这会发现所有Hairdressers10公里您$location的。

+0

这是我的功能 public function scopeCloseTo($ query,$ lat,$ lon,$ radius) { $ haversine =“ACOS(SIN(RADIANS('lat'))* SIN(RADIANS($ lat))+ COS(RADIANS ('lat')) * COS(RADIANS($ lat))* COS(RADIANS('lon') - RADIANS($ lon)))* 6380“; return $ query - > join('profiles','users.id','=','profiles.user_id') - > select(['users.name','users.email',' ('{$ haversine} <?“,[$ radius]);}其中, } –

+0

这没有给我结果。我做错了什么。在拉拉维尔5.2中是否存在whereraw和selectraw?我的表名是地方。我的模特名字是地方。它的属性是lat和lon –

+0

@JunaidMasood这些方法肯定存在于Laravel 5.2中我们选择使用'whereRaw'和'selectRaw'去选择上面的路线,以避免与paginatination(和其他)工厂不匹配的冲突(作为附注 - 这将在Laravel 5.3中修复)。你的'haversine'实现和我的不一样,但是你的表名'lat'和'lon'不正确。它应该是'place.lat'和'place.lon',你也应该在你的' - > select([...,place.lon,place.lat,.... users.name ,用户。电子邮件' – Ohgodwhy