【问题标题】:how to search all the location for given distance and given latitude and longitude in laravel如何在laravel中搜索给定距离和给定纬度和经度的所有位置
【发布时间】:2016-05-16 15:34:38
【问题描述】:
这是我的情景:
我通过以下方式将商店详细信息保存在 mysql 数据库中。
店铺名称、纬度、经度、
现在如果有人给出他的位置在纬度和经度上的距离(比如 5 公里),我需要填写他 5 公里内的所有商店,
此处用户为中心,半径为 5 公里,我需要找到该圈内的所有商店,我的应用程序是在 laravel 5.1 中开发的
我尝试关注这个code,但它不起作用。
谁能帮帮我。
【问题讨论】:
标签:
php
mysql
google-maps
geolocation
laravel-5.1
【解决方案1】:
您可以在模型中添加以下代码
public function ScopeDistance($query,$from_latitude,$from_longitude,$distance)
{
// This will calculate the distance in km
// if you want in miles use 3959 instead of 6371
$raw = \DB::raw('ROUND ( ( 6371 * acos( cos( radians('.$from_latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$from_longitude.') ) + sin( radians('.$from_latitude.') ) * sin( radians( latitude ) ) ) ) ) AS distance');
return $query->select('*')->addSelect($raw)->orderBy( 'distance', 'ASC' )->groupBy('distance')->having('distance', '<=', $distance);
}
你可以用它来做这样的事情
$ads = Ad::with(['user','photos'])->distance($from_latitude,$from_longitude,$distance)->get();
【解决方案3】:
微调参数。我给出了 0.50,但您可以选择更小的值,以减少覆盖区域。
$latitude = \Input::get('latitude');
$longitude = \Input::get('longitude');
$upper_latitude = $latitude + (.50); //Change .50 to small values
$lower_latitude = $latitude - (.50); //Change .50 to small values
$upper_longitude = $longitude + (.50); //Change .50 to small values
$lower_longitude = $longitude - (.50); //Change .50 to small values
$result = \DB::table('table')
->whereBetween('geo_locations.latitude', [$lower_latitude, $upper_latitude])
->whereBetween('geo_locations.logitude', [$lower_longitude, $upper_longitude])
->get();