php根据坐标计算距离

//获取2点之间的距离
function GetDistance($lat1, $lng1, $lat2, $lng2){ 
    $radLat1 = $lat1 * (PI / 180);
    $radLat2 = $lat2 * (PI / 180);
   
    $a = $radLat1 - $radLat2; 
    $b = ($lng1 * (PI / 180)) - ($lng2 * (PI / 180)); 
   
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1)*cos($radLat2)*pow(sin($b/2),2))); 
    $s = $s * EARTH_RADIUS; 
    $s = round($s * 10000) / 10000; 
    return $s; 

}



### 如何通过经纬度坐标计算两点间距离 计算两点之间基于经纬度的距离,通常使用球面三角学公式。以下是几种常见的方法及其对应的公式和代码实现。 #### 1. Haversine 公式 Haversine 公式是一种常用的地理距离计算方法,适用于短距离计算。该公式考虑了地球的球形特性,并通过弧度计算两点之间的最短路径(大圆距离)[^2]。 公式如下: \[ a = \sin^2\left(\frac{\Delta \text{lat}}{2}\right) + \cos(\text{lat}_1) \cdot \cos(\text{lat}_2) \cdot \sin^2\left(\frac{\Delta \text{lon}}{2}\right) \] \[ c = 2 \cdot \arctan2\left(\sqrt{a}, \sqrt{1-a}\right) \] \[ d = R \cdot c \] 其中: - \(R\) 是地球半径(通常取平均值 6371 km)。 - \(\Delta \text{lat} = \text{lat}_2 - \text{lat}_1\),纬度差。 - \(\Delta \text{lon} = \text{lon}_2 - \text{lon}_1\),经度差。 Python 示例代码: ```python from math import radians, sin, cos, sqrt, atan2 def haversine(lat1, lon1, lat2, lon2): # 将角度转换为弧度 lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2]) # 计算差值 dlat = lat2 - lat1 dlon = lon2 - lon1 # 应用 Haversine 公式 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = 6371 * c # 地球半径约为 6371 km return distance # 示例调用 distance = haversine(40.7128, -74.0060, 34.0522, -118.2437) print(f"Distance using Haversine formula: {distance:.2f} km") ``` #### 2. Vincenty 公式 Vincenty 公式是另一种更精确的方法,适用于椭球体模型下的距离计算。虽然复杂度较高,但其精度优于 Haversine 公式[^3]。 Python 示例代码(使用 `geopy` 库): ```python from geopy.distance import geodesic def calculate_distance_with_geopy(lat1, lon1, lat2, lon2): point1 = (lat1, lon1) point2 = (lat2, lon2) distance = geodesic(point1, point2).kilometers return distance # 示例调用 distance = calculate_distance_with_geopy(34.052235, -118.243683, 40.712776, -74.005974) print(f"Distance using Vincenty formula: {distance:.2f} km") ``` #### 3. PHP 实现 在 PHP 中,可以通过以下代码实现 Haversine 公式的计算[^4]: ```php function calculateDistance($lat1, $lon1, $lat2, $lon2) { $earthRadius = 6371; // 地球半径,单位:千米 $dLat = deg2rad($lat2 - $lat1); $dLon = deg2rad($lon2 - $lon1); $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); $distance = $earthRadius * $c; return round($distance, 2); // 返回两位小数 } // 示例调用 $distance = calculateDistance(40.7128, -74.0060, 34.0522, -118.2437); echo "Distance: $distance km"; ``` ### 注意事项 - Haversine 公式假设地球是一个完美的球体,因此可能存在一定的误差。 - Vincenty 公式基于 WGS-84 椭球模型,适合更高精度的需求。 - 在实际应用中,应根据需求选择合适的公式或库函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值