【PHP】经纬度计算距离,按距离排序

6 篇文章 0 订阅

方式一:PHP

/**
     *求两个已知经纬度之间的距离,单位为千米(测试)
     *@param lng1,lng2 经度
     *@param lat1,lat2 纬度
     *@return float 距离,单位千米
     **/
    public function getDistance($lng1, $lat1, $lng2, $lat2)
    {
    方法一:
        // $earthRadius = 6367000; //approximate radius of earth in meters 
        // $lat1 = ($lat1 * pi()) / 180;
        // $lng1 = ($lng1 * pi()) / 180;
        // $lat2 = ($lat2 * pi()) / 180;
        // $lng2 = ($lng2 * pi()) / 180;
        // $calcLongitude = $lng2 - $lng1;
        // $calcLatitude = $lat2 - $lat1;
        // $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        // $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        // $calculatedDistance = $earthRadius * $stepTwo;

        // if ($calculatedDistance < 1000) return $calculatedDistance . '米';
        // if ($calculatedDistance >= 1000) return $calculatedDistance / 1000 . '公里';
        // return round($calculatedDistance); // 0.34092299665475米

    方法二:
        $EARTH_RADIUS = 6378.137;
        $radLat1 = $this->rad($lat1);
        $radLat2 = $this->rad($lat2);
        $a = $radLat1 - $radLat2;
        $b = $this->rad($lng1) - $this->rad($lng2);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $EARTH_RADIUS * 1000;

        if ($s < 1000) return round($s, 2) . '米';
        if ($s >= 1000) return round($s / 1000, 2) . '公里';
    }

    private function rad($d)
    {
        return $d * M_PI / 180.0;
    }

方式二:SQL

$arr = Db::select('SELECT *, (2 * 6378.137 * ASIN(SQRT(POW(SIN(PI() * (' . $lng . ' - longitude) / 360),2) + COS(PI() * 39.916527 / 180) * COS(latitude * PI() / 180) * POW(SIN(PI() * (' . $lat . ' - latitude) / 360),
        2)))) AS distance FROM f_dining WHERE dining_status = 1 AND is_delete = 1 ORDER BY distance ASC');
            $res = json_decode(json_encode($arr), true);

            if ($res) {
                foreach ($res as &$v) {
                    if ($v['distance'] < 1) {
                        $v['distance'] = round($v['distance'] * 1000) . '米';
                    } else {
                        $v['distance'] = round($v['distance']) . '公里';
                    }
                }
            }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值