PHP计算两个点的距离实现

两种方法,一个代码计算,一个redis计算

代码计算

/**
 * [getDistance description]根据两点的经纬度计算距离
 * @param  [type] $latitudeOne  [description]第一个点的纬度
 * @param  [type] $longitudeOne [description]第一个点的经度
 * @param  [type] $latitudeTwo  [description]第二个点的纬度
 * @param  [type] $longitudeTwo [description]第二个点的经度
 * @return [type]               [description]返回距离
 */
function getDistance($latitudeOne,$longitudeOne,$latitudeTwo,$longitudeTwo){
        $earthRadius = 6378137; //地球半径

        $latitudeOne = ($latitudeOne * pi()) / 180;
        $longitudeOne = ($longitudeOne * pi()) / 180;

        $latitudeTwo = ($latitudeTwo * pi()) / 180;
        $longitudeTwo = ($longitudeTwo * pi()) / 180;

        $calcLongitude = $longitudeTwo - $longitudeOne;
        $calcLatitude = $latitudeTwo - $latitudeOne;

        $stepOne = pow(sin($calcLatitude / 2),2) + cos($latitudeOne) * cos($latitudeTwo) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1,sqrt($stepOne)));
        $calculateDistance = $earthRadius * $stepTwo;

        $kilometer = round($calculateDistance / 1000,1); //得出的$calculateDistance是米为单位,这里除1000得到km,四舍五入到小数点一位数;

        return $kilometer;
}

$res = $this->getDistance(13.361389,38.115556,13.361389,38.125566);
var_dump($res); //答案是1.1

redis计算

$redis = new \redis();

$redis -> connect('127.0.0.1',6379);

$redis->geoAdd("address",13.361389,38.115556,'peter',13.361389,38.125566,'peter1');//添加位置
        
$redis->geoPos("address",'peter');//位置获取
        
$res = $redis->geoDist("address",'peter','peter1','km');//两点之间的距离

var_dump($res);//答案是1.1133

//ps:redis_version > 3.2

还有个redis LBS的技巧

//接redis计算代码
$potion=['WITHDIST','count'=>2,'ASC'];//空字符串 返回key,WITHCOORD 返回key和经纬度 WITHDIST 返回key和距离 count返回几条 ASC和DESC降序和升序

$res1 = $redis->geoRadius("address",13.361389,38.115556,'2','km',$potion); //m 米 km千米

var_dump($res1);

/***
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "peter"
    [1]=>
    string(6) "0.0001"
  }
  [1]=>
  array(2) {
    [0]=>
    string(6) "peter1"
    [1]=>
    string(6) "1.1134"
  }
}
***/

本文为ctexthuang原创文章,转载请注明来自ctexthuang_blog

tag(s): none
show comments · back · home
Edit with markdown
召唤看板娘