这是范围实现了一个Haversine 公式搜索,对速度进行了额外的优化,在此处记录。
我希望有一种更简洁的方法从查询对象中获取原始 SQL,但不幸toSql()
的是在占位符被替换之前返回 SQL,所以我依赖于几个*Raw
调用。这不是太糟糕,但我希望它更清洁。
该代码假定您有列lat
并且lng
在您的表中。
const DISTANCE_UNIT_KILOMETERS = 111.045;
const DISTANCE_UNIT_MILES = 69.0;
/**
* @param $query
* @param $lat
* @param $lng
* @param $radius numeric
* @param $units string|['K', 'M']
*/
public function scopeNearLatLng($query, $lat, $lng, $radius = 10, $units = 'K')
{
$distanceUnit = $this->distanceUnit($units);
if (!(is_numeric($lat) && $lat >= -90 && $lat <= 90)) {
throw new Exception("Latitude must be between -90 and 90 degrees.");
}
if (!(is_numeric($lng) && $lng >= -180 && $lng <= 180)) {
throw new Exception("Longitude must be between -180 and 180 degrees.");
}
$haversine = sprintf('*, (%f * DEGREES(ACOS(COS(RADIANS(%f)) * COS(RADIANS(lat)) * COS(RADIANS(%f - lng)) + SIN(RADIANS(%f)) * SIN(RADIANS(lat))))) AS distance',
$distanceUnit,
$lat,
$lng,
$lat
);
$subselect = clone $query;
$subselect
->selectRaw(DB::raw($haversine));
// Optimize the query, see details here:
// http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/
$latDistance = $radius / $distanceUnit;
$latNorthBoundary = $lat - $latDistance;
$latSouthBoundary = $lat + $latDistance;
$subselect->whereRaw(sprintf("lat BETWEEN %f AND %f", $latNorthBoundary, $latSouthBoundary));
$lngDistance = $radius / ($distanceUnit * cos(deg2rad($lat)));
$lngEastBoundary = $lng - $lngDistance;
$lngWestBoundary = $lng + $lngDistance;
$subselect->whereRaw(sprintf("lng BETWEEN %f AND %f", $lngEastBoundary, $lngWestBoundary));
$query
->from(DB::raw('(' . $subselect->toSql() . ') as d'))
->where('distance', '<=', $radius);
}
/**
* @param $units
*/
private function distanceUnit($units = 'K')
{
if ($units == 'K') {
return static::DISTANCE_UNIT_KILOMETERS;
} elseif ($units == 'M') {
return static::DISTANCE_UNIT_MILES;
} else {
throw new Exception("Unknown distance unit measure '$units'.");
}
}
这可以这样使用:
$places->NearLatLng($lat, $lng, $radius, $units);
$places->orderBy('distance');
生成的 SQL 大致如下所示:
select
*
from
(
select
*,
(
'111.045' * DEGREES(
ACOS(
COS(
RADIANS('45.5088')
) * COS(
RADIANS(lat)
) * COS(
RADIANS('-73.5878' - lng)
) + SIN(
RADIANS('45.5088')
) * SIN(
RADIANS(lat)
)
)
)
) AS distance
from
`places`
where lat BETWEEN 45.418746 AND 45.598854
and lng BETWEEN -73.716301 AND -73.459299
) as d
where `distance` <= 10
order by `distance` asc