2012-03-09 36 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