Skip to content

Instantly share code, notes, and snippets.

@lukecurtis93
Created April 1, 2019 09:35
Show Gist options
  • Save lukecurtis93/aa900483a1c7dc875c7d5b684382ee8a to your computer and use it in GitHub Desktop.
Save lukecurtis93/aa900483a1c7dc875c7d5b684382ee8a to your computer and use it in GitHub Desktop.
Simple Geosearch in Laravel
/**
* 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