【问题标题】:How to Calculate Distance in laravel using lat long如何使用 lat long 在 laravel 中计算距离
【发布时间】:2018-11-01 02:55:31
【问题描述】:

如何在 laravel5.5 中使用 SQL 查询计算距离? 我的代码在下面提到。

$specialProducts = Products::select('products.id', 'products.name', 'products.product_img', 'products.slug', 'products.price','products.lat','(3959 * ACOS(COS(RADIANS($lat))* COS(RADIANS(22.2765097))* COS(RADIANS(70.792523) - RADIANS(70.7583265))+ SIN(RADIANS(22.2897874))* SIN(RADIANS(22.2765097)))) AS distance')
            ->join('subcategories', 'subcategories.id', '=', 'products.sub_category_id')
            ->join('categories', 'categories.id', '=', 'subcategories.category_id')
            ->join('store', 'store.id', '=', 'products.store_id')
            ->where('products.status', 1)
            ->where('products.special', 1)

            ->orderBy('products.created_at', 'DESC')
            ->get();

【问题讨论】:

  • @martinstoeckli 是的兄弟
  • 你的经纬度值在哪里??
  • 22.2765097 / 70.792523 添加静态值

标签: laravel laravel-5.5


【解决方案1】:

如果您的数据库中有纬度和经度值,那么您可以使用 SQl 查询获取它们之间的距离,如下例所示,使用带有 DB:raw() 的原始 SQL。

$lat = 41.118491 // user's latitude
$lng = 25.404509 // user's longitude

SELECT *, 
( 6371 * acos( cos( radians($lat) ) 
* cos( radians( latitude ) ) 
* cos( radians( longitude ) - radians($lng) ) + sin( radians($lat) ) 
* sin( radians( latitude ) ) ) ) 
AS calculated_distance 
FROM settings as T 
HAVING calculated_distance <= (SELECT distance FROM settings WHERE sid=T.sid) 
ORDER BY distance_calc

如果您想以英里而不是公里为单位获取距离,请将 6371 替换为 3959。

计算过程可能需要很长时间,因此您可能需要缓存结果以备下次使用。

【讨论】:

    【解决方案2】:

    最好用php而不是mysql。在这里查看我的回复。 https://stackoverflow.com/a/50040011/1262144

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-31
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多