Created
August 17, 2020 03:47
-
-
Save LarryBarker/101bf047bf63f64abbc5956821c578a2 to your computer and use it in GitHub Desktop.
MySQL lat/lng coordinate search
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 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