Skip to content

Instantly share code, notes, and snippets.

@LarryBarker
Created August 17, 2020 03:47
Show Gist options
  • Save LarryBarker/101bf047bf63f64abbc5956821c578a2 to your computer and use it in GitHub Desktop.
Save LarryBarker/101bf047bf63f64abbc5956821c578a2 to your computer and use it in GitHub Desktop.
MySQL lat/lng coordinate search
/**
* Scope locations near a pair of coordinates
*
* @param Builder $query
* @param float $int
* @param float $lng
*/
public function scopeIsNear($query, $lat, $lng)
{
$statement = sprintf("id, name, street, locality, region, postal_code, country, website, phone, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance",
$lat,
$lng,
$lat);
$query->selectRaw($statement);
}
/**
* Scope locations within a given radius
*
* @param Builder $query
* @param string $column
* @param int $distance
*/
public function scopeIsWithinRadius($query, int $radius = 10)
{
$query->having('distance', '<', $radius);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment