php計算兩個座標(經度,緯度)之間距離的方法

來源:互聯網
上載者:User

例子一

function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
 $pi80 = M_PI / 180;
 $lat1 *= $pi80;
 $lng1 *= $pi80;
 $lat2 *= $pi80;
 $lng2 *= $pi80;
 $r = 6372.797;
 $dlat = $lat2 - $lat1;
 $dlng = $lng2 - $lng1;
 $a = sin($dlat/2)*sin($dlat/2)+cos($lat1)*cos($lat2)*sin($dlng/2)*sin($dlng/2);
 $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
 $km = $r * $c;
 return ($miles ? ($km * 0.621371192) : $km);
}

例子二

/**
 * 計算兩個座標之間的距離(米)
 * @param float $fP1Lat 起點(緯度)
 * @param float $fP1Lon 起點(經度)
 * @param float $fP2Lat 終點(緯度)
 * @param float $fP2Lon 終點(經度)
 * @return int
 */ 
function distanceBetween($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon){ 
    $fEARTH_RADIUS = 6378137; 
    //角度換算成弧度 
    $fRadLon1 = deg2rad($fP1Lon); 
    $fRadLon2 = deg2rad($fP2Lon); 
    $fRadLat1 = deg2rad($fP1Lat); 
    $fRadLat2 = deg2rad($fP2Lat); 
    //計算經緯度的差值 
    $fD1 = abs($fRadLat1 - $fRadLat2); 
    $fD2 = abs($fRadLon1 - $fRadLon2); 
    //距離計算 
    $fP = pow(sin($fD1/2), 2) + 
          cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2/2), 2); 
    return intval($fEARTH_RADIUS * 2 * asin(sqrt($fP)) + 0.5); 

/**
 * 百度座標系轉換成標準GPS坐系
 * @param float $lnglat 座標(如:106.426, 29.553404)
 * @return string 轉換後的標準GPS值:
 */ 
function BD09LLtoWGS84($fLng, $fLat){ // 經度,緯度 
    $lnglat = explode(',', $lnglat); 
    list($x,$y) = $lnglat; 
    $Baidu_Server = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x={$x}&y={$y}"; 
    $result = @file_get_contents($Baidu_Server); 
    $json = json_decode($result); 
    if($json->error == 0){ 
        $bx = base64_decode($json->x); 
        $by = base64_decode($json->y); 
        $GPS_x = 2 * $x - $bx; 
        $GPS_y = 2 * $y - $by; 
        return $GPS_x.','.$GPS_y;//經度,緯度 
    }else 
        return $lnglat; 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.