转换城市&;国家坐标点


Converting City&Country to Coordinate points

有没有相当快的php代码可以将城市+国家转换为纬度和经度坐标。我有一个位置列表,我需要将它们转换为坐标。我试着用javascript做这件事,但在试图将结果返回到php以将其存储在JSON文件中时遇到了一些问题。那么,有什么高效的PHP代码可以做到这一点吗?

谢谢。

在我的应用程序中,我使用以下函数使用谷歌服务对位置进行地理编码。该函数将一个参数location转换为地理代码(例如"Boston,USA"或"SW1 1AA,United Kingdom"),并返回一个带有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;
}