2012-08-02 62 views
1

我目前使用以下方法從GoogleMaps獲取座標。 我可以寫這個更短/更高效嗎?從GoogleMaps獲取地理座標有沒有更簡單/更簡單的方法?

EDIT 2013年6月21日

截至目前老Google Geocoding API關閉。這是我修改後的代碼,可與最新版本一起使用。我更新了這篇文章,如果有人絆倒了它並發現它有用。

public function getGeographicCoordinatesFromGoogle() 
{ 
    // create address string 
    $value = $this->address_line_1 . ' ' . 
      $this->postal_code . ' ' . 
      $this->city . ' ' . 
      $this->country; 
    $value = preg_replace('!\s+!', '+', $value); 

    // create request 
    $request = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' . 
       $value . '&sensor=false'; 

    // get value from xml request 
    $xml = file_get_contents($request); 
    $doc = new \DOMDocument('1.0', 'UTF-8'); 
    @$doc->loadXML($xml); 

    // fetch result 
    $result = $doc->getElementsByTagName('lat')->item(0)->nodeValue . ',' . 
       $doc->getElementsByTagName('lng')->item(0)->nodeValue; 

    // check result 
    if (!preg_match('/(-?\d+\.\d+),(-?\d+\.\d+)/', $result)) { 
     $result = null; 
    } 
    // assign value 
    $this->setGeographicCoordinates($result); 
} 

回答

0

我建議您使用http_build_query()而不是試圖用正則表達式來構建SearchQuery。還有其他的字符需要逃脫。

這是一個相當長的方法。也許有一個類只處理與GoogleMaps的通信(類GeoBackend和方法getGeoDataForAddress(),它會返回一個GeoData對象,可能會要求座標等)。

1

您可以改用json的XML。 json是更新,輕量級和麪向對象的。

+0

+1是的,今天我看到了JSON支持,當我切換到新的API。我認爲老一代不支持它,我想我會繼續這樣做。 – insertusernamehere 2013-06-21 09:55:44

相關問題