Created
April 1, 2019 09:35
-
-
Save lukecurtis93/aa900483a1c7dc875c7d5b684382ee8a to your computer and use it in GitHub Desktop.
Simple Geosearch in Laravel
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
/** | |
* Scope to query the database to return the listings between | |
* a latitude and longitude, with distance. | |
* | |
* @param \Illuminate\Database\Eloquent\Builder $query | |
* @param Double $lat | |
* @param Double $lng | |
* @param Integer $radius - KM | |
* @return \Illuminate\Database\Eloquent\Builder | |
*/ | |
public function scopeAroundLatLng($query, $lat, $lng, $radius) | |
{ | |
// earth's radius in km = ~6371 | |
$earth_radius = 6371; | |
// latitude boundaries | |
$maxlat = $lat + rad2deg($radius / $earth_radius); | |
$minlat = $lat - rad2deg($radius / $earth_radius); | |
// longitude boundaries (longitude gets smaller when latitude increases) | |
$maxlng = $lng + rad2deg($radius / $earth_radius / cos(deg2rad($lat))); | |
$minlng = $lng - rad2deg($radius / $earth_radius / cos(deg2rad($lat))); | |
return $query->whereBetween('lat', [$minlat, $maxlat])->whereBetween('lng', [$minlng, $maxlng]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment