2012-03-09 67 views
0

是否有相當快的php代碼將城市+國家轉換爲經度和緯度座標。我有一個位置列表,我需要將它們轉換爲座標。我試着用javascript來做,但我遇到了一些問題,試圖將結果返回到PHP以將其存儲在我的JSON文件中。那麼有沒有高效的PHP代碼來做到這一點?將城市與國家轉換爲座標點

謝謝。

+0

您使用什麼服務進行地理編碼?谷歌?雅虎?兵?還有別的嗎? – 2012-03-09 17:04:42

回答

0

在我的應用程序中,我使用以下函數對使用Google服務的位置進行地理編碼。該函數將一個參數 - location用於地理編碼(例如「Boston,USA」或「SW1 1AA,英國」),並返回一個Lat/Lon關聯數組。如果發生錯誤或無法確定位置,則返回FALSE。

請注意,在許多情況下,城市+國家將無法唯一確定位置。例如,僅在美國就有100個城市被命名爲斯普林菲爾德。另外,在將國家傳送到地理編碼服務時,請務必輸入完整的國家/地區名稱,而不是雙字母代碼。我發現這很難:我通過'加拿大'的'CA'並得到了奇怪的結果。顯然,谷歌假設'CA'的意思是「加利福尼亞州」。

function getGeoLocationGoogle($location) 
{ 
    $url = "http://maps.googleapis.com/maps/api/geocode/xml?address=". urlencode($location) . "&sensor=false"; 
    $userAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 FirePHP/0.4"; 

    //Setup curl object and execute 
    $curl = curl_init($url); 
    curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); 
    curl_setopt($curl, CURLOPT_FAILONERROR, true); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
    $result = curl_exec($curl); 

    $req = $location; 

    //Process response from Google servers 
    if (($error = curl_errno($curl)) > 0) 
    { 
     return FALSE; 
    } 

    $geo_location = array(); 
    //Try to convert XML response into an object 
    try 
    { 
     $xmlDoc = new DOMDocument(); 
     $xmlDoc->loadXML($result); 
     $root = $xmlDoc->documentElement; 

     //get errors 
     $status = $root->getElementsByTagName("status")->item(0)->nodeValue; 
     if($status != "OK") 
     { 
      $error_msg = "Could not determine geographical location of $location - response code $status"; 
     } 
     $location = $root->getElementsByTagName("geometry")->item(0)->getElementsByTagName("location")->item(0); 
     if(!$location) 
     { 
      return FALSE; 
     } 

     $xmlLatitude = $location->getElementsByTagName("lat")->item(0); 
     $valueLatitude = $xmlLatitude->nodeValue; 
     $geo_location['Latitude'] = $valueLatitude; 

     //get longitude 
     $xmlLongitude = $location->getElementsByTagName("lng")->item(0); 
     $valueLongitude = $xmlLongitude->nodeValue; 
     $geo_location['Longitude'] = $valueLongitude; 

     //return location as well - for good measure 
     $geo_location['Location'] = $req; 
    } 
    catch (Exception $e) 
    { 
     return FALSE; 
    }  

    return $geo_location; 
} 
+0

我需要計算幾千個位置的座標,所以這個速度足夠快以至頁面不會超時? – ewein 2012-03-09 18:20:11

+0

如果您需要在幾千個位置上完成此操作,那麼很可能您的設計是錯誤的。你永遠不需要在飛行中執行那麼多的地理編碼請求。你想達到什麼目的? – 2012-03-09 19:31:01

+0

我正在創建地點之間的連接地圖。所以我有一個數據庫,我有我的位置存儲,我需要將這些位置轉換爲座標並將座標存儲到一個JSON文件。 – ewein 2012-03-11 00:24:46

相關問題