php 两地经纬度获取距离

composer require jeroendesloovere/distance
<?php

namespace LonLatFilterShop;

use JeroenDesloovere\Distance\Distance;
use think\Exception;

class LonLatFilterShop
{
    /**
     * @param []起点位置经纬度
     * @param []终点位置经纬度
     * @return float
     * @throws Exception
     */
    public static function KM($position1=[],$position2=[]){
        if(!isset($position1[0]) || ($position1[0]==='')){
            throw new Exception("起点位置的经度不能为空");
        }
        if(!isset($position1[1]) || ($position1[1]==='')){
            throw new Exception("起点位置的经度不能为空");
        }
        if(!isset($position2[0]) || ($position2[0]==='')){
            throw new Exception("起点位置的经度不能为空");
        }
        if(!isset($position2[1]) || ($position2[1]==='')){
            throw new Exception("终点位置的经度不能为空");
        }
        $latitude1 = $position1[1]; #纬度
        $longitude1 = $position1[0]; #经度
        $latitude2 = $position2[1]; #纬度
        $longitude2 = $position2[0];#经度
        $distance = Distance::between(
            $latitude1,
            $longitude1,
            $latitude2,
            $longitude2
        );
        return $distance;
    }


    /**
     * @param []当前位置经纬度
     * @param $data 要过滤的数组 [['lon'=>经度,'lat'=>纬度]]
     * @param $filterDistance 大于多少公里不展示
     * @return 返回 $data
     */
    public static function filterShop($position=[],$data,$filterDistance=0){
        if(!isset($position[0]) || ($position[0]==='')){
            throw new Exception("起点位置的经度不能为空");
        }
        if(!isset($position[1]) || ($position[1]==='')){
            throw new Exception("起点位置的经度不能为空");
        }
        if(!$data){
            return [];
        }
        $filterShop = [];
        foreach ($data as $k =>$v){
//            [['lon'=>经度,'lat'=>纬度]]
            if(!isset($v['lon']) || ($v['lon']==='')){
                continue;
            }
            if(!isset($v['lat']) || ($v['lat']==='')){
                continue;
            }
            /**
             * 距离位置
             */
            $kg = self::KM($position,[$v['lon'],$v['lat']]);
            if($filterDistance && ($kg>$filterDistance)){
                continue;
            }
            $v['distance']=$kg;
            $filterShop[] = $v;
        }
        if(!$filterShop){
            return [];
        }
        $edit = array_column($filterShop,'distance');
        array_multisort($edit,SORT_ASC,$filterShop);
        return $filterShop;
    }

}

 

posted @ 2022-12-26 17:28  酷酷的城池  阅读(23)  评论(0编辑  收藏  举报