Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enniosousa/c2aef7aedc214ace55ee05c0d89e09ca to your computer and use it in GitHub Desktop.
Save enniosousa/c2aef7aedc214ace55ee05c0d89e09ca to your computer and use it in GitHub Desktop.
Laravel (Illuminate) query builder scope to list neighboring locations within a given distance from a given location
<?php
/**
* Query builder scope to list neighboring locations
* within a given distance from a given location
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param mixed $lat Lattitude of given location
* @param mixed $lng Longitude of given location
* @param integer $radius Optional distance
* @param string $unit Optional unit
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeDistance($query, $lat, $lng, $radius = 100, $unit = "km")
{
$unit = ($unit === "km") ? 6378.10 : 3963.17;
$lat = (float) $lat;
$lng = (float) $lng;
$radius = (double) $radius;
return $query->having('distance','<=',$radius)
->select(DB::raw("*,
($unit * ACOS(COS(RADIANS($lat))
* COS(RADIANS(latitude))
* COS(RADIANS($lng) - RADIANS(longitude))
+ SIN(RADIANS($lat))
* SIN(RADIANS(latitude)))) AS distance")
)->orderBy('distance','asc');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment