2015-09-25 135 views
0

所以我試圖讓使用PHP的座標之間的距離。 我使用這兩個功能:獲得兩個座標之間的距離公里

  1. 通過IP
  2. 定位用戶獲得與GPS圖像座標
通過IP我得到的緯度和經度從IP定位用戶

,並把它們放在$ LAT1和$ lon1

$ip = $_SERVER['REMOTE_ADDR']; 
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json")); 
$user_location = $details->loc; 
$pieces = explode(",", $user_location); 
$lat1 = $pieces[0]; 
$lon1 = $pieces[1]; 
$unit = "Km"; 

中獲取圖像我我選擇了行,他們都包含從EXIF的經度和緯度。

function get_image($db){ 
    $select = "id, image_name"; 
    $sql = "SELECT $select FROM images ORDER BY id DESC"; 
    $stmt = $db->prepare($sql); 
    $stmt->execute(); 
    $spot = $stmt->fetchAll(PDO::FETCH_ASSOC); 

    if(!$stmt -> rowCount()){ 
     echo "<div class='noSpots'> 
        <p>Sorry there seams to be nothing in your area</p> 
       </div>"; 
    } 
     return $spot; 
}//spots_narrow ends here 

所以在這兩個函數後,我現在可以返回四個變量與我想要計算兩個緯度和經度之間的距離。

- $ lat1 
- $ lon1 
- $ lat2 
- $ lon2 
+0

https://developers.google.com/maps/articles/phpsqlsearch_v3請參閱'使用MySQL查找位置' – chris85

回答

0

http://rosettacode.org/wiki/Haversine_formula#PHP

class POI { 
    private $latitude; 
    private $longitude; 
    public function __construct($latitude, $longitude) { 
     $this->latitude = deg2rad($latitude); 
     $this->longitude = deg2rad($longitude); 
    } 
    public function getLatitude() return $this->latitude; 
    public function getLongitude() return $this->longitude; 
    public function getDistanceInMetersTo(POI $other) { 
     $radiusOfEarth = 6371000;// Earth's radius in meters. 
     $diffLatitude = $other->getLatitude() - $this->latitude; 
     $diffLongitude = $other->getLongitude() - $this->longitude; 
     $a = sin($diffLatitude/2) * sin($diffLatitude/2) + 
      cos($this->latitude) * cos($other->getLatitude()) * 
      sin($diffLongitude/2) * sin($diffLongitude/2); 
     $c = 2 * asin(sqrt($a)); 
     $distance = $radiusOfEarth * $c; 
     return $distance; 
    } 
} 
1

你想看看Haversine Formula我並不熱衷於PHP,但在僞PHP代碼,這是怎麼一回事呢:

$EarthRadius = 6371000; // radius in meters 
$phi1 = deg2rad($lat1) 
$phi2 = deg2rad($lat2) 
$deltaLat = deg2rad($lat2 - $lat1) 
$deltaLon = deg2rad($lon2 - $lon1) 

var $a = sin($deltaLat/2) * sin($deltaLat/2) + cos($phi1) * cos($phi2) * sin($deltaLon/2) * sin($deltaLon/2); 
var $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); 

var $result = $EarthRadius * $c; 

你應該能夠在PHP Math模塊中找到cos,sin,atan2的等價公式。還有一些其他的近似值,但這應該工作得很好。

+0

上面的帖子會給你以米爲單位的距離。 –

+0

我不能縫使它工作?我應該將$ lat和$ lon轉換爲$ phi1和$ phi2嗎? – user3426191

+0

我正在編寫僞代碼。您的$ lat1之一將是我的lat1,$ lat2 - > lat2等等......您還可以使用deg2rad公式轉換爲弧度。例如: $ phi1 = deg2rad($ lat1); 我會更新帖子來解決這個問題。 –