2012-08-02 88 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

相关问题