zl程序教程

您现在的位置是:首页 >  其他

当前栏目

PHP 通过经纬度计算距离

2023-03-07 09:47:16 时间

封装的方法:

传递参数:

地址1的纬度:lat1  ,经度:lng1,

地址2的纬度   lat2  ,经度:lng2,

/**
     * 计算两个经纬度距离
     */
    public function get_distance($lat1, $lng1, $lat2, $lng2){ 
        $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; 
        return round($calculatedDistance); 
    }

调用示例

$latitude=$this->request->param('latitude',39.4);//纬度
$longitude=$this->request->param('longitude',116);//经度
$distance=get_distance($latitude, $longitude, $v['latitude'], $v['longitude']);#计算2个坐标的距离

未经允许不得转载:肥猫博客 » PHP 通过经纬度计算距离