”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 PHP 中使用纬度和经度计算半径内的距离?

如何在 PHP 中使用纬度和经度计算半径内的距离?

发布于2024-11-03
浏览:249

How to Calculate Distances within a Radius Using Latitude and Longitude in PHP?

根据纬度和经度计算距离

在此场景中,您要确定 15 英里半径内的点用户输入的坐标。为此,您可以利用数学公式来计算距离。

考虑以下 PHP 函数:

function get_distance($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') { 

    // Calculate the angle difference
    $theta = $longitude1 - $longitude2; 

    // Calculate the distance
    $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2)))   
                (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * 
                cos(deg2rad($theta))); 

    // Convert to degrees
    $distance = acos($distance); 
    $distance = rad2deg($distance); 

    // Convert to miles or kilometers
    $distance = $distance * 60 * 1.1515; 

    // Round the distance
    return (round($distance,2));
}

或者,您可以使用数据库查询来完成此操作:

$query = "SELECT *,(((acos(sin((".$latitude."*pi()/180)) * 
            sin((`Latitude`*pi()/180)) cos((".$latitude."*pi()/180)) * 
            cos((`Latitude`*pi()/180)) * cos(((".$longitude."- `Longitude`)* 
            pi()/180))))*180/pi())*60*1.1515
        ) as distance 
        FROM `MyTable` 
        HAVING distance > ".$distance.";
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3