【问题标题】: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();
    

    【讨论】:

      【解决方案2】:

      看看这个: Calculate distance given 2 points, latitude and longitude

      对于问题的代码部分,我认为最快的方法是将计算分成两部分。

      首先我们从坐标中构建一个 5x5km 的正方形,然后在 laravel 中使用 whereBetween 子句选择其中的每一家商店。

      您使用链接中的公式计算精确距离。 基本上它的 5 =

      只需将 (latitude1-latitude2) 和 (longitude1-longitude2) 转换为公里 :)

      【讨论】:

        【解决方案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();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-07-12
          • 1970-01-01
          • 2011-06-29
          • 2013-06-06
          • 2011-11-05
          • 2011-08-28
          • 2012-06-22
          相关资源
          最近更新 更多