-
-
Save goosechaser/07dbf28818cedc1c9bb5 to your computer and use it in GitHub Desktop.
Eloquent with raw query in Lararavel: geolocation by latitude, longitude and radius.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MODEL | |
public function scopeDistance($query, $lat, $lng, $radius, $unit = "km") | |
{ | |
$unit = ($unit === "km") ? 6378.10 : 3963.17; | |
$lat = (float) $lat; | |
$lng = (float) $lng; | |
$radius = (double) $radius; | |
return $query->select(DB::raw("* | |
FROM ( | |
SELECT *, | |
($unit * ACOS(COS(RADIANS($lat)) | |
* COS(RADIANS(lat)) | |
* COS(RADIANS($lng) - RADIANS(lng)) | |
+ SIN(RADIANS($lat)) | |
* SIN(RADIANS(lat)))) AS distance") | |
) | |
->whereRaw("lat | |
BETWEEN $lat - ($radius / 69) | |
AND $lat + ($radius / 69) | |
AND lng | |
BETWEEN $lng - ($radius / (69 * COS(RADIANS($lat)))) | |
AND $lng + ($radius / (69 * COS(RADIANS($lat)))) | |
) d WHERE distance <= $radius"); | |
} | |
// CONTROLLER | |
$items = Model::distance($lat, $lng, $radius, "km") | |
->orderBy("distance") | |
->get(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment