1

我目前正在使用以下方法从 GoogleMaps 获取坐标。我可以写这个更短/更有效吗?

编辑 21.06.2013

截至目前,旧的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);
}
4

2 回答 2

1

您可以使用 json 代替 xml。json 是更新的、轻量级的和面向对象的。

于 2013-06-21T09:45:46.087 回答
0

我建议您使用 http_build_query() 而不是尝试使用 Regex 构建 SearchQuery。还有其他需要转义的字符。

这是一个相当长的方法。也许有一个只处理与 GoogleMaps 的通信的类是有意义的(类 GeoBackend 带有方法 getGeoDataForAddress(),它返回一个 GeoData-Object,可以要求它提供坐标等)

于 2012-10-11T13:50:20.580 回答