2016-07-27 28 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